From abb94964d17440ef4a0d3307579f3388a11cf412 Mon Sep 17 00:00:00 2001 From: Josef Pihrt Date: Wed, 22 Jan 2025 21:24:48 +0100 Subject: [PATCH] Add file path validation --- .../Testing.Common/Testing/AdditionalFile.cs | 2 + .../Testing/FilePathVerifier.cs | 39 +++++++++++++++++++ src/Tests/Testing.Common/Testing/TestFile.cs | 2 + 3 files changed, 43 insertions(+) create mode 100644 src/Tests/Testing.Common/Testing/FilePathVerifier.cs diff --git a/src/Tests/Testing.Common/Testing/AdditionalFile.cs b/src/Tests/Testing.Common/Testing/AdditionalFile.cs index 59cba91ec5..40f9272353 100644 --- a/src/Tests/Testing.Common/Testing/AdditionalFile.cs +++ b/src/Tests/Testing.Common/Testing/AdditionalFile.cs @@ -21,6 +21,8 @@ public AdditionalFile(string source, string? expectedSource = null, string? path { Source = source ?? throw new ArgumentNullException(nameof(source)); ExpectedSource = expectedSource; + + FilePathVerifier.VerifyFilePath(path); Path = path; } diff --git a/src/Tests/Testing.Common/Testing/FilePathVerifier.cs b/src/Tests/Testing.Common/Testing/FilePathVerifier.cs new file mode 100644 index 0000000000..f88f90e252 --- /dev/null +++ b/src/Tests/Testing.Common/Testing/FilePathVerifier.cs @@ -0,0 +1,39 @@ +using System; +using System.IO; +using System.Linq; + +namespace Roslynator.Testing; + +internal static class FilePathVerifier +{ + private static readonly char[] _invalidPathChars = Path.GetInvalidPathChars(); + private static readonly char[] _invalidFileNameChars = Path.GetInvalidFileNameChars(); + + public static void VerifyFilePath(string? path) + { + if (path is null) + return; + + if (string.IsNullOrWhiteSpace(path)) + throw new ArgumentException("File path cannot be empty or contain only whitespace", nameof(path)); + + if (path.IndexOfAny(_invalidPathChars) >= 0) + throw new ArgumentException("File path contains invalid character(s)", nameof(path)); + + if (path[path.Length - 1] == Path.DirectorySeparatorChar + || path[path.Length - 1] == Path.AltDirectorySeparatorChar) + { + throw new ArgumentException("File path cannot end with directory separator", nameof(path)); + } + + var dirSeparatorIndex = FileSystemHelpers.LastIndexOfDirectorySeparator(path); + if (dirSeparatorIndex >= 0) + { + for (int i = dirSeparatorIndex + 1; i < path.Length; i++) + { + if (_invalidFileNameChars.Contains(path[i])) + throw new ArgumentException("File name contains invalid character(s)", nameof(path)); + } + } + } +} diff --git a/src/Tests/Testing.Common/Testing/TestFile.cs b/src/Tests/Testing.Common/Testing/TestFile.cs index 1ee705ce46..8d1d3310f8 100644 --- a/src/Tests/Testing.Common/Testing/TestFile.cs +++ b/src/Tests/Testing.Common/Testing/TestFile.cs @@ -9,6 +9,8 @@ public TestFile(string source, string? expectedSource = null, string? path = nul { Source = source; ExpectedSource = expectedSource; + + FilePathVerifier.VerifyFilePath(path); Path = path; }