diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-23 19:37:31 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-23 19:37:31 -0500 |
| commit | 746f7ceefa61e62ad801b825f80b87fe9c853c44 (patch) | |
| tree | 52afa6e3ee234950bbd338e3d086b682da277b58 | |
| parent | 0bc3f2e327d8ae9a8a0bd1058cb90c59c58933ee (diff) | |
| parent | 8870f4f5590373d54370e64c7b9081521245d8dc (diff) | |
| download | slskd-746f7ceefa61e62ad801b825f80b87fe9c853c44.tar.gz | |
Merge pull request #1740 from slskd/paths
Change path manipulation logic (again)
12 files changed, 809 insertions, 743 deletions
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f94b9c7b..f67af8d5 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -35,6 +35,7 @@ namespace slskd; using System; using System.IO; using System.Linq; +using System.Runtime.InteropServices; /// <summary> /// Utility functions to help safely work with paths from untrusted sources. @@ -50,7 +51,19 @@ public static class FileSafety /// <returns>The combined path.</returns> /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception> /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception> - public static string CombineSafely(string root, params string[] segments) + public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments); + + /// <summary> + /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// </summary> + /// <param name="root">The root directory.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <param name="segments">The segments to append.</param> + /// <returns>The combined path.</returns> + /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception> + /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception> + public static string CombineSafely(string root, OSPlatform? os, params string[] segments) { // ensure no inputs are null. matches the behavior of Path.Combine() if (string.IsNullOrWhiteSpace(root)) @@ -58,19 +71,41 @@ public static class FileSafety throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace"); } + if (ContainsTraversalSegments(root)) + { + throw new ArgumentException("Specified root directory contains path traversal segments", nameof(root)); + } + if (segments is null || segments.Any(s => s is null)) { throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } + var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows(); + foreach (var segment in segments) { // if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment // and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc" // not what we want! - if (IsPathAbsolute(segment)) + if (IsPathAbsolute(segment, os)) { - throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); + throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'"); + } + + if (isWindows) + { + if (segment.Contains(':')) + { + throw new ArgumentException($"Colons are not permitted in segments: '{segment}'"); + } + + // on Windows, a segment beginning with a slash is considered 'drive rooted' and something like + // "\foo" translates to "C:\foo" when passed to Path.Combine() + if (segment.StartsWith('\\') || segment.StartsWith('/')) + { + throw new ArgumentException($"Drive-relative segments or those containing leading slashes are not permitted in segments: '{segment}'"); + } } var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); @@ -79,16 +114,17 @@ public static class FileSafety // untrusted input could use this to "break out" of the root directory and access sensitive areas if (parts.Any(s => s is "." or "..")) { - throw new ArgumentException($"Path traversal is not permitted: '{segment}'"); + throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'"); } } var combined = Path.Combine(root, Path.Combine(segments)); - // not sure how we could possibly get here, but if we do, throw. + // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting + // path is actually rooted in the root we provided; if not the input was successful in traversal if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) { - throw new ArgumentException($"Path traversal detected in path {combined}, which is not allowed"); + throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } return combined; @@ -102,36 +138,46 @@ public static class FileSafety public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; /// <summary> - /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted), using - /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted) on the current + /// operating system. /// </summary> /// <remarks> /// This is necessary because the base library is opaque and untestable in a cross-platform way, so we are - /// implementing the nuclear option and merging the logic for Windows and non-Windows. + /// implementing the nuclear option and doing it ourselves. /// </remarks> /// <param name="path">The path to check.</param> + /// <param name="os">An optional operating system override, for testing.</param> /// <returns>True if the path is absolute, false otherwise.</returns> - public static bool IsPathAbsolute(string path) + public static bool IsPathAbsolute(string path, OSPlatform? os = null) { if (string.IsNullOrEmpty(path)) { return false; } - // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / - // Windows root-relative paths and UNC paths start with \ - if (path[0] is '/' or '\\') + if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows()) { - return true; + // Windows drive-letter path: X:\ or X:/ + // X:foo is relative on windows + if (path.Length >= 3 + && char.IsAsciiLetter(path[0]) + && path[1] == ':' + && (path[2] == '\\' || path[2] == '/')) + { + return true; + } + + // UNC path \\server\share + if (path.StartsWith("\\\\")) + { + return true; + } + + return false; } - // Windows drive-letter paths: X:\ or X:/ - // X:foo is a "drive relative" path so it doesn't _technically_ count, but - // it's questionable and the user probably intended to root it anyway - // this matches the built in IsPathRooted but not IsPathFullyQualified - if (path.Length >= 2 - && char.IsAsciiLetter(path[0]) - && path[1] == ':') + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / + if (path.StartsWith('/')) { return true; } @@ -140,10 +186,11 @@ public static class FileSafety } /// <summary> - /// Returns a value indicating whether the specified <paramref name="path"/>, using - /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// Returns a value indicating whether the specified <paramref name="path"/> is relative on the current + /// operating system. /// </summary> /// <param name="path">The path to check.</param> + /// <param name="os">An optional operating system override, for testing.</param> /// <returns>True if the path is relative, false otherwise.</returns> - public static bool IsPathRelative(string path) => !IsPathAbsolute(path); + public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); }
\ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 1999220f..eb1c9069 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,19 +33,31 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; + using System.Runtime.InteropServices; /// <summary> /// Validates that the specified path is absolute. /// </summary> public class AbsolutePathAttribute : ValidationAttribute { + public AbsolutePathAttribute() + { + } + + public AbsolutePathAttribute(OSPlatform? os = null) + { + OS = os; + } + + public OSPlatform? OS { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path)) + if (!FileSafety.IsPathAbsolute(path, os: OS)) { return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 64e418b1..f465ba98 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,19 +33,30 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; + using System.Runtime.InteropServices; /// <summary> /// Validates that the specified path is relative. /// </summary> public class RelativePathAttribute : ValidationAttribute { + public RelativePathAttribute() + { + } + + public RelativePathAttribute(OSPlatform? os = null) + { + OS = os; + } + + public OSPlatform? OS { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathRelative(path)) + if (!FileSafety.IsPathRelative(path, os: OS)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 4b281863..3b304d99 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -79,6 +79,17 @@ namespace slskd.Files { ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + if (Path.GetFullPath(filename) != filename) + { + throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); + } + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename)); + } + FileInfo info; try @@ -153,11 +164,22 @@ namespace slskd.Files /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception> public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories) { + if (directories is null or [] || directories.Any(directory => string.IsNullOrEmpty(directory))) + { + throw new ArgumentException("One or more directories are null or empty"); + } + if (directories.Any(directory => Path.GetFullPath(directory) != directory)) { throw new ArgumentException("Only absolute paths may be specified", nameof(directories)); } + if (directories.Any(directory => FileSafety.ContainsTraversalSegments(directory))) + { + Log.Warning("Suspicious attempt to delete a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directories: {Directories}", string.Join(", ", directories)); + throw new ArgumentException("Directories containing traversal segments are not allowed", nameof(directories)); + } + if (directories.Any(directory => AllowedDirectories.Contains(directory))) { throw new ArgumentException("Deletion of application-controlled directory roots is not supported"); @@ -216,11 +238,22 @@ namespace slskd.Files /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception> public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files) { + if (files is null or [] || files.Any(file => string.IsNullOrWhiteSpace(file))) + { + throw new ArgumentException("One or more files are null or empty", nameof(files)); + } + if (files.Any(file => Path.GetFullPath(file) != file)) { throw new ArgumentException("Only absolute paths may be specified", nameof(files)); } + if (files.Any(file => FileSafety.ContainsTraversalSegments(file))) + { + Log.Warning("Suspicious attempt to delete a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file(s): {File}", string.Join(", ", files)); + throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(files)); + } + // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed); @@ -269,15 +302,23 @@ namespace slskd.Files /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { + ArgumentException.ThrowIfNullOrWhiteSpace(directory); + if (Path.GetFullPath(directory) != directory) { throw new ArgumentException("Only absolute paths may be specified", nameof(directory)); } + if (FileSafety.ContainsTraversalSegments(directory)) + { + Log.Warning("Suspicious attempt to list a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directory: {Directory}", directory); + throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(directory)); + } + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' - if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed))) + if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed + Path.DirectorySeparatorChar) || directory == allowed)) { - throw new UnauthorizedException($"Only application-controlled directories can be deleted"); + throw new UnauthorizedException($"Only application-controlled directories can be listed"); } if (!Directory.Exists(directory)) @@ -340,6 +381,12 @@ namespace slskd.Files { ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to create a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed"); + } + var path = Path.GetDirectoryName(filename); UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); @@ -411,6 +458,12 @@ namespace slskd.Files ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); + if (FileSafety.ContainsTraversalSegments(sourceFilename) || FileSafety.ContainsTraversalSegments(destinationDirectory)) + { + Log.Warning("Suspicious attempt to move a file with either a source filename or destination directory name containing unsafe path segments (one or more of path traversal characters '.' and '..'). Source: {Source}, Destination: {Destination}", sourceFilename, destinationDirectory); + throw new ArgumentException("Filenames and directories containing traversal segments are not allowed"); + } + if (!File.Exists(sourceFilename)) { throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs new file mode 100644 index 00000000..2d496c4b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -0,0 +1,242 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class CombineSafelyTests + { + public static string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; + public static string ExpectedStartsWith = Base + Path.DirectorySeparatorChar; + + [Theory] + [InlineData(null)] + [InlineData(" ")] + public void Throws_ArgumentException_Given_NullOrWhiteSpaceRoot(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentNullException>(ex); + } + + [Theory] + [InlineData("foo/../bar")] + [InlineData("foo\\..\\bar")] + public void Throws_ArgumentException_Given_TraversingRoot(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Fact] + public void Returns_Root_Given_No_Segments() + { + var result = FileSafety.CombineSafely(Base); + + Assert.StartsWith(ExpectedStartsWith.TrimEnd(Path.DirectorySeparatorChar), result); + } + + [Fact] + public void Drops_Empty_Segments() + { + var result = FileSafety.CombineSafely(Base, string.Empty, "foo", string.Empty, "bar"); + + Assert.StartsWith(ExpectedStartsWith, result); + Assert.EndsWith(Path.Combine("foo", "bar"), result); + } + + [Fact] + public void Throws_Given_Null_Segment() + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, "foo", null, "bar")); + + Assert.NotNull(ex); + Assert.IsType<ArgumentNullException>(ex); + } + + [Fact] + public void Throws_Given_Null_Segments() + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, segments: null)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentNullException>(ex); + } + + [Fact] + public void SingleSegment_ReturnsBaseAndSegment() + { + var result = FileSafety.CombineSafely(Base, "subdir"); + + Assert.Equal(Path.Combine(Base, "subdir"), result); + } + + [Fact] + public void MultipleSegments_CombinesAll() + { + var result = FileSafety.CombineSafely(Base, "sub", "dir", "file.flac"); + + Assert.Equal(Path.Combine(Base, "sub", "dir", "file.flac"), result); + Assert.StartsWith(ExpectedStartsWith, result); + } + + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("sub//dir")] + [InlineData("sub\\\\dir")] + [InlineData("My Artist")] + [InlineData("Artist.Name")] + [InlineData("...dir")] + [InlineData("..hidden")] + [InlineData(".hidden")] + [InlineData("dir/..dir")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("用户/音乐")] + [InlineData("ユーザー/音楽")] + [InlineData("사용자/음악")] + public void Combines_Safe_Segments(string segment) + { + var result = FileSafety.CombineSafely(Base, segment); + + Assert.Equal(Path.Combine(Base, segment), result); + Assert.StartsWith(ExpectedStartsWith, result); + } + + [Theory] + [InlineData("/Music")] + [InlineData("//server/share")] + public void Throws_ArgumentException_Given_AbsolutePath_On_Unix(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + Assert.NotNull(ex); + Assert.Contains("Absolute", ex.Message); + } + + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + public void Throws_ArgumentException_Given_AbsolutePath_On_Windows(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + + Assert.NotNull(ex); + Assert.Contains("Absolute", ex.Message); + } + + [Theory] + [InlineData("foo:bar")] + [InlineData("C:relative")] + [InlineData("sub/foo:bar")] + [InlineData("sub/foo/bar:qux")] + public void Throws_ArgumentException_Given_Colon_In_Segment_On_Windows(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + + Assert.NotNull(ex); + Assert.Contains("Colon", ex.Message); + } + + [Theory] + [InlineData("foo:bar")] + [InlineData("sub/foo:bar")] + [InlineData("sub/foo/bar:qux")] + public void Accepts_Colon_In_Segment_On_Linux(string segment) + { + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:relative")] + public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) + { + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + if (!OperatingSystem.IsWindows()) + { + Assert.Null(result); + } + else + { + // this test breaks when run on windows + // this is valid on linux (which we're trying to test for) + // but invalid on windows because it is a drive-relative path and it successfully traverses + Assert.NotNull(result); + Assert.IsType<ArgumentException>(result); + Assert.Contains("traversal detected", result.Message); + } + } + + [Theory] + [InlineData("/Music")] + [InlineData("\\Music")] + public void Throws_ArgumentException_Given_Leading_Slash_In_Segment_On_Windows(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + + Assert.NotNull(ex); + Assert.Contains("Drive-relative", ex.Message); + } + + [Theory] + [InlineData("\\Music")] + public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) + { + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + if (!OperatingSystem.IsWindows()) + { + Assert.Null(result); + } + else + { + // this test breaks when run on windows + // this is valid on linux (which we're trying to test for) + // but invalid on windows because it is a drive-relative path and it successfully traverses + Assert.NotNull(result); + Assert.IsType<ArgumentException>(result); + Assert.Contains("traversal detected", result.Message); + } + } + + [Theory] + // Bare traversal + [InlineData("..")] + [InlineData(".")] + // Traversal as first component + [InlineData("../escape")] + [InlineData("./dir")] + // Traversal in middle + [InlineData("sub/../escape")] + [InlineData("sub/./dir")] + // Traversal at end + [InlineData("sub/..")] + [InlineData("sub/.")] + // Double traversal + [InlineData("sub/../../escape")] + [InlineData("a/b/c/../../..")] + // Via backslash + [InlineData("sub\\..")] + [InlineData("sub\\.")] + [InlineData("sub\\..\\escape")] + public void Throws_ArgumentException_Given_Traversing_Segment(string segment) + { + var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment)); + + Assert.NotNull(ex); + Assert.Contains("traversal", ex.Message); + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs new file mode 100644 index 00000000..205c87c2 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -0,0 +1,114 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class ContainsTraversalSegmentTests + { + [Theory] + // Bare traversal segments + [InlineData("..")] + [InlineData(".")] + // Traversal as first component — forward slash + [InlineData("../escape")] + [InlineData("./dir")] + // Traversal at end — forward slash + [InlineData("sub/..")] + [InlineData("sub/.")] + // Traversal in middle — forward slash + [InlineData("sub/../escape")] + [InlineData("sub/./dir")] + // Double traversal — forward slash + [InlineData("sub/../../escape")] + [InlineData("a/b/c/../../..")] + // Traversal via backslash + [InlineData("sub\\..")] + [InlineData("sub\\.")] + [InlineData("sub\\..\\escape")] + [InlineData("sub\\.\\dir")] + // Mixed separators + [InlineData("sub/..\\escape")] + [InlineData("sub\\./../escape")] + // Unicode path components mixed with forward-slash traversal + [InlineData("Ünïcödé/../escape")] + [InlineData("Ünïcödé/./escape")] + [InlineData("пользователь/../etc")] + [InlineData("пользователь/./etc")] + [InlineData("用户/../escape")] + [InlineData("ユーザー/../../escape")] + [InlineData("사용자/../escape")] + [InlineData("مستخدم/../escape")] + [InlineData("χρήστης/../μουσική")] + [InlineData("משתמש/../מוזיקה")] + // Unicode path components mixed with backslash traversal + [InlineData("用户\\..\\escape")] + [InlineData("ユーザー\\..\\escape")] + [InlineData("пользователь\\..\\Музыка")] + // Traversal between two valid Unicode segments + [InlineData("Ünïcödé/../пользователь")] + [InlineData("用户/music/../escape")] + // Traversal at end after unicode + [InlineData("Ünïcödé/..")] + [InlineData("пользователь/..")] + [InlineData("用户\\..")] + public void Path_ContainsTraversal(string path) + { + Assert.True(FileSafety.ContainsTraversalSegments(path)); + } + + [Theory] + // Simple names — no separators, no dots + [InlineData("subdir")] + [InlineData("file.flac")] + [InlineData("My Artist")] + [InlineData("Artist.Name")] + // Dotfile and dot-prefixed names — not exactly . or .. + [InlineData(".hidden")] + [InlineData("..hidden")] + [InlineData("...")] + [InlineData("...dir")] + // Segments that start with .. but are not exactly .. + [InlineData("dir/..dir")] + [InlineData("dir/...")] + // Forward-slash paths — no traversal + [InlineData("sub/dir")] + [InlineData("Artist/Album")] + [InlineData("Artist/Album/Song.flac")] + // Backslash paths — no traversal + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("Artist\\Album\\Song.flac")] + // Mixed separators — no traversal + [InlineData("Artist/Album\\Song.flac")] + // Double separators — empty segment is not . or .. + [InlineData("sub//dir")] + [InlineData("sub\\\\dir")] + // Null and empty string — both return false without throwing + [InlineData(null)] + [InlineData("")] + // Unicode — no traversal, forward slash + [InlineData("Ünïcödé")] + [InlineData("Ünïcödé/Àrtïst/Àlbüm")] + [InlineData("пользователь/Музыка")] + [InlineData("用户/音乐/专辑")] + [InlineData("ユーザー/音楽/アルバム")] + [InlineData("사용자/음악/앨범")] + [InlineData("مستخدم/موسيقى")] + [InlineData("χρήστης/μουσική")] + [InlineData("משתמש/מוזיקה")] + // Unicode — no traversal, backslash + [InlineData("пользователь\\Музыка\\Альбом")] + [InlineData("用户\\音乐\\专辑")] + [InlineData("ユーザー\\音楽\\アルバム")] + [InlineData("사용자\\음악\\앨범")] + // Unicode names that start with dots — not traversal + [InlineData("Ünïcödé/..hidden")] + [InlineData("пользователь/...dir")] + [InlineData("用户/..名前")] + public void Path_DoesNotContainTraversal(string path) + { + Assert.False(FileSafety.ContainsTraversalSegments(path)); + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs new file mode 100644 index 00000000..42eab9b8 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -0,0 +1,131 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class IsPathTests + { + public class Windows + { + public class Absolute + { + [Theory] + // drive-letter paths (X:\ or X:/) + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("D:\\path")] + [InlineData("Z:\\downloads")] + [InlineData("C:\\Users\\Ünïcödé\\Music")] + [InlineData("C:\\Users\\пользователь\\Музыка")] + [InlineData("C:\\Users\\用户\\音乐")] + // UNC paths (\\ prefix) + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\server\\share\\My Music")] + [InlineData("\\\\192.168.1.1\\share")] + [InlineData("\\\\server\\Ünïcödé")] + [InlineData("\\\\server\\share\\пользователь")] + [InlineData("\\\\server\\share\\用户\\音乐")] + public void IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("Artist/Album/Song")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData(".hidden")] + [InlineData("..hidden")] + [InlineData("...dir")] + [InlineData("../escape")] + [InlineData("./dir")] + [InlineData("..")] + [InlineData(".")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("/Music")] // root-relative — no drive letter, not absolute on Windows + [InlineData("\\Music")] // root-relative — no drive letter, not absolute on Windows + [InlineData("/home/user")] // Unix-style — not recognised as absolute on Windows + [InlineData("//server/share")] // Unix UNC — not recognised as absolute on Windows + [InlineData("C:")] // bare drive letter — length < 3, not absolute + [InlineData("C:Music")] // drive-relative — no separator after colon, not absolute + [InlineData("D:path")] // drive-relative — no separator after colon, not absolute + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + } + } + } + + public class Linux + { + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user/Music")] + [InlineData("/home/user/My Music")] + [InlineData("/etc/hosts")] + [InlineData("/tmp")] + [InlineData("/home/Ünïcödé")] + [InlineData("/home/пользователь/Музыка")] + [InlineData("/home/用户/音乐")] + [InlineData("/home/ユーザー/音楽")] + [InlineData("/home/사용자/음악")] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("./dir")] + [InlineData("..")] + [InlineData(".")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("C:\\Music")] // Windows drive-letter — not absolute on Linux + [InlineData("C:/Music")] // Windows drive-letter — not absolute on Linux + [InlineData("\\\\server\\share")] // Windows UNC — not absolute on Linux + [InlineData("\\Music")] // Windows root-relative — not absolute on Linux + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + } + } + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs deleted file mode 100644 index a37e9e74..00000000 --- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs +++ /dev/null @@ -1,545 +0,0 @@ -using System; -using System.IO; -using Xunit; - -namespace slskd.Tests.Unit.Files; - -public class FileSafetyTests -{ - // Use a platform-appropriate absolute base path. Backslash roots are not recognised on Linux/macOS, - // so a Windows-style base would make containment assertions meaningless on those platforms. - private static readonly string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; - - private static void AssertContainedInBase(string result) - { - var resolvedBase = Path.GetFullPath(Base); - var resolvedResult = Path.GetFullPath(result); - Assert.True( - resolvedResult == resolvedBase || - resolvedResult.StartsWith(resolvedBase + Path.DirectorySeparatorChar), - $"Result '{resolvedResult}' escapes base '{resolvedBase}'"); - } - - public class ContainsTraversalSegments_ReturnsTrue - { - [Theory] - // Bare traversal segments - [InlineData("..")] - [InlineData(".")] - // Traversal as first component — forward slash - [InlineData("../escape")] - [InlineData("./dir")] - // Traversal at end — forward slash - [InlineData("sub/..")] - [InlineData("sub/.")] - // Traversal in middle — forward slash - [InlineData("sub/../escape")] - [InlineData("sub/./dir")] - // Double traversal — forward slash - [InlineData("sub/../../escape")] - [InlineData("a/b/c/../../..")] - // Traversal via backslash - [InlineData("sub\\..")] - [InlineData("sub\\.")] - [InlineData("sub\\..\\escape")] - [InlineData("sub\\.\\dir")] - // Mixed separators - [InlineData("sub/..\\escape")] - [InlineData("sub\\./../escape")] - // Unicode path components mixed with forward-slash traversal - [InlineData("Ünïcödé/../escape")] - [InlineData("Ünïcödé/./escape")] - [InlineData("пользователь/../etc")] - [InlineData("пользователь/./etc")] - [InlineData("用户/../escape")] - [InlineData("ユーザー/../../escape")] - [InlineData("사용자/../escape")] - [InlineData("مستخدم/../escape")] - [InlineData("χρήστης/../μουσική")] - [InlineData("משתמש/../מוזיקה")] - // Unicode path components mixed with backslash traversal - [InlineData("用户\\..\\escape")] - [InlineData("ユーザー\\..\\escape")] - [InlineData("пользователь\\..\\Музыка")] - // Traversal between two valid Unicode segments - [InlineData("Ünïcödé/../пользователь")] - [InlineData("用户/music/../escape")] - // Traversal at end after unicode - [InlineData("Ünïcödé/..")] - [InlineData("пользователь/..")] - [InlineData("用户\\..")] - public void Path_ContainsTraversal(string path) - { - Assert.True(FileSafety.ContainsTraversalSegments(path)); - } - } - - public class ContainsTraversalSegments_ReturnsFalse - { - [Theory] - // Simple names — no separators, no dots - [InlineData("subdir")] - [InlineData("file.flac")] - [InlineData("My Artist")] - [InlineData("Artist.Name")] - // Dotfile and dot-prefixed names — not exactly . or .. - [InlineData(".hidden")] - [InlineData("..hidden")] - [InlineData("...")] - [InlineData("...dir")] - // Segments that start with .. but are not exactly .. - [InlineData("dir/..dir")] - [InlineData("dir/...")] - // Forward-slash paths — no traversal - [InlineData("sub/dir")] - [InlineData("Artist/Album")] - [InlineData("Artist/Album/Song.flac")] - // Backslash paths — no traversal - [InlineData("sub\\dir")] - [InlineData("Artist\\Album")] - [InlineData("Artist\\Album\\Song.flac")] - // Mixed separators — no traversal - [InlineData("Artist/Album\\Song.flac")] - // Double separators — empty segment is not . or .. - [InlineData("sub//dir")] - [InlineData("sub\\\\dir")] - // Null and empty string — both return false without throwing - [InlineData(null)] - [InlineData("")] - // Unicode — no traversal, forward slash - [InlineData("Ünïcödé")] - [InlineData("Ünïcödé/Àrtïst/Àlbüm")] - [InlineData("пользователь/Музыка")] - [InlineData("用户/音乐/专辑")] - [InlineData("ユーザー/音楽/アルバム")] - [InlineData("사용자/음악/앨범")] - [InlineData("مستخدم/موسيقى")] - [InlineData("χρήστης/μουσική")] - [InlineData("משתמש/מוזיקה")] - // Unicode — no traversal, backslash - [InlineData("пользователь\\Музыка\\Альбом")] - [InlineData("用户\\音乐\\专辑")] - [InlineData("ユーザー\\音楽\\アルバム")] - [InlineData("사용자\\음악\\앨범")] - // Unicode names that start with dots — not traversal - [InlineData("Ünïcödé/..hidden")] - [InlineData("пользователь/...dir")] - [InlineData("用户/..名前")] - public void Path_DoesNotContainTraversal(string path) - { - Assert.False(FileSafety.ContainsTraversalSegments(path)); - } - } - - public class CombineSafely_Returns - { - [Fact] - public void NoSegments_ReturnsBasePath() - { - var result = FileSafety.CombineSafely(Base); - Assert.Equal(Base, result); - } - - [Fact] - public void EmptySegment_ReturnsBasePath() - { - var result = FileSafety.CombineSafely(Base, string.Empty); - Assert.Equal(Base, result); - } - - [Fact] - public void SingleSegment_ReturnsBaseAndSegment() - { - var result = FileSafety.CombineSafely(Base, "subdir"); - Assert.Equal(Path.Combine(Base, "subdir"), result); - } - - [Fact] - public void MultipleSegments_CombinesAll() - { - var result = FileSafety.CombineSafely(Base, "sub", "dir", "file.flac"); - Assert.Equal(Path.Combine(Base, "sub", "dir", "file.flac"), result); - } - - [Fact] - public void SegmentWithForwardSlash_CombinesCorrectly() - { - var result = FileSafety.CombineSafely(Base, "sub/dir"); - AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithBackslash_CombinesCorrectly() - { - var result = FileSafety.CombineSafely(Base, "sub\\dir"); - AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithDoubleSlash_CollapsedAndContained() - { - var result = FileSafety.CombineSafely(Base, "sub//dir"); - AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithDoubleBackslash_CollapsedAndContained() - { - var result = FileSafety.CombineSafely(Base, "sub\\\\dir"); - AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithSpaces_Contained() - { - var result = FileSafety.CombineSafely(Base, "My Artist", "My Album"); - AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithUnicode_Contained() - { - var result = FileSafety.CombineSafely(Base, "Ünïcödé", "пользователь", "音楽"); - AssertContainedInBase(result); - } - - [Fact] - public void DotfileSegment_Contained() - { - var result = FileSafety.CombineSafely(Base, ".hidden"); - AssertContainedInBase(result); - } - - [Fact] - public void ThreeDotsSegment_Contained() - { - var result = FileSafety.CombineSafely(Base, "...dir"); - AssertContainedInBase(result); - } - - [Fact] - public void DotDotPrefixedName_Contained() - { - var result = FileSafety.CombineSafely(Base, "..hidden"); - AssertContainedInBase(result); - } - } - - public class CombineSafely_AlwaysContainedInBase - { - [Theory] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("sub//dir")] - [InlineData("sub\\\\dir")] - [InlineData("My Artist")] - [InlineData("Artist.Name")] - [InlineData("...dir")] - [InlineData("..hidden")] - [InlineData(".hidden")] - [InlineData("dir/..dir")] - [InlineData("Ünïcödé")] - [InlineData("пользователь/Музыка")] - [InlineData("用户/音乐")] - [InlineData("ユーザー/音楽")] - [InlineData("사용자/음악")] - public void SingleSegment_IsContained(string segment) - { - var result = FileSafety.CombineSafely(Base, segment); - var resolvedBase = Path.GetFullPath(Base); - var resolvedResult = Path.GetFullPath(result); - Assert.True( - resolvedResult == resolvedBase || - resolvedResult.StartsWith(resolvedBase + Path.DirectorySeparatorChar), - $"Result '{resolvedResult}' escapes base '{resolvedBase}'"); - } - } - - public class CombineSafely_Throws_ForRootedSegment - { - [Theory] - [InlineData("/Music")] // Unix absolute / Windows root-relative, forward slash - [InlineData("//server/share")] // Unix-style UNC - [InlineData("C:\\Music")] // Windows drive-letter, backslash - [InlineData("C:/Music")] // Windows drive-letter, forward slash - [InlineData("D:\\path")] // alternate drive letter - [InlineData("C:relative")] // Windows drive-relative - [InlineData("\\Music")] // Windows root-relative, backslash - [InlineData("\\\\server\\share")] // Windows UNC - public void Throws_ArgumentException(string segment) - { - var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted() - { - var ex = Assert.Throws<ArgumentException>(() => - FileSafety.CombineSafely(Base, "valid", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted_Windows() - { - var ex = Assert.Throws<ArgumentException>(() => - FileSafety.CombineSafely(Base, "valid", "C:\\escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted() - { - var ex = Assert.Throws<ArgumentException>(() => - FileSafety.CombineSafely(Base, "sub", "dir", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted_Windows() - { - var ex = Assert.Throws<ArgumentException>(() => - FileSafety.CombineSafely(Base, "sub", "dir", "C:\\escape")); - Assert.Contains("Rooted", ex.Message); - } - } - - public class CombineSafely_Throws_ForTraversalSegment - { - [Theory] - // Bare traversal - [InlineData("..")] - [InlineData(".")] - // Traversal as first component - [InlineData("../escape")] - [InlineData("./dir")] - // Traversal in middle - [InlineData("sub/../escape")] - [InlineData("sub/./dir")] - // Traversal at end - [InlineData("sub/..")] - [InlineData("sub/.")] - // Double traversal - [InlineData("sub/../../escape")] - [InlineData("a/b/c/../../..")] - // Via backslash - [InlineData("sub\\..")] - [InlineData("sub\\.")] - [InlineData("sub\\..\\escape")] - // Unicode path components mixed with traversal - [InlineData("Ünïcödé/../escape")] - [InlineData("пользователь/../../escape")] - [InlineData("用户\\..\\escape")] - public void Throws_ArgumentException(string segment) - { - var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentContainsTraversal() - { - var ex = Assert.Throws<ArgumentException>(() => - FileSafety.CombineSafely(Base, "valid", "../escape")); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsTraversal() - { - var ex = Assert.Throws<ArgumentException>(() => - FileSafety.CombineSafely(Base, "sub", "dir", "..")); - Assert.Contains("traversal", ex.Message); - } - } - - public class IsPathAbsolute_ReturnsTrue - { - // Unix/Linux/macOS absolute paths - [Theory] - [InlineData("/")] // filesystem root - [InlineData("/home")] // single component - [InlineData("/home/user/Music")] // deep path - [InlineData("/home/user/My Music")] // spaces in component - [InlineData("/etc/hosts")] // config file - [InlineData("/tmp")] // temp directory - [InlineData("/home/Ünïcödé")] // latin extended - [InlineData("/home/пользователь/Музыка")] // Cyrillic - [InlineData("/home/用户/音乐")] // Chinese - [InlineData("/home/ユーザー/音楽")] // Japanese - [InlineData("/home/사용자/음악")] // Korean - public void Unix_Paths(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path)); - } - - // Unix-style UNC paths (// prefix) - [Theory] - [InlineData("//server/share")] - [InlineData("//server/share/folder")] - [InlineData("//192.168.1.1/share")] - [InlineData("//server/Ünïcödé")] - [InlineData("//server/share/пользователь")] - public void Unix_UNCPaths(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path)); - } - - // Windows root-relative paths (rooted to the current drive, no drive letter) - [Theory] - [InlineData("\\Music")] - [InlineData("\\Music\\Artist\\Album")] - [InlineData("/Music")] - [InlineData("/Music/Artist/Album")] - [InlineData("\\Ünïcödé")] - [InlineData("\\пользователь\\Музыка")] - public void Windows_RootRelativePaths(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path)); - } - - // Windows UNC paths (\\ prefix) - [Theory] - [InlineData("\\\\server\\share")] - [InlineData("\\\\server\\share\\folder")] - [InlineData("\\\\server\\share\\My Music")] - [InlineData("\\\\192.168.1.1\\share")] - [InlineData("\\\\server\\Ünïcödé")] - [InlineData("\\\\server\\share\\пользователь")] - [InlineData("\\\\server\\share\\用户\\音乐")] - public void Windows_UNCPaths(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path)); - } - - // Windows drive-letter paths — with or without a separator after the colon - [Theory] - [InlineData("C:\\")] // drive root, backslash - [InlineData("C:/")] // drive root, forward slash - [InlineData("C:\\Music")] // basic, backslash - [InlineData("C:/Music")] // basic, forward slash - [InlineData("C:\\Music\\Artist\\Album")] // deep, backslash - [InlineData("D:\\path")] // different drive letter - [InlineData("Z:\\downloads")] // drive letter Z - [InlineData("C:")] // bare drive letter - [InlineData("C:Music")] // drive-relative, no separator - [InlineData("D:path")] // different drive letter, no separator - [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended - [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic - [InlineData("C:\\Users\\用户\\音乐")] // Chinese - public void Windows_DriveLetterPaths(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path)); - } - } - - public class IsPathAbsolute_ReturnsFalse - { - [Theory] - [InlineData(null)] // null - [InlineData("")] // empty string - [InlineData("subdir")] // simple name - [InlineData("sub/dir")] // forward slash - [InlineData("sub\\dir")] // backslash - [InlineData("Artist\\Album")] // multi-level backslash - [InlineData("Artist/Album/Song")] // deep forward slash - [InlineData("music.flac")] // file name with extension - [InlineData("My Music")] // spaces - [InlineData(".hidden")] // dotfile - [InlineData("..hidden")] // dot-prefixed name - [InlineData("...dir")] // three dots — relative, not traversal - [InlineData("../escape")] // traversal — still relative - [InlineData("./dir")] // current-dir segment — still relative - [InlineData("..")] // bare double-dot - [InlineData(".")] // bare single-dot - [InlineData("Ünïcödé")] // unicode, no root - [InlineData("пользователь/Музыка")] // unicode with separator, no root - public void Relative_Paths(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path)); - } - } - - public class IsPathRelative_ReturnsTrue - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("music.flac")] - [InlineData(".hidden")] - [InlineData("../escape")] - public void Relative_Paths(string path) - { - Assert.True(FileSafety.IsPathRelative(path)); - } - - } - - public class IsPathRelative_ReturnsFalse - { - [Theory] - [InlineData("/home/user")] - [InlineData("//server/share")] - [InlineData("\\Music")] - [InlineData("\\\\server\\share")] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("C:\\")] - [InlineData("C:")] - [InlineData("C:Music")] - [InlineData("D:path")] - public void Absolute_Paths(string path) - { - Assert.False(FileSafety.IsPathRelative(path)); - } - } - - public class CombineSafely_NullAndEdgeCases - { - [Fact] - public void NullSegmentsArray_Throws() - { - // Passing null without an explicit cast is interpreted as a null params array. - // foreach over a null array throws NullReferenceException. - Assert.ThrowsAny<Exception>(() => FileSafety.CombineSafely(Base, null)); - } - - [Fact] - public void NullSegment_Throws() - { - // A null element inside the params array reaches Path.IsPathRooted(null), - // which throws ArgumentNullException. - Assert.Throws<ArgumentNullException>(() => FileSafety.CombineSafely(Base, null, "subdir")); - } - - [Fact] - public void NullSegmentAlone_Throws() - { - // Explicit cast to string forces a single-element array containing null. - // Path.IsPathRooted(null) throws ArgumentNullException. - Assert.Throws<ArgumentNullException>(() => FileSafety.CombineSafely(Base, (string)null)); - } - - [Fact] - public void NullBasePath_Throws() - { - Assert.ThrowsAny<Exception>(() => FileSafety.CombineSafely(null, "subdir")); - } - - [Fact] - public void TraversalInRoot_IsNotValidated() - { - // CombineSafely only validates segments, not the root parameter — root is assumed - // to be a known-good value supplied by the application, not untrusted input. - // This test documents that a traversal-containing root is NOT rejected. - var root = OperatingSystem.IsWindows() ? "C:\\base\\..\\etc" : "/base/../etc"; - var result = FileSafety.CombineSafely(root, "subdir"); - Assert.NotNull(result); - } - } -} diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index bc8601c5..b1375e45 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Runtime.InteropServices; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class AbsolutePathAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(string value) + private static (bool IsValid, string ErrorMessage) Validate(string value, OSPlatform? os = null) { - var attribute = new AbsolutePathAttribute(); + var attribute = new AbsolutePathAttribute(os); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); @@ -29,149 +30,86 @@ public class AbsolutePathAttributeTests Assert.True(isValid); } - public class Passes + public class Windows { - // Standard Windows drive-letter absolute paths [Theory] - [InlineData("C:\\Music")] // basic - [InlineData("C:/Music")] // forward slash separator - [InlineData("C:\\Music\\Artist\\Album")] // multi-level backslash - [InlineData("C:\\Music\\Artist/Album")] // mixed separators - [InlineData("C:\\Music\\My Artist")] // spaces in component - [InlineData("C:\\Program Files\\App")] // spaces, typical Windows path - [InlineData("D:\\path")] // different drive letter - [InlineData("Z:\\downloads")] // drive letter Z - [InlineData("C:")] // bare drive - [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended - [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic - [InlineData("C:\\Users\\用户\\音乐")] // Chinese - [InlineData("C:\\Users\\ユーザー\\音楽")] // Japanese - [InlineData("C:\\Users\\사용자\\음악")] // Korean - [InlineData("C:\\Users\\مستخدم\\موسيقى")] // Arabic - [InlineData("C:\\Users\\χρήστης\\μουσική")] // Greek - [InlineData("C:Music")] // drive-relative (no separator) + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\Music\\Artist/Album")] + [InlineData("C:/Music/My Artist")] public void Windows_DriveLetterPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Windows); Assert.True(isValid); } - // Windows root paths (drive root with trailing separator) [Theory] - [InlineData("C:\\")] // Windows C: root - [InlineData("D:\\")] // Windows D: root - [InlineData("Z:\\")] // Windows Z: root - [InlineData("C:/")] // root with forward slash + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("C:/")] public void Windows_RootPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Windows); Assert.True(isValid); } - // Windows root-relative paths (rooted to the current drive, no drive letter) [Theory] - [InlineData("\\Music")] // root-relative, backslash - [InlineData("\\Music\\Artist\\Album")] // deep, backslash - [InlineData("/Music")] // root-relative, forward slash - [InlineData("/Music/Artist/Album")] // deep, forward slash - [InlineData("\\Ünïcödé")] // latin extended - [InlineData("\\пользователь\\Музыка")] // Cyrillic - [InlineData("\\用户\\音乐")] // Chinese - [InlineData("\\ユーザー\\音楽")] // Japanese - [InlineData("\\사용자\\음악")] // Korean - public void Windows_RootRelativePaths_Pass(string value) + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\192.168.1.1\\share")] + public void Windows_UNCPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Windows); Assert.True(isValid); } - // Windows UNC (Universal Naming Convention) paths. - // Server name is DNS-constrained (ASCII), but share names and path components support Unicode. [Theory] - [InlineData("\\\\server\\share")] // basic UNC - [InlineData("\\\\server\\share\\folder")] // UNC with subfolder - [InlineData("\\\\server\\share\\My Music")] // UNC with spaces - [InlineData("\\\\192.168.1.1\\share")] // UNC with IP address - [InlineData("\\\\DESKTOP-ABC\\SharedFolder")] // UNC with machine name - [InlineData("\\\\192.168.1.1\\Ünïcödé")] // latin extended share name - [InlineData("\\\\server\\Müsïk")] // latin extended share name - [InlineData("\\\\server\\share\\Ünïcödé Artist")] // latin extended path component - [InlineData("\\\\server\\音楽")] // Japanese share name - [InlineData("\\\\server\\share\\пользователь")] // Cyrillic path component - [InlineData("\\\\server\\share\\用户\\音乐")] // Chinese path components - [InlineData("\\\\server\\share\\사용자\\음악")] // Korean path components - public void Windows_UNCPaths_Pass(string value) + [InlineData("\\Music")] + [InlineData("/Music")] + [InlineData("/Music/Artist/Album")] + [InlineData("C:")] + [InlineData("C:Music")] + public void Windows_RootRelativePaths_Fail(string value) { - var (isValid, _) = Validate(value); - Assert.True(isValid); + var (isValid, _) = Validate(value, OSPlatform.Windows); + Assert.False(isValid); } + } - // Unix/Linux absolute paths — always start with a leading / + public class Unix + { [Theory] - [InlineData("/")] // filesystem root - [InlineData("/home")] // single component - [InlineData("/home/user")] // typical home directory - [InlineData("/home/user/Music")] // deep path - [InlineData("/home/user/My Music")] // spaces in component - [InlineData("/etc/hosts")] // config file path - [InlineData("/usr/local/bin")] // system path - [InlineData("/var/log/app.log")] // log file - [InlineData("/tmp")] // temp directory - [InlineData("/media/usb0")] // mounted device - [InlineData("/mnt/storage/Music")] // mounted storage - [InlineData("/home/user/Ünïcödé")] // latin extended - [InlineData("/home/пользователь/Музыка")] // Cyrillic - [InlineData("/home/用户/音乐")] // Chinese - [InlineData("/home/ユーザー/音楽")] // Japanese - [InlineData("/home/사용자/음악")] // Korean - [InlineData("/home/مستخدم/موسيقى")] // Arabic - [InlineData("/home/χρήστης/μουσική")] // Greek - [InlineData("/home/משתמש/מוזיקה")] // Hebrew + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user")] public void Unix_Paths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); Assert.True(isValid); } - // macOS absolute paths — same format as Unix, with macOS-specific conventions [Theory] - [InlineData("/Users/username")] // home directory - [InlineData("/Users/username/Music")] // music library - [InlineData("/Users/username/Music/Artist/Album")] // deep path - [InlineData("/Volumes/External Drive")] // mounted external drive - [InlineData("/Volumes/External Drive/Music")] // file on external drive - [InlineData("/Applications/App.app")] // application bundle - [InlineData("/Library/Application Support/App")] // system library - [InlineData("/Users/Ünïcödé")] // latin extended username - [InlineData("/Users/пользователь/Музыка")] // Cyrillic - [InlineData("/Users/用户/音乐")] // Chinese - [InlineData("/Users/ユーザー/音楽")] // Japanese - [InlineData("/Users/사용자/음악")] // Korean - [InlineData("/Volumes/Ünïcödé Drive/Music")] // latin extended volume name - [InlineData("/Volumes/音楽ドライブ")] // Japanese volume name - [InlineData("/Volumes/외장 드라이브/음악")] // Korean volume name - public void MacOS_Paths_Pass(string value) + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void Unix_UNCPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); Assert.True(isValid); } - // Unix-style UNC equivalents (// prefix, used on some systems) [Theory] - [InlineData("//server/share")] // basic - [InlineData("//server/share/folder")] // with subfolder - [InlineData("//server/Ünïcödé")] // latin extended share name - [InlineData("//server/share/Ünïcödé Artist")] // latin extended path component - [InlineData("//server/音楽")] // Japanese share name - [InlineData("//server/share/пользователь")] // Cyrillic path component - public void Unix_UNCPaths_Pass(string value) + [InlineData("\\")] + [InlineData("\\home")] + public void Unix_Backslash_Fail(string value) { - var (isValid, _) = Validate(value); - Assert.True(isValid); + var (isValid, _) = Validate(value, OSPlatform.Linux); + Assert.False(isValid); } } - public class Relative_Fails + public class Relative { [Theory] [InlineData("subdir")] // simple name @@ -188,9 +126,15 @@ public class AbsolutePathAttributeTests [InlineData(".")] // current-dir but fundamentally not absolute public void RelativePath_Fails(string value) { - var (isValid, errorMessage) = Validate(value); + var (isValid, errorMessage) = Validate(value, OSPlatform.Linux); + Assert.False(isValid); Assert.Equal("The Field field must be an absolute file path.", errorMessage); + + var (isValid2, errorMessage2) = Validate(value, OSPlatform.Windows); + + Assert.False(isValid2); + Assert.Equal("The Field field must be an absolute file path.", errorMessage2); } } } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index bc581bf1..1d480010 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Runtime.InteropServices; using slskd.Validation; using Xunit; @@ -6,15 +7,15 @@ namespace slskd.Tests.Unit.Common.Validation; public class RelativePathAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(string value) + private static (bool IsValid, string ErrorMessage) Validate(string value, OSPlatform? os = null) { - var attribute = new RelativePathAttribute(); + var attribute = new RelativePathAttribute(os); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); } - // null and empty are explicitly allowed; presence is enforced by [Required] separately + // paths can be null or empty; [Required] dictates whether they must be defined [Fact] public void Null_Passes() { @@ -29,77 +30,116 @@ public class RelativePathAttributeTests Assert.True(isValid); } - public class Passes + public class Relative { [Theory] - [InlineData("Artist")] // simple name - [InlineData("music.flac")] // file with extension - [InlineData("My Artist")] // spaces - [InlineData("Artist.Name")] // dots that are not traversal - [InlineData("Artist/Album")] // forward slash - [InlineData("Artist\\Album")] // backslash - [InlineData("Artist/Album/Song.flac")] // multi-level forward slash - [InlineData("Artist\\Album\\Song.flac")] // multi-level backslash - [InlineData("Artist/Album\\Song.flac")] // mixed separators - [InlineData("...dir")] // three dots — not a traversal segment - [InlineData("..hidden")] // starts with .. but is a name, not traversal - [InlineData(".hidden")] // dotfile name, not a traversal segment - [InlineData("dir/..dir")] // segment starts with .. but is not exactly .. - [InlineData("Ünïcödé Àrtïst")] // latin extended - [InlineData("Ünïcödé/Àrtïst/Àlbüm")] // latin extended, forward slash - [InlineData("Ünïcödé\\Àrtïst\\Àlbüm")] // latin extended, backslash - [InlineData("пользователь/Музыка")] // Cyrillic, forward slash - [InlineData("пользователь\\Музыка\\Альбом")] // Cyrillic, backslash - [InlineData("用户/音乐/专辑")] // Chinese, forward slash - [InlineData("用户\\音乐\\专辑")] // Chinese, backslash - [InlineData("ユーザー/音楽/アルバム")] // Japanese, forward slash - [InlineData("ユーザー\\音楽\\アルバム")] // Japanese, backslash - [InlineData("사용자/음악/앨범")] // Korean, forward slash - [InlineData("사용자\\음악\\앨범")] // Korean, backslash - [InlineData("مستخدم/موسيقى")] // Arabic - [InlineData("χρήστης/μουσική")] // Greek - [InlineData("משתמש/מוזיקה")] // Hebrew + [InlineData("subdir")] // simple name + [InlineData("sub/dir")] // forward slash + [InlineData("sub\\dir")] // backslash + [InlineData("Artist\\Album")] // multi-level + [InlineData("music.flac")] // file name with extension + [InlineData("My Music")] // spaces + [InlineData("Ünïcödé")] // latin extended, still relative + [InlineData("Artist/Album/Song")] // deep relative + [InlineData("...dir")] // three dots — relative, not traversal + [InlineData(".hidden")] // dotfile — relative, not traversal + [InlineData("..")] // traversal-like but fundamentally not absolute + [InlineData(".")] // current-dir but fundamentally not absolute public void RelativePath_Passes(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); + Assert.True(isValid); + + var (isValid2, _) = Validate(value, OSPlatform.Windows); + + Assert.True(isValid2); } } - public class Absolute_Fails + public class Windows { [Theory] - // Windows drive-letter paths [InlineData("C:\\Music")] [InlineData("C:/Music")] - [InlineData("D:\\path\\to\\file")] - [InlineData("Z:/downloads")] - [InlineData("C:")] - // Windows root-relative (no drive letter) - [InlineData("\\Music")] - [InlineData("\\Music\\Artist\\Album")] - // Windows UNC + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\Music\\Artist/Album")] + [InlineData("C:/Music/My Artist")] + public void Windows_DriveLetterPaths_Fail(string value) + { + var (isValid, _) = Validate(value, OSPlatform.Windows); + + Assert.False(isValid); + } + + [Theory] + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("C:/")] + public void Windows_RootPaths_Fail(string value) + { + var (isValid, _) = Validate(value, OSPlatform.Windows); + + Assert.False(isValid); + } + + [Theory] [InlineData("\\\\server\\share")] [InlineData("\\\\server\\share\\folder")] [InlineData("\\\\192.168.1.1\\share")] - // Unix/Linux + public void Windows_UNCPaths_Fail(string value) + { + var (isValid, _) = Validate(value, OSPlatform.Windows); + + Assert.False(isValid); + } + + [Theory] + [InlineData("\\Music")] + [InlineData("/Music")] + [InlineData("/Music/Artist/Album")] + [InlineData("C:")] + [InlineData("C:Music")] + public void Windows_RootRelativePaths_Pass(string value) + { + var (isValid, _) = Validate(value, OSPlatform.Windows); + + Assert.True(isValid); + } + } + + public class Unix + { + [Theory] [InlineData("/")] + [InlineData("/home")] [InlineData("/home/user")] - [InlineData("/etc/hosts")] - [InlineData("/usr/local/bin")] - // macOS - [InlineData("/Users/username")] - [InlineData("/Volumes/External Drive")] - // Unix-style UNC (// prefix) + public void Unix_Paths_Fail(string value) + { + var (isValid, _) = Validate(value, OSPlatform.Linux); + + Assert.False(isValid); + } + + [Theory] [InlineData("//server/share")] [InlineData("//server/share/folder")] - // Windows drive-relative (no separator after colon; still rooted) - [InlineData("C:Music")] - public void AbsolutePath_Fails(string value) + [InlineData("//192.168.1.1/share")] + public void Unix_UNCPaths_Fail(string value) { - var (isValid, errorMessage) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); + Assert.False(isValid); - Assert.Equal("The Field field must be a relative path.", errorMessage); + } + + [Theory] + [InlineData("\\")] + [InlineData("\\home")] + public void Unix_Backslash_Pass(string value) + { + var (isValid, _) = Validate(value, OSPlatform.Linux); + + Assert.True(isValid); } } } diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index dbc82736..dbf8396f 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -41,7 +41,7 @@ public class StringAttributeTests Assert.True(isValid); var (isValid2, message2) = Validate("foo", a => a.AllowNull = false); - Assert.True(isValid); + Assert.True(isValid2); } } @@ -69,7 +69,7 @@ public class StringAttributeTests Assert.True(isValid); var (isValid2, _) = Validate("hello", a => a.AllowEmpty = true); - Assert.True(isValid); + Assert.True(isValid2); } } @@ -97,7 +97,7 @@ public class StringAttributeTests Assert.True(isValid); var (isValid2, _) = Validate("hello", a => a.AllowWhiteSpace = true); - Assert.True(isValid); + Assert.True(isValid2); } } diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index a9f30129..137fd73e 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using slskd.Transfers.API; @@ -276,15 +277,31 @@ public class QueueDownloadBatchRequestTests [Theory] [InlineData("C:\\Music")] // Windows absolute [InlineData("C:/Music")] // Windows absolute, forward slash + [InlineData("\\\\server\\share")] // UNC + public void AbsolutePath_Fails_Windows(string value) + { + if (OperatingSystem.IsWindows()) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + } + } + + [Theory] [InlineData("/music")] // Unix absolute [InlineData("/home/user/Music")] // Unix absolute, deep - [InlineData("\\\\server\\share")] // UNC - public void AbsolutePath_Fails(string value) + [InlineData("//server/share")] // UNC + public void AbsolutePath_Fails_Non_Windows(string value) { - var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); - Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + if (!OperatingSystem.IsWindows()) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + } } [Theory] |
