From 95847e83d2be4cdb865c17a82cbc140d06bad7c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 20:39:37 -0500 Subject: add FileSafety --- src/slskd/Common/FileSafety.cs | 149 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 src/slskd/Common/FileSafety.cs (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs new file mode 100644 index 00000000..f94b9c7b --- /dev/null +++ b/src/slskd/Common/FileSafety.cs @@ -0,0 +1,149 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd; + +using System; +using System.IO; +using System.Linq; + +/// +/// Utility functions to help safely work with paths from untrusted sources. +/// +public static class FileSafety +{ + /// + /// An alternative to that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// + /// The root directory. + /// The segments to append. + /// The combined path. + /// Thrown if the root, list of segments, or one or more segments is null. + /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. + public static string CombineSafely(string root, params string[] segments) + { + // ensure no inputs are null. matches the behavior of Path.Combine() + if (string.IsNullOrWhiteSpace(root)) + { + throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace"); + } + + if (segments is null || segments.Any(s => s is null)) + { + throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); + } + + 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)) + { + throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); + } + + var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); + + // ensure the segments we're combining don't contain traversal segments "." or ".." + // 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}'"); + } + } + + var combined = Path.Combine(root, Path.Combine(segments)); + + // not sure how we could possibly get here, but if we do, throw. + if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) + { + throw new ArgumentException($"Path traversal detected in path {combined}, which is not allowed"); + } + + return combined; + } + + /// + /// Returns a value indicating whether the specified contains path traversal segments. + /// + /// The path to check. + /// True if one or more segments is present, false otherwise. + public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; + + /// + /// Returns a value indicating whether the specified is absolute (rooted), using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// + /// + /// 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. + /// + /// The path to check. + /// True if the path is absolute, false otherwise. + public static bool IsPathAbsolute(string path) + { + 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 '\\') + { + return true; + } + + // 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] == ':') + { + return true; + } + + return false; + } + + /// + /// Returns a value indicating whether the specified , using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// + /// The path to check. + /// True if the path is relative, false otherwise. + public static bool IsPathRelative(string path) => !IsPathAbsolute(path); +} \ No newline at end of file -- cgit v1.2.3 From 96ea096105f4fe0371a58cdc9ecf5c6b82a937e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 May 2026 19:14:25 -0500 Subject: fix path detection (again) --- src/slskd/Common/FileSafety.cs | 48 +- .../Common/FileSafety/CombineSafelyTests.cs | 285 +++++++++++ .../FileSafety/ContainsTraversalSegmentsTests.cs | 114 +++++ .../Common/FileSafety/IsPathTests.cs | 213 ++++++++ tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 545 --------------------- .../API/DTO/QueueDownloadBatchRequestTests.cs | 29 +- 6 files changed, 665 insertions(+), 569 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs delete mode 100644 tests/slskd.Tests.Unit/Common/FileSafetyTests.cs (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f94b9c7b..1e25ccd0 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; /// /// Utility functions to help safely work with paths from untrusted sources. @@ -102,36 +103,46 @@ public static class FileSafety public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; /// - /// Returns a value indicating whether the specified is absolute (rooted), using - /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// Returns a value indicating whether the specified is absolute (rooted) on the current + /// operating system. /// /// /// 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. /// /// The path to check. + /// An optional operating system override, for testing. /// True if the path is absolute, false otherwise. - 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 +151,11 @@ public static class FileSafety } /// - /// Returns a value indicating whether the specified , using - /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// Returns a value indicating whether the specified is relative on the current + /// operating system. /// /// The path to check. + /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. - 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/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs new file mode 100644 index 00000000..4cac90c5 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -0,0 +1,285 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +internal static class CombineSafelyTestHelpers +{ + // 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. + public static readonly string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; + + public 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 CombineSafely_Returns +{ + [Fact] + public void NoSegments_ReturnsBasePath() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base); + Assert.Equal(CombineSafelyTestHelpers.Base, result); + } + + [Fact] + public void EmptySegment_ReturnsBasePath() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, string.Empty); + Assert.Equal(CombineSafelyTestHelpers.Base, result); + } + + [Fact] + public void SingleSegment_ReturnsBaseAndSegment() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "subdir"); + Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "subdir"), result); + } + + [Fact] + public void MultipleSegments_CombinesAll() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"); + Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"), result); + } + + [Fact] + public void SegmentWithForwardSlash_CombinesCorrectly() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub/dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithBackslash_CombinesCorrectly() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithDoubleSlash_CollapsedAndContained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub//dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithDoubleBackslash_CollapsedAndContained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\\\dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithSpaces_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "My Artist", "My Album"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithUnicode_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "Ünïcödé", "пользователь", "音楽"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void DotfileSegment_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, ".hidden"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void ThreeDotsSegment_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "...dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void DotDotPrefixedName_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "..hidden"); + CombineSafelyTestHelpers.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(CombineSafelyTestHelpers.Base, segment); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } +} + +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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted_Windows() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "C:\\escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted_Windows() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentContainsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "../escape")); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "..")); + Assert.Contains("traversal", ex.Message); + } +} + +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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, null)); + } + + [Fact] + public void NullSegment_Throws() + { + // A null element inside the params array reaches Path.IsPathRooted(null), + // which throws ArgumentNullException. + Assert.Throws(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, (string)null)); + } + + [Fact] + public void NullBasePath_Throws() + { + Assert.ThrowsAny(() => 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/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs new file mode 100644 index 00000000..9667789e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -0,0 +1,114 @@ +using Xunit; + +namespace slskd.Tests.Unit.Files; + +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)); + } +} 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..723879a0 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -0,0 +1,213 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +public class IsPath_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 IsPath_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)); + } + } +} + +public class IsPath_MacOS +{ + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/Users")] + [InlineData("/Users/user/Music")] + [InlineData("/Volumes/ExternalDrive")] + [InlineData("/home/Ünïcödé")] + [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.OSX)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.OSX)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + [InlineData("\\Music")] + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.OSX)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.OSX)); + } + } +} + +public class IsPath_FreeBSD +{ + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/usr")] + [InlineData("/usr/local/music")] + [InlineData("/home/user/Music")] + [InlineData("/home/Ünïcödé")] + [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.FreeBSD)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + [InlineData("\\Music")] + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.FreeBSD)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); + } + } +} 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(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "valid", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "valid", "C:\\escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "sub", "dir", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - 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(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentContainsTraversal() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "valid", "../escape")); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsTraversal() - { - var ex = Assert.Throws(() => - 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(() => 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(() => 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(() => FileSafety.CombineSafely(Base, (string)null)); - } - - [Fact] - public void NullBasePath_Throws() - { - Assert.ThrowsAny(() => 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/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] -- cgit v1.2.3 From 9376c6a3b47ecffc1f1acc880c931d784db3c18b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 22 May 2026 11:56:59 -0500 Subject: adjust FileSafety tests --- src/slskd/Common/FileSafety.cs | 23 +- .../Common/FileSafety/CombineSafelyTests.cs | 420 +++++++-------------- .../FileSafety/ContainsTraversalSegmentsTests.cs | 214 +++++------ .../Common/FileSafety/IsPathTests.cs | 316 ++++++---------- .../Validation/AbsolutePathAttributeTests.cs | 154 +++----- .../Validation/RelativePathAttributeTests.cs | 9 +- 6 files changed, 436 insertions(+), 700 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1e25ccd0..c024aa86 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -51,7 +51,19 @@ public static class FileSafety /// The combined path. /// Thrown if the root, list of segments, or one or more segments is null. /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. - public static string CombineSafely(string root, params string[] segments) + public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments); + + /// + /// An alternative to that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// + /// The root directory. + /// An optional operating system override, for testing. + /// The segments to append. + /// The combined path. + /// Thrown if the root, list of segments, or one or more segments is null. + /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. + 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)) @@ -59,6 +71,11 @@ 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"); @@ -69,9 +86,9 @@ public static class FileSafety // 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}'"); } var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 4cac90c5..dce61235 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -1,285 +1,147 @@ using System; using System.IO; +using System.Runtime.InteropServices; using Xunit; -namespace slskd.Tests.Unit.Files; +namespace slskd.Tests.Unit.Common; -internal static class CombineSafelyTestHelpers +public partial 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. - public static readonly string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; - - public 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 CombineSafely_Returns -{ - [Fact] - public void NoSegments_ReturnsBasePath() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base); - Assert.Equal(CombineSafelyTestHelpers.Base, result); - } - - [Fact] - public void EmptySegment_ReturnsBasePath() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, string.Empty); - Assert.Equal(CombineSafelyTestHelpers.Base, result); - } - - [Fact] - public void SingleSegment_ReturnsBaseAndSegment() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "subdir"); - Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "subdir"), result); - } - - [Fact] - public void MultipleSegments_CombinesAll() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"); - Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"), result); - } - - [Fact] - public void SegmentWithForwardSlash_CombinesCorrectly() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub/dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithBackslash_CombinesCorrectly() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithDoubleSlash_CollapsedAndContained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub//dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithDoubleBackslash_CollapsedAndContained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\\\dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithSpaces_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "My Artist", "My Album"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithUnicode_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "Ünïcödé", "пользователь", "音楽"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void DotfileSegment_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, ".hidden"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void ThreeDotsSegment_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "...dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void DotDotPrefixedName_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "..hidden"); - CombineSafelyTestHelpers.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(CombineSafelyTestHelpers.Base, segment); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } -} - -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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "C:\\escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentContainsTraversal() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "../escape")); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsTraversal() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "..")); - Assert.Contains("traversal", ex.Message); - } -} - -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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, null)); - } - - [Fact] - public void NullSegment_Throws() - { - // A null element inside the params array reaches Path.IsPathRooted(null), - // which throws ArgumentNullException. - Assert.Throws(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, (string)null)); - } - - [Fact] - public void NullBasePath_Throws() - { - Assert.ThrowsAny(() => 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); - } -} + 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(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(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 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] + // 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(() => 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 index 9667789e..205c87c2 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -1,114 +1,114 @@ using Xunit; -namespace slskd.Tests.Unit.Files; +namespace slskd.Tests.Unit.Common; -public class ContainsTraversalSegments_ReturnsTrue +public partial class FileSafetyTests { - [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) + public class ContainsTraversalSegmentTests { - Assert.True(FileSafety.ContainsTraversalSegments(path)); - } -} + [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)); + [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 index 723879a0..42eab9b8 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -1,213 +1,131 @@ using System.Runtime.InteropServices; using Xunit; -namespace slskd.Tests.Unit.Files; +namespace slskd.Tests.Unit.Common; -public class IsPath_Windows +public partial class FileSafetyTests { - public class Absolute + public class IsPathTests { - [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) + public class Windows { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.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 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 IsPath_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) + public class Linux { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.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)); - } - } -} - -public class IsPath_MacOS -{ - public class Absolute - { - [Theory] - [InlineData("/")] - [InlineData("/Users")] - [InlineData("/Users/user/Music")] - [InlineData("/Volumes/ExternalDrive")] - [InlineData("/home/Ünïcödé")] - [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.OSX)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.OSX)); - } - } - - public class Relative - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("music.flac")] - [InlineData(".hidden")] - [InlineData("../escape")] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("\\\\server\\share")] - [InlineData("\\Music")] - public void IsRelative_NotAbsolute(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.OSX)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.OSX)); - } - } -} - -public class IsPath_FreeBSD -{ - public class Absolute - { - [Theory] - [InlineData("/")] - [InlineData("/usr")] - [InlineData("/usr/local/music")] - [InlineData("/home/user/Music")] - [InlineData("/home/Ünïcödé")] - [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.FreeBSD)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); - } - } - - public class Relative - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("music.flac")] - [InlineData(".hidden")] - [InlineData("../escape")] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("\\\\server\\share")] - [InlineData("\\Music")] - public void IsRelative_NotAbsolute(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.FreeBSD)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); + 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/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index bc8601c5..c5c94209 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,7 +126,7 @@ 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); } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index bc581bf1..d1d71f18 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,9 +7,9 @@ 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); @@ -61,7 +62,7 @@ public class RelativePathAttributeTests [InlineData("משתמש/מוזיקה")] // Hebrew public void RelativePath_Passes(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); Assert.True(isValid); } } @@ -97,7 +98,7 @@ public class RelativePathAttributeTests [InlineData("C:Music")] public void AbsolutePath_Fails(string value) { - var (isValid, errorMessage) = Validate(value); + var (isValid, errorMessage) = Validate(value, OSPlatform.Windows); Assert.False(isValid); Assert.Equal("The Field field must be a relative path.", errorMessage); } -- cgit v1.2.3 From 01836889040aa76883bf81eb0f4b900f6e7fc4be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 May 2026 16:36:10 -0500 Subject: make CombineSafely() even safer --- src/slskd/Common/FileSafety.cs | 24 +++++- .../Common/FileSafety/CombineSafelyTests.cs | 95 ++++++++++++++++++++++ 2 files changed, 116 insertions(+), 3 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index c024aa86..f67af8d5 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -81,6 +81,8 @@ public static class FileSafety 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 @@ -91,22 +93,38 @@ public static class FileSafety 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, '\\', '/'); // ensure the segments we're combining don't contain traversal segments "." or ".." // 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; diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index dce61235..2d496c4b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -51,6 +51,24 @@ public partial class FileSafetyTests 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(ex); + } + + [Fact] + public void Throws_Given_Null_Segments() + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, segments: null)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + [Fact] public void SingleSegment_ReturnsBaseAndSegment() { @@ -116,6 +134,83 @@ public partial class FileSafetyTests 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(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(result); + Assert.Contains("traversal detected", result.Message); + } + } + [Theory] // Bare traversal [InlineData("..")] -- cgit v1.2.3 From def6a3a05f02a53b814821ab6b9692e89c2df693 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:18:06 -0500 Subject: add sanitize functions to FileSafety --- src/slskd/Common/FileSafety.cs | 106 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f67af8d5..aae14a25 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -36,12 +36,34 @@ using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; /// /// Utility functions to help safely work with paths from untrusted sources. /// public static class FileSafety { + + /// + /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). + /// + public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/']; + + /// + /// Invalid filename characters on Windows. + /// + public static readonly char[] InvalidFileNameCharactersOnWindows = + [ + '\"', '<', '>', '|', '\0', + (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, + (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, + (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, + (char)31, ':', '*', '?', '\\', '/', + ]; + + private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ + private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + /// /// An alternative to that disallows rooted segments in the second or /// subsequent position, and disallows segments containing path traversal characters "." and "..". @@ -193,4 +215,88 @@ public static class FileSafety /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + + /// + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// + /// The path to convert. + /// An optional operating system override, for testing. + /// The converted path. + public static string LocalizePath(this string path, OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + return path.Replace('\\', sep).Replace('/', sep); + } + + /// + /// Sanitizes the specified (or string intended to be used as or as part of a filename) + /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and + /// and replacing any invalid characters with the specified . + /// + /// The filename (or string intended to be used as/part of one). + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized filename. + public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + { + if (replacement is '/' or '\\') + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); + } + + os ??= Compute.OSPlatform(); + + var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + + if (characters.Contains(replacement)) + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}"); + } + + var sanitized = filename; + + foreach (var c in characters) + { + sanitized = sanitized.Replace(c, replacement); + } + + // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames + // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath() + return sanitized + .Replace('/', replacement) + .Replace('\\', replacement); + } + + /// + /// Sanitizes the specified to make it suitable and safe on the local operating system + /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with + /// the specified , and by dropping any path traversal segments. + /// + /// The path. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path. + public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + // flip slashes the correct way + path = path.LocalizePath(os); + + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + var segments = path + .Split(sep) + .Select(s => SanitizeFilename(s, replacement, os)) + .Select(s => s is "." or ".." ? replacement.ToString() : s); + + return string.Join(sep, segments); + } } \ No newline at end of file -- cgit v1.2.3 From 89f2a6e19745f22a8f003556b743cbe87ec67cc8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:43:50 -0500 Subject: strip soulseek qt prefixes too --- src/slskd/Common/FileSafety.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index aae14a25..06fd340d 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -63,6 +63,7 @@ public static class FileSafety private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix /// /// An alternative to that disallows rooted segments in the second or @@ -291,6 +292,9 @@ public static class FileSafety path = DriveRootRegex.Replace(path, string.Empty); path = UncRootRegex.Replace(path, string.Empty); + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split(sep) -- cgit v1.2.3 From 34005f37c03e878c2a3286ca0223f921a66a5671 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 May 2026 19:10:37 -0500 Subject: tests --- src/slskd/Common/FileSafety.cs | 1 - .../Common/FileSafety/LocalizePathTests.cs | 16 ++++++++++++++- .../Common/FileSafety/SanitizeFilenameTests.cs | 24 ++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 06fd340d..dc27a8b4 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -43,7 +43,6 @@ using System.Text.RegularExpressions; /// public static class FileSafety { - /// /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). /// diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index ed3e692f..2df3e18f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -10,8 +10,15 @@ public partial class FileSafetyTests [Theory] [InlineData("foo/bar", "foo/bar")] [InlineData("foo\\bar", "foo/bar")] + [InlineData("foo/bar/baz", "foo/bar/baz")] [InlineData("foo\\bar/baz", "foo/bar/baz")] [InlineData("foo\\\\bar", "foo//bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde/foo/bar/")] + [InlineData("@@abcde/foo/bar/", "@@abcde/foo/bar/")] + [InlineData("\\\\server\\foo\\", "//server/foo/")] + [InlineData("//server/foo/", "//server/foo/")] + [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] + [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] public void Linux_NormalizesToForwardSlash(string input, string expected) { @@ -24,7 +31,14 @@ public partial class FileSafetyTests [InlineData("foo/bar", "foo\\bar")] [InlineData("foo\\bar", "foo\\bar")] [InlineData("foo/bar/baz", "foo\\bar\\baz")] + [InlineData("foo\\bar/baz", "foo\\bar\\baz")] [InlineData("foo//bar", "foo\\\\bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde\\foo\\bar\\")] + [InlineData("@@abcde/foo/bar/", "@@abcde\\foo\\bar\\")] + [InlineData("\\\\server\\foo\\", "\\\\server\\foo\\")] + [InlineData("//server/foo/", "\\\\server\\foo\\")] + [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] + [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] public void Windows_NormalizesToBackslash(string input, string expected) { @@ -38,7 +52,7 @@ public partial class FileSafetyTests { var result = "foo/bar".LocalizePath(); - Assert.NotNull(result); + Assert.False(string.IsNullOrEmpty(result)); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 285fdffd..34e969d4 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -85,6 +85,18 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C:_Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Linux_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + [Fact] public void Linux_Uses_Custom_Replacement() { @@ -109,6 +121,18 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C__Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Windows_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + [Fact] public void Windows_Replaces_ControlCharacters() { -- cgit v1.2.3 From ebf7c753f385c558cc1442609eaa17d2eb32e6da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:40:13 -0500 Subject: add get filename/directory name safely methods, overload sanitizefilename with sanitizePathRoot --- src/slskd/Common/FileSafety.cs | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index dc27a8b4..93a91faa 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -216,6 +216,54 @@ public static class FileSafety /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + /// + /// Returns the filename from the specified , properly + /// handling both forward and backslashes and removing invalid characters. + /// + /// The path from which to extract the filename. + /// An optional value indicating that invalid characters should not be replaced. + /// An optional operating system override, for testing. + /// The extracted filename. + /// Thrown if the specified path is null. + public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + { + ArgumentNullException.ThrowIfNull(path); + + return LocalizePath(path, os) + .Split(Path.DirectorySeparatorChar) + .TakeLast(1) + .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) + .Single(); + } + + /// + /// Returns the full directory name from the specified , properly handling both + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments and sanitizing + /// each of the remaining segments. + /// + /// The path from which to extract the directory name. + /// An optional value indicating that root segments should not be stripped. + /// An optional value indicating that path segments should not be sanitized. + /// An optional operating system override, for testing. + /// The directory name. + /// Thrown if the specified path is null. + public static string GetDirectoryNameSafely(string path, bool stripRoot = true, bool sanitize = true, OSPlatform? os = null) + { + ArgumentNullException.ThrowIfNull(path); + + var local = LocalizePath(path, os: os); + + if (stripRoot) + { + local = StripPathRoot(local); + } + + return string.Join(Path.DirectorySeparatorChar, local + .Split(Path.DirectorySeparatorChar) + .SkipLast(1) + .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); + } + /// /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). /// @@ -270,6 +318,21 @@ public static class FileSafety .Replace('\\', replacement); } + /// + /// Sanitizes the specified to make it suitable and safe on the local operating + /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified + /// . + /// + /// + /// This is an overload for that exists to improve understanding of intent at the + /// call site. + /// + /// The path segment. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path segment. + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) => SanitizeFilename(segment, replacement, os); + /// /// Sanitizes the specified to make it suitable and safe on the local operating system /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with -- cgit v1.2.3 From 062d282403cc03c3fdd4101742647be6a83d0329 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:40:29 -0500 Subject: extract StripPathRoot --- src/slskd/Common/FileSafety.cs | 23 ++++ .../Common/FileSafety/StripPathRootTests.cs | 150 +++++++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 93a91faa..a175ebbd 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -365,4 +365,27 @@ public static class FileSafety return string.Join(sep, segments); } + + /// + /// Removes the root of the specified , including Window's drive prefix (e.g. C:\), + /// UNC paths on any OS (e.g. \\server on Windows, //server on Linux), and drops the hashed prefix added by + /// Soulseek Qt to hide the path on disk (e.g. @@abcde). + /// + /// The path to strip. + /// An optional operating system override, for testing. + /// The path with the root stripped, if one was present. + public static string StripPathRoot(string path, OSPlatform? os = null) + { + // flip slashes the correct way + path = LocalizePath(path, os); + + // strip C:\ or //server, if present (regardless of slash variant) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + + return path; + } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs new file mode 100644 index 00000000..f3638c9e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -0,0 +1,150 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class StripPathRootTests + { + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.StripPathRoot("foo/bar"); + + Assert.NotNull(result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music/Artist")] + [InlineData("C:/Music/Artist", "Music/Artist")] + [InlineData("D:\\path\\to\\file", "path/to/file")] + [InlineData("Z:\\", "")] + [InlineData("Z:/", "")] + [InlineData("Z:", "")] // bare drive letter, no separator + [InlineData("c:\\Music", "Music")] // lowercase drive letter + [InlineData("A:/single", "single")] + public void Linux_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music\\Artist")] + [InlineData("C:/Music/Artist", "Music\\Artist")] + [InlineData("D:\\path\\to\\file", "path\\to\\file")] + [InlineData("Z:\\", "")] + [InlineData("Z:", "")] + [InlineData("c:\\Music", "Music")] + public void Windows_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "share/Music")] + [InlineData("//server/Music", "Music")] + [InlineData("//192.168.1.1/share/folder", "share/folder")] + [InlineData("//server", "")] // no path after server + public void Linux_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "share\\Music")] + [InlineData("\\\\server\\Music", "Music")] + [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] + [InlineData("\\\\server", "")] // no path after server + public void Windows_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "Music/Artist")] + [InlineData("@@abcdefgh/Music", "Music")] + [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] + public void Linux_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "Music\\Artist")] + [InlineData("@@abcdefgh\\Music", "Music")] + [InlineData("@@abcde/Music/Artist", "Music\\Artist")] + public void Windows_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abc/Music")] // only 3 alphanumeric chars — does not match + [InlineData("@@abcd/Music")] // only 4 — does not match + public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.StartsWith("@@", result); + } + + [Theory] + [InlineData("Music/Artist", "Music/Artist")] + [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("", "")] + [InlineData("foo", "foo")] + public void Linux_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Music\\Artist", "Music\\Artist")] + [InlineData("Artist\\Album\\song.flac", "Artist\\Album\\song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("foo", "foo")] + public void Windows_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/home/user/Music", "/home/user/Music")] + [InlineData("/Music", "/Music")] + [InlineData("/single", "/single")] + public void Linux_ReturnsUnchanged_Given_Single_ForwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\Music", "\\Music")] + [InlineData("\\home\\user", "\\home\\user")] + public void Windows_ReturnsUnchanged_Given_Single_BackwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} -- cgit v1.2.3 From 012b429f11d6c0247fa90a74c0367a112d45a84c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:00:35 -0500 Subject: add SanitizePathSegment --- src/slskd/Common/FileSafety.cs | 27 ++++-- .../Common/FileSafety/SanitizePathSegmentTests.cs | 99 ++++++++++++++++++++++ 2 files changed, 121 insertions(+), 5 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a175ebbd..7e8c3516 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,15 +323,32 @@ public static class FileSafety /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified /// . /// - /// - /// This is an overload for that exists to improve understanding of intent at the - /// call site. - /// /// The path segment. /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized path segment. - public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) => SanitizeFilename(segment, replacement, os); + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + { + var sanitized = SanitizeFilename(segment, replacement, os); + + // is is possible for the result of sanitization to produce path traversal strings, + // which would result in traversal when combined (or throw an error because of CombineSafely) + // this can happen either because the segment is already periods, or because the replacement + // character is a period and the input one or two invalid characters. + // if this happens we follow the principle of least surprise and return an empty string + // avoid using a period for replacement (don't let users choose) and we won't have this problem + if (sanitized is "." or "..") + { + if (replacement is '.') + { + return string.Empty; + } + + return replacement.ToString(); + } + + return sanitized; + } /// /// Sanitizes the specified to make it suitable and safe on the local operating system diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs new file mode 100644 index 00000000..72e6a21b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -0,0 +1,99 @@ +using System; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class SanitizePathSegmentTests + { + [Theory] + [InlineData('/')] + [InlineData('\\')] + public void Throws_Given_Slash_As_Replacement(char replacement) + { + var ex = Record.Exception(() => FileSafety.SanitizePathSegment("segment", replacement)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid in filenames", ex.Message); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Replaces_Traversal_Segments_With_Replacement(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal("_", s); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Returns_Empty_String_When_Replacement_Is_Period_And_Result_Would_Be_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '.'); + + Assert.Equal("", s); + } + + [Theory] + [InlineData("a.")] + [InlineData("..b")] + [InlineData("c..d")] + public void Preserves_Periods_In_Segment_If_Not_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal(input, s); + } + + [Fact] + public void Respects_Replacement_Character() + { + var s = FileSafety.SanitizePathSegment("???", replacement: '!'); + + Assert.Equal("!!!", s); + } + + [Theory] + [InlineData("clean", "clean")] + [InlineData("Artist - Album", "Artist - Album")] + [InlineData("Ünïcödé", "Ünïcödé")] + [InlineData("пользователь", "пользователь")] + public void Linux_ReturnsUnchanged_Given_Safe_Segment(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("has/slash", "has_slash")] + [InlineData("has\\backslash", "has_backslash")] + [InlineData("has/both\\types", "has_both_types")] + public void Linux_Replaces_Slashes(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("file:name", "file_name")] + [InlineData("file*name", "file_name")] + [InlineData("file?name", "file_name")] + [InlineData("file\"name", "file_name")] + [InlineData("file/name", "file_name")] + [InlineData("file\\name", "file_name")] + public void Windows_Replaces_InvalidCharacters(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} -- cgit v1.2.3 From ba3d4690e132a966567db40c8b778c5ed3922833 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:24:27 -0500 Subject: paths ending in a slash don't have a file --- src/slskd/Common/FileSafety.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 7e8c3516..6c1ce8b6 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -229,6 +229,11 @@ public static class FileSafety { ArgumentNullException.ThrowIfNull(path); + if (path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } + return LocalizePath(path, os) .Split(Path.DirectorySeparatorChar) .TakeLast(1) -- cgit v1.2.3 From b52215184538991dfe1012c1017437edeb2e7b70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:24:50 -0500 Subject: remove the option to strip the root when getting directory --- src/slskd/Common/FileSafety.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 6c1ce8b6..acbe273b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -247,22 +247,16 @@ public static class FileSafety /// each of the remaining segments. /// /// The path from which to extract the directory name. - /// An optional value indicating that root segments should not be stripped. /// An optional value indicating that path segments should not be sanitized. /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool stripRoot = true, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool sanitize = true, OSPlatform? os = null) { ArgumentNullException.ThrowIfNull(path); var local = LocalizePath(path, os: os); - if (stripRoot) - { - local = StripPathRoot(local); - } - return string.Join(Path.DirectorySeparatorChar, local .Split(Path.DirectorySeparatorChar) .SkipLast(1) -- cgit v1.2.3 From 957dd89b04e941a17efb76dbfa439a2a0f5157ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:34:27 -0500 Subject: more tests, make root stripping optional --- src/slskd/Common/FileSafety.cs | 22 +++-- .../FileSafety/GetDirectoryNameSafelyTests.cs | 90 ++++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 96 ++++++++++++++++++++++ .../Common/FileSafety/SanitizePathTests.cs | 30 +++---- 4 files changed, 214 insertions(+), 24 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index acbe273b..dcdaa00a 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -269,7 +269,7 @@ public static class FileSafety /// The path to convert. /// An optional operating system override, for testing. /// The converted path. - public static string LocalizePath(this string path, OSPlatform? os = null) + public static string LocalizePath(string path, OSPlatform? os = null) { os ??= Compute.OSPlatform(); @@ -281,7 +281,7 @@ public static class FileSafety /// /// Sanitizes the specified (or string intended to be used as or as part of a filename) /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and - /// and replacing any invalid characters with the specified . + /// replacing any invalid characters with the specified . /// /// The filename (or string intended to be used as/part of one). /// The character to substitute for invalid characters. @@ -356,22 +356,26 @@ public static class FileSafety /// /// The path. /// The character to substitute for invalid characters. + /// An optional value indicating whether to keep the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) { os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; // flip slashes the correct way - path = path.LocalizePath(os); + path = LocalizePath(path, os); - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = DriveRootRegex.Replace(path, string.Empty); - path = UncRootRegex.Replace(path, string.Empty); + if (!retainRoot) + { + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); - // strip @@abcde prefixes used by SoulseekQt to obscure paths - path = SoulseekQtRootRegex.Replace(path, string.Empty); + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs new file mode 100644 index 00000000..fd78fcaa --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -0,0 +1,90 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetDirectoryNameSafelyTests + { + [Fact] + public void Throws_Given_Null() + { + var ex = Record.Exception(() => FileSafety.GetDirectoryNameSafely(null)); + + Assert.NotNull(ex); + } + + [Fact] + public void Returns_Empty_Given_Empty() + { + var result = FileSafety.GetDirectoryNameSafely(""); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo.bar")] + public void Returns_Empty_Given_Bare_File(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("C:")] // bare drive letter — StripPathRoot removes it, nothing left + [InlineData("C:\\")] // drive root with trailing backslash + [InlineData("C:/")] // drive root with trailing forward slash + [InlineData("/")] // Unix-style root — no double-slash, not stripped; splits to ["", ""] + [InlineData("\\")] // single backslash root + [InlineData("//server")] // UNC root — StripPathRoot removes server, nothing left + [InlineData("\\\\server")] // UNC root, backslashes + public void Returns_Empty_Given_Root(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "Music\\Artist")] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + public void Returns_Directory_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters_In_Segments() + { + var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + + Assert.Equal("Music_\\Artist", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_In_Segments() + { + var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: false); + + Assert.Equal("Music*\\Artist", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac"); + var resultExplicit = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs new file mode 100644 index 00000000..a25da89b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -0,0 +1,96 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetFileNameSafelyTests + { + [Fact] + public void Throws_Given_Null() + { + var ex = Record.Exception(() => FileSafety.GetFileNameSafely(null)); + + Assert.NotNull(ex); + } + + [Fact] + public void Returns_Empty_Given_Empty() + { + var result = FileSafety.GetFileNameSafely(""); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("\\")] + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("//")] + [InlineData("\\\\")] + [InlineData("foo\\")] + [InlineData("foo//")] + [InlineData("C:\\foo//bar\\")] + [InlineData("C:/foo\\bar/")] + public void Returns_Empty_Given_Path_Ending_In_Separator(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("//server", "server")] + [InlineData("\\\\server", "server")] + public void Returns_LastSegment_Given_UncRoot(string input, string expected) + { + // StripPathRoot is not called; the last segment of the localized + split path is returned + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo", "foo")] + [InlineData("foo.bar", "foo.bar")] + [InlineData("foo\\bar", "bar")] + [InlineData("foo/bar", "bar")] + [InlineData("C:\\Music\\song.flac", "song.flac")] + [InlineData("C:/Music/song.flac", "song.flac")] + [InlineData("Music\\Artist\\song.flac", "song.flac")] + [InlineData("//server/share/song.flac", "song.flac")] + [InlineData("\\\\server\\share\\song.flac", "song.flac")] + public void Returns_Filename_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false); + + Assert.Equal("file:name.flac", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac"); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index ea5b8538..2f712334 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -10,7 +10,7 @@ public partial class FileSafetyTests [Fact] public void NullOs_UsesPlatformDefault_DoesNotThrow() { - var result = "foo/bar".SanitizePath(); + var result = FileSafety.SanitizePath("foo/bar"); Assert.NotNull(result); } @@ -22,7 +22,7 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/пользователь", "Ünïcödé/пользователь")] public void Linux_NormalizesSlashes(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -33,7 +33,7 @@ public partial class FileSafetyTests [InlineData("Artist/Album/song.flac", "Artist\\Album\\song.flac")] public void Windows_NormalizesSlashes(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -45,7 +45,7 @@ public partial class FileSafetyTests [InlineData("Z:\\", "")] public void Windows_Strips_DriveRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -56,7 +56,7 @@ public partial class FileSafetyTests [InlineData("D:\\path", "path")] public void Linux_Strips_DriveRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -67,7 +67,7 @@ public partial class FileSafetyTests [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] public void Windows_Strips_UncRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -78,7 +78,7 @@ public partial class FileSafetyTests [InlineData("//192.168.1.1/share/folder", "share/folder")] public void Linux_Strips_UncRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -89,7 +89,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] public void Linux_Strips_SoulseekQtPrefix(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -100,7 +100,7 @@ public partial class FileSafetyTests [InlineData("@@abcde/Music/Artist", "Music\\Artist")] public void Windows_Strips_SoulseekQtPrefix(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -110,7 +110,7 @@ public partial class FileSafetyTests [InlineData("@@abcd/Music")] // only 4 — does not match public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.StartsWith("@@", result); } @@ -124,7 +124,7 @@ public partial class FileSafetyTests [InlineData("foo/.", "foo/_")] public void Linux_Replaces_TraversalSegments(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -135,7 +135,7 @@ public partial class FileSafetyTests [InlineData("..\\etc", "_\\etc")] public void Windows_Replaces_TraversalSegments(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -143,7 +143,7 @@ public partial class FileSafetyTests [Fact] public void Linux_Replaces_InvalidFilenameChars_In_Segments() { - var result = "seg\0ment/file\0name".SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OSPlatform.Linux); Assert.Equal("seg_ment/file_name", result); } @@ -151,7 +151,7 @@ public partial class FileSafetyTests [Fact] public void Windows_Replaces_InvalidFilenameChars_In_Segments() { - var result = "seg*ment\\file:name".SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OSPlatform.Windows); Assert.Equal("seg_ment\\file_name", result); } @@ -159,7 +159,7 @@ public partial class FileSafetyTests [Fact] public void Uses_Custom_Replacement() { - var result = "foo/../bar".SanitizePath(replacement: '-', os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OSPlatform.Linux); Assert.Equal("foo/-/bar", result); } -- cgit v1.2.3 From 3003f80c16af1d551b9d6e484c566c7d69c061a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:52:50 -0500 Subject: make slskqt regex slash optional --- src/slskd/Common/FileSafety.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index dcdaa00a..479f7834 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -62,7 +62,7 @@ public static class FileSafety private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants - private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]?", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix /// /// An alternative to that disallows rooted segments in the second or -- cgit v1.2.3 From 058b02ea093f4d7867441d055bef2b857eb98dd0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:54:01 -0500 Subject: always split by both slashes --- src/slskd/Common/FileSafety.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 479f7834..ebd9a69c 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -130,7 +130,7 @@ public static class FileSafety } } - var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); + var parts = segment.Split('\\', '/'); // ensure the segments we're combining don't contain traversal segments "." or ".." // untrusted input could use this to "break out" of the root directory and access sensitive areas @@ -234,8 +234,7 @@ public static class FileSafety return null; } - return LocalizePath(path, os) - .Split(Path.DirectorySeparatorChar) + var segments = localPath.Split('/', '\\'); .TakeLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) .Single(); @@ -258,7 +257,7 @@ public static class FileSafety var local = LocalizePath(path, os: os); return string.Join(Path.DirectorySeparatorChar, local - .Split(Path.DirectorySeparatorChar) + .Split('/', '\\') .SkipLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); } @@ -379,7 +378,7 @@ public static class FileSafety // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path - .Split(sep) + .Split('/', '\\') .Select(s => SanitizeFilename(s, replacement, os)) .Select(s => s is "." or ".." ? replacement.ToString() : s); -- cgit v1.2.3 From 2926ef6ee1c9151d72ae9ab5d713630b299224ed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:54:32 -0500 Subject: use method instead of inline --- src/slskd/Common/FileSafety.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index ebd9a69c..011a7a70 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -369,11 +369,7 @@ public static class FileSafety if (!retainRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) - path = DriveRootRegex.Replace(path, string.Empty); - path = UncRootRegex.Replace(path, string.Empty); - - // strip @@abcde prefixes used by SoulseekQt to obscure paths - path = SoulseekQtRootRegex.Replace(path, string.Empty); + path = StripPathRoot(path); } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings -- cgit v1.2.3 From 3e52de31aad47a3a333c64ef1b68f8abcf726fe8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:55:07 -0500 Subject: fix GetFileNameSafely test cases --- src/slskd/Common/FileSafety.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 011a7a70..9c8fac74 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -224,17 +224,22 @@ public static class FileSafety /// An optional value indicating that invalid characters should not be replaced. /// An optional operating system override, for testing. /// The extracted filename. - /// Thrown if the specified path is null. public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) { - ArgumentNullException.ThrowIfNull(path); + if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } - if (path.EndsWith('/') || path.EndsWith('\\')) + if (StripPathRoot(path, os) == string.Empty) { return null; } + var localPath = LocalizePath(path, os); var segments = localPath.Split('/', '\\'); + + return segments .TakeLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) .Single(); @@ -254,7 +259,7 @@ public static class FileSafety { ArgumentNullException.ThrowIfNull(path); - var local = LocalizePath(path, os: os); + var local = LocalizePath(path, os); return string.Join(Path.DirectorySeparatorChar, local .Split('/', '\\') -- cgit v1.2.3 From 046c60b817144b46d82c4311d166e6ba78062a90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 17:48:57 -0500 Subject: i want to be done with this --- src/slskd/Common/FileSafety.cs | 60 ++++++-- .../Common/FileSafety/CombineSafelyTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 151 +++++++++++++++++---- .../Common/FileSafety/SanitizePathSegmentTests.cs | 2 +- 4 files changed, 180 insertions(+), 36 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 9c8fac74..1fff4b08 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -241,7 +241,7 @@ public static class FileSafety return segments .TakeLast(1) - .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s) .Single(); } @@ -251,20 +251,63 @@ public static class FileSafety /// each of the remaining segments. /// /// The path from which to extract the directory name. + /// An optional value indicating whether to keep the path's root, if present. /// An optional value indicating that path segments should not be sanitized. /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) { - ArgumentNullException.ThrowIfNull(path); + if (path is null or "") + { + return null; + } + + // a plain string is assumed to be a file. matches the behavior of the BCL method + if (!path.Contains('/') && !path.Contains('\\')) + { + return null; + } + + var isUNC = path.StartsWith("//") || path.StartsWith("\\\\"); + + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + var local = LocalizePath(path, os) + .TrimEnd('/', '\\'); // treat file-less paths the same as files + + var unrooted = StripPathRoot(local, os); - var local = LocalizePath(path, os); + // were given a root; C:\, //server, @@abcde + if (unrooted is null or "") + { + return null; + } + + if (!retainRoot) + { + local = unrooted; + } - return string.Join(Path.DirectorySeparatorChar, local + // strip empty segments + var segments = local .Split('/', '\\') + .Where(s => s is not "") + .ToArray(); + + // we were given all slashes, a file in the root, or some other case where + // only a file or subdirectory remains; no parent directory + if (segments.Length <= 1) + { + return null; + } + + var newPath = string.Join(sep, segments .SkipLast(1) - .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); + + return (retainRoot && isUNC) ? $"{sep}{sep}{newPath}" : newPath; } /// @@ -276,7 +319,6 @@ public static class FileSafety public static string LocalizePath(string path, OSPlatform? os = null) { os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); @@ -380,8 +422,8 @@ public static class FileSafety // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split('/', '\\') - .Select(s => SanitizeFilename(s, replacement, os)) - .Select(s => s is "." or ".." ? replacement.ToString() : s); + .Where(s => s is not "") + .Select(s => SanitizePathSegment(s, replacement, os)); return string.Join(sep, segments); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 2d496c4b..0ffa0129 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -103,6 +103,9 @@ public partial class FileSafetyTests [InlineData("用户/音乐")] [InlineData("ユーザー/音楽")] [InlineData("사용자/음악")] + [InlineData("foo\\bar\\baz\\qux\\deeply\\nested")] + [InlineData("foo/bar/baz/qux/deeply/nested")] + [InlineData("foo/bar\\baz/qux\\deeply/nested")] public void Combines_Safe_Segments(string segment) { var result = FileSafety.CombineSafely(Base, segment); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index fd78fcaa..07e4d485 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using Xunit; namespace slskd.Tests.Unit.Common; @@ -7,29 +8,29 @@ public partial class FileSafetyTests public class GetDirectoryNameSafelyTests { [Fact] - public void Throws_Given_Null() + public void Returns_Null_Given_Null() { - var ex = Record.Exception(() => FileSafety.GetDirectoryNameSafely(null)); + var result = FileSafety.GetDirectoryNameSafely(null); - Assert.NotNull(ex); + Assert.Null(result); } [Fact] - public void Returns_Empty_Given_Empty() + public void Returns_Null_Given_Empty() { var result = FileSafety.GetDirectoryNameSafely(""); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] [InlineData("foo")] [InlineData("foo.bar")] - public void Returns_Empty_Given_Bare_File(string input) + public void Returns_Null_Given_Bare_File(string input) { var result = FileSafety.GetDirectoryNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] @@ -40,51 +41,149 @@ public partial class FileSafetyTests [InlineData("\\")] // single backslash root [InlineData("//server")] // UNC root — StripPathRoot removes server, nothing left [InlineData("\\\\server")] // UNC root, backslashes - public void Returns_Empty_Given_Root(string input) + public void Returns_Null_Given_Root(string input) { var result = FileSafety.GetDirectoryNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); + } + + [Fact] + public void Sanitizes_Path_When_Sanitize_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: true); + + Assert.DoesNotContain('\0', result); + } + + [Fact] + public void Does_Not_Sanitize_Path_When_Sanitize_False() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: false); + + Assert.Contains('\0', result); + } + + [Fact] + public void Sanitize_Defaults_To_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz"); + + Assert.DoesNotContain('\0', result); } [Theory] - [InlineData("foo\\bar", "foo")] + [InlineData("\\foo\\\\bar\\\\baz", "foo\\bar")] + [InlineData("/foo//bar//baz", "foo\\bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\foo\\\\bar\\\\baz", "foo/bar")] + [InlineData("/foo//bar//baz", "foo/bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] [InlineData("C:\\Music\\song.flac", "Music")] [InlineData("C:/Music/song.flac", "Music")] - [InlineData("C:\\Music\\Artist\\song.flac", "Music\\Artist")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic/Artist")] + [InlineData("C:\\foo.txt", null)] [InlineData("//server/share/song.flac", "share")] [InlineData("\\\\server\\share\\song.flac", "share")] - public void Returns_Directory_Given_Path_With_File(string input, string expected) + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); Assert.Equal(expected, result); } - [Fact] - public void Sanitize_True_Replaces_InvalidCharacters_In_Segments() + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic\\Artist")] + [InlineData("C:\\foo.txt", null)] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); - Assert.Equal("Music_\\Artist", result); + Assert.Equal(expected, result); } - [Fact] - public void Sanitize_False_Preserves_InvalidCharacters_In_Segments() + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C_\\Music")] + [InlineData("C:/Music/song.flac", "C_\\Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C_\\Music\\Artist")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\server\\share\\song.flac", "\\\\server\\share")] + [InlineData("@@abcde\\foo\\bar", "@@abcde\\foo")] + public void Retains_Path_Root_When_RetainRoot_True_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: false); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); - Assert.Equal("Music*\\Artist", result); + Assert.Equal(expected, result); } - [Fact] - public void Default_Sanitize_Is_True() + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C:/Music")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C:/Music/Artist")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\server\\share\\song.flac", "//server/share")] + [InlineData("@@abcde\\foo\\bar", "@@abcde/foo")] + public void Retains_Path_Root_When_RetainRoot_True_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:\\Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:\\Music")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\serv?er\\share\\song.flac", "\\\\serv?er\\share")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde\\fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde\\fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Windows(string input, string expected) { - var resultDefault = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac"); - var resultExplicit = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Windows); - Assert.Equal(resultExplicit, resultDefault); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:/Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\serv?er\\share\\song.flac", "//serv?er/share")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde/fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde/fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 72e6a21b..27dcf925 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -54,7 +54,7 @@ public partial class FileSafetyTests [Fact] public void Respects_Replacement_Character() { - var s = FileSafety.SanitizePathSegment("???", replacement: '!'); + var s = FileSafety.SanitizePathSegment("\0\0\0", replacement: '!'); Assert.Equal("!!!", s); } -- cgit v1.2.3 From cc5d80202e6f5973a0ce1bbdb30635392aa07ada Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 19:15:08 -0500 Subject: tweak root handling --- src/slskd/Common/FileSafety.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1fff4b08..650c082b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -247,7 +247,7 @@ public static class FileSafety /// /// Returns the full directory name from the specified , properly handling both - /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments and sanitizing + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing /// each of the remaining segments. /// /// The path from which to extract the directory name. @@ -269,7 +269,7 @@ public static class FileSafety return null; } - var isUNC = path.StartsWith("//") || path.StartsWith("\\\\"); + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -307,7 +307,12 @@ public static class FileSafety .SkipLast(1) .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); - return (retainRoot && isUNC) ? $"{sep}{sep}{newPath}" : newPath; + if (retainRoot) + { + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; } /// -- cgit v1.2.3 From 7239327610f020dcb9028a845709c79a5567869d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jun 2026 18:33:17 -0500 Subject: gracefully handle nulls --- src/slskd/Common/FileSafety.cs | 22 +++++++++++++++++++++- .../FileSafety/GetDirectoryNameSafelyTests.cs | 2 +- .../Common/FileSafety/LocalizePathTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizeFilenameTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizePathTests.cs | 9 +++++++++ .../Common/FileSafety/StripPathRootTests.cs | 8 ++++++++ 7 files changed, 63 insertions(+), 2 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 650c082b..9819209f 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,6 +323,11 @@ public static class FileSafety /// The converted path. public static string LocalizePath(string path, OSPlatform? os = null) { + if (path is null) + { + return null; + } + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -340,6 +345,11 @@ public static class FileSafety /// The sanitized filename. public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) { + if (filename is null) + { + return null; + } + if (replacement is '/' or '\\') { throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); @@ -412,6 +422,11 @@ public static class FileSafety /// The sanitized path. public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) { + if (path is null) + { + return null; + } + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -421,7 +436,7 @@ public static class FileSafety if (!retainRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path); + path = StripPathRoot(path, os); } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings @@ -443,6 +458,11 @@ public static class FileSafety /// The path with the root stripped, if one was present. public static string StripPathRoot(string path, OSPlatform? os = null) { + if (path is null) + { + return null; + } + // flip slashes the correct way path = LocalizePath(path, os); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index ff64e90d..3d89e9f5 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -112,7 +112,7 @@ public partial class FileSafetyTests [InlineData("\\\\server\\file.txt", "\\\\server")] [InlineData("@@abcde/file.txt", "@@abcde")] [InlineData("@@abcde\\file.txt", "@@abcde")] - public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) + public void Returns_Sanitized_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) { var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index 160f2a72..0b3eb81e 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -54,5 +54,13 @@ public partial class FileSafetyTests Assert.False(string.IsNullOrEmpty(result)); } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.LocalizePath(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 34e969d4..c0334d9b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -152,5 +152,13 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizeFilename(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 27dcf925..d322179b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -95,5 +95,13 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizePathSegment(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 2f712334..92a9e62c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -163,5 +163,14 @@ public partial class FileSafetyTests Assert.Equal("foo/-/bar", result); } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.SanitizePath(null); + + Assert.Null(result); + } + } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index f3638c9e..1ec2021d 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -15,6 +15,14 @@ public partial class FileSafetyTests Assert.NotNull(result); } + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.StripPathRoot(null); + + Assert.Null(result); + } + [Theory] [InlineData("C:\\Music\\Artist", "Music/Artist")] [InlineData("C:/Music/Artist", "Music/Artist")] -- cgit v1.2.3 From 16271c5f89dd6b8a5af4690fc2813285ce797dad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jun 2026 18:43:16 -0500 Subject: add leading slashes back when SanitizePath and retainRoot = true --- src/slskd/Common/FileSafety.cs | 13 ++- .../Common/FileSafety/SanitizePathTests.cs | 93 ++++++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 9819209f..5a5d964e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -309,6 +309,7 @@ public static class FileSafety if (retainRoot) { + // leading slashes are stripped of leading slashes by Split() so we must add them back return new string(sep, leadingSlashCount) + newPath; } @@ -427,6 +428,8 @@ public static class FileSafety return null; } + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -445,7 +448,15 @@ public static class FileSafety .Where(s => s is not "") .Select(s => SanitizePathSegment(s, replacement, os)); - return string.Join(sep, segments); + var newPath = string.Join(sep, segments); + + if (retainRoot) + { + // leading slashes are stripped of leading slashes by Split() so we must add them back + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; } /// diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 92a9e62c..f36e53de 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -1,3 +1,4 @@ +using System; using System.Runtime.InteropServices; using Xunit; @@ -172,5 +173,97 @@ public partial class FileSafetyTests Assert.Null(result); } + // --- retainRoot: true --- + // These verify that SanitizePath honours retainRoot. The UNC and single-slash absolute + // cases are EXPECTED TO FAIL: SanitizePath filters empty segments produced by splitting on + // leading slashes, so "//server/share" becomes "server/share" — the root is silently lost. + // Drive-letter and @@-prefix cases pass because they produce no empty segments. + + + [Theory] + [InlineData("C:/Music/Artist", "C:/Music/Artist")] + [InlineData("C:\\Music\\Artist", "C:/Music/Artist")] + public void Linux_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "C_\\Music\\Artist")] + [InlineData("C:/Music/Artist", "C_\\Music\\Artist")] + public void Windows_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "@@abcde/Music/Artist")] + [InlineData("@@abcde\\Music\\Artist", "@@abcde/Music/Artist")] + public void Linux_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "@@abcde\\Music\\Artist")] + [InlineData("@@abcde/Music/Artist", "@@abcde\\Music\\Artist")] + public void Windows_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "//server/share/Music")] + [InlineData("//server/Music", "//server/Music")] + [InlineData("\\\\server\\share\\Music", "//server/share/Music")] + [InlineData("\\\\server\\Music", "//server/Music")] + public void Linux_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/absolute/Music", "/absolute/Music")] + [InlineData("/single", "/single")] + [InlineData("\\absolute\\Music", "/absolute/Music")] + [InlineData("\\single", "/single")] + public void Linux_RetainsAbsoluteRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "\\\\server\\share\\Music")] + [InlineData("\\\\server\\Music", "\\\\server\\Music")] + [InlineData("//server/share/Music", "\\\\server\\share\\Music")] + [InlineData("//server/Music", "\\\\server\\Music")] + public void Windows_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\absolute\\Music", "\\absolute\\Music")] + [InlineData("/absolute/Music", "\\absolute\\Music")] + public void Windows_RetainsDriveRelativeRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } } } -- cgit v1.2.3 From 31a9b5918d49650564c4b59c8ae95a16412bef9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:18:03 -0500 Subject: use OperatingSystem instead of the other thing --- src/slskd/Common/FileSafety.cs | 55 +++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 25 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 5a5d964e..b72d3749 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -35,7 +35,6 @@ namespace slskd; using System; using System.IO; using System.Linq; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; /// @@ -85,7 +84,7 @@ public static class FileSafety /// The combined path. /// Thrown if the root, list of segments, or one or more segments is null. /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. - public static string CombineSafely(string root, OSPlatform? os, params string[] segments) + public static string CombineSafely(string root, OperatingSystem? os, params string[] segments) { // ensure no inputs are null. matches the behavior of Path.Combine() if (string.IsNullOrWhiteSpace(root)) @@ -103,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows(); + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); foreach (var segment in segments) { @@ -170,15 +169,18 @@ public static class FileSafety /// The path to check. /// An optional operating system override, for testing. /// True if the path is absolute, false otherwise. - public static bool IsPathAbsolute(string path, OSPlatform? os = null) + public static bool IsPathAbsolute(string path, OperatingSystem? os = null) { if (string.IsNullOrEmpty(path)) { return false; } - if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows()) + Console.WriteLine($"IsPathAbsolute? path: {path}, os: {os}, iswindows? {System.OperatingSystem.IsWindows()}"); + + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { + Console.WriteLine("Windows!"); // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows if (path.Length >= 3 @@ -198,6 +200,8 @@ public static class FileSafety return false; } + Console.WriteLine("Linux!"); + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / if (path.StartsWith('/')) { @@ -214,7 +218,7 @@ public static class FileSafety /// The path to check. /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. - public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); /// /// Returns the filename from the specified , properly @@ -224,7 +228,7 @@ public static class FileSafety /// An optional value indicating that invalid characters should not be replaced. /// An optional operating system override, for testing. /// The extracted filename. - public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) { @@ -256,7 +260,7 @@ public static class FileSafety /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "") { @@ -271,8 +275,8 @@ public static class FileSafety var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; var local = LocalizePath(path, os) .TrimEnd('/', '\\'); // treat file-less paths the same as files @@ -322,15 +326,15 @@ public static class FileSafety /// The path to convert. /// An optional operating system override, for testing. /// The converted path. - public static string LocalizePath(string path, OSPlatform? os = null) + public static string LocalizePath(string path, OperatingSystem? os = null) { if (path is null) { return null; } - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); } @@ -344,7 +348,7 @@ public static class FileSafety /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized filename. - public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null) { if (filename is null) { @@ -356,9 +360,9 @@ public static class FileSafety throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); } - os ??= Compute.OSPlatform(); + os ??= Compute.OperatingSystem(); - var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; if (characters.Contains(replacement)) { @@ -388,7 +392,7 @@ public static class FileSafety /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized path segment. - public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null) { var sanitized = SanitizeFilename(segment, replacement, os); @@ -418,10 +422,10 @@ public static class FileSafety /// /// The path. /// The character to substitute for invalid characters. - /// An optional value indicating whether to keep the path's root, if present. + /// An optional value indicating whether to strip the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', bool stripRoot = false, OperatingSystem? os = null) { if (path is null) { @@ -430,13 +434,13 @@ public static class FileSafety var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (!retainRoot) + if (stripRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) path = StripPathRoot(path, os); @@ -450,9 +454,10 @@ public static class FileSafety var newPath = string.Join(sep, segments); - if (retainRoot) + if (!stripRoot) { - // leading slashes are stripped of leading slashes by Split() so we must add them back + // leading slashes are stripped by Split() so we must add them back, + // unless we intended to strip the root return new string(sep, leadingSlashCount) + newPath; } @@ -467,7 +472,7 @@ public static class FileSafety /// The path to strip. /// An optional operating system override, for testing. /// The path with the root stripped, if one was present. - public static string StripPathRoot(string path, OSPlatform? os = null) + public static string StripPathRoot(string path, OperatingSystem? os = null) { if (path is null) { -- cgit v1.2.3 From e5d362836ce8892487864170abdc31fc032989c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 08:07:48 -0500 Subject: fix junk --- src/slskd/Common/FileSafety.cs | 5 ---- .../Common/Validation/RelativePathAttribute.cs | 31 ++-------------------- 2 files changed, 2 insertions(+), 34 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index b72d3749..a07de6d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -176,11 +176,8 @@ public static class FileSafety return false; } - Console.WriteLine($"IsPathAbsolute? path: {path}, os: {os}, iswindows? {System.OperatingSystem.IsWindows()}"); - if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { - Console.WriteLine("Windows!"); // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows if (path.Length >= 3 @@ -200,8 +197,6 @@ public static class FileSafety return false; } - Console.WriteLine("Linux!"); - // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / if (path.StartsWith('/')) { diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 62185a42..1bdbd4fb 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -83,38 +83,11 @@ namespace slskd.Validation // OS == OperatingSystem.All or .Any; if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - // this can only be exercised via unit tests; OSPlatform can't be passeed as an attribute argument - // so, this takes precedent over PlatformAgnostic - if (!FileSafety.IsPathRelative(path, os: OS)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } - else - { - if (!PlatformAgnostic) - { - if (!FileSafety.IsPathRelative(path, os: null)) // this OS - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } - else - { - if (!FileSafety.IsPathRelative(path, os: OSPlatform.Linux)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - - if (!FileSafety.IsPathRelative(path, os: OSPlatform.Windows)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } } return ValidationResult.Success; } } -} +} \ No newline at end of file -- cgit v1.2.3 From fec423393232bc3b9b3a8b40ebeafb489c871e65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:24:26 -0500 Subject: don't strip roots or restore slashes --- src/slskd/Common/FileSafety.cs | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a07de6d1..73dd4b40 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -412,35 +412,26 @@ public static class FileSafety /// /// Sanitizes the specified to make it suitable and safe on the local operating system - /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with - /// the specified , and by dropping any path traversal segments. + /// by converting to the correct slashes, replacing any invalid characters with the specified + /// , and by dropping any path traversal segments. /// /// The path. /// The character to substitute for invalid characters. - /// An optional value indicating whether to strip the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - public static string SanitizePath(string path, char replacement = '_', bool stripRoot = false, OperatingSystem? os = null) + public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null) { if (path is null) { return null; } - var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OperatingSystem(); var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (stripRoot) - { - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path, os); - } - // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split('/', '\\') @@ -449,13 +440,6 @@ public static class FileSafety var newPath = string.Join(sep, segments); - if (!stripRoot) - { - // leading slashes are stripped by Split() so we must add them back, - // unless we intended to strip the root - return new string(sep, leadingSlashCount) + newPath; - } - return newPath; } -- cgit v1.2.3 From ee41b93605a380480a5f7d826e7ae0602cd52de1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:52:37 -0500 Subject: wip --- src/slskd/Common/FileSafety.cs | 6 +- .../Common/FileSafety/CombineSafelyTests.cs | 38 +++++++++++ .../FileSafety/ContainsTraversalSegmentsTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 79 ++++++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 32 +++++++++ .../Common/FileSafety/IsPathTests.cs | 3 + .../Common/FileSafety/LocalizePathTests.cs | 4 ++ .../Common/FileSafety/SanitizeFilenameTests.cs | 16 +++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 1 + .../Common/FileSafety/SanitizePathTests.cs | 36 ++++++++++ .../Common/FileSafety/StripPathRootTests.cs | 18 +++++ 11 files changed, 234 insertions(+), 2 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 73dd4b40..bf81da0e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -432,11 +432,13 @@ public static class FileSafety // flip slashes the correct way path = LocalizePath(path, os); - // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings, + // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement) var segments = path .Split('/', '\\') .Where(s => s is not "") - .Select(s => SanitizePathSegment(s, replacement, os)); + .Select(s => SanitizePathSegment(s, replacement, os)) + .Where(s => s is not ""); var newPath = string.Join(sep, segments); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index ee5a69d8..c3b69b12 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -218,6 +218,44 @@ public partial class FileSafetyTests } } + [Fact] + public void Returns_Root_Given_Single_Empty_Segment() + { + var result = FileSafety.CombineSafely(Base, ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Returns_Root_Given_All_Empty_Segments() + { + var result = FileSafety.CombineSafely(Base, "", ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Handles_Root_With_Trailing_Separator() + { + var rootWithTrailing = Base + Path.DirectorySeparatorChar; + var result = FileSafety.CombineSafely(rootWithTrailing, "foo"); + + Assert.StartsWith(ExpectedStartsWith, result); + Assert.EndsWith("foo", result); + } + + [Theory] + [InlineData("./foo")] + [InlineData("../bar")] + [InlineData("foo/../bar")] + public void Throws_ArgumentException_Given_TraversingRoot_With_Os_Override(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root, OperatingSystem.Linux, "segment")); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + [Theory] // Bare traversal [InlineData("..")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs index 205c87c2..f0b1a394 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -106,6 +106,9 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/..hidden")] [InlineData("пользователь/...dir")] [InlineData("用户/..名前")] + // Segments that look like traversal but have surrounding whitespace — not exact matches + [InlineData(" . ")] + [InlineData(" .. ")] public void Path_DoesNotContainTraversal(string path) { Assert.False(FileSafety.ContainsTraversalSegments(path)); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index 3ac48efd..eaeaa29f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -45,6 +45,14 @@ public partial class FileSafetyTests Assert.Null(result); } + [Fact] + public void Returns_Null_Given_Whitespace_Only() + { + var result = FileSafety.GetDirectoryNameSafely(" "); + + Assert.Null(result); + } + [Theory] [InlineData("foo")] [InlineData("foo.bar")] @@ -192,6 +200,77 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo/bar")] + public void Treats_Trailing_Slash_As_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo\\bar")] + public void Treats_Trailing_Slash_As_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o/bar", "fo\0o")] + [InlineData("C:/Mu\0sic/song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo\0o")] + [InlineData("C:\\Mu\0sic\\song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo/../bar/file.txt", "foo/../bar")] + [InlineData("../etc/file.txt", "../etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\..\\bar\\file.txt", "foo\\..\\bar")] + [InlineData("..\\etc\\file.txt", "..\\etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcd/foo/bar/file.txt")] + public void Short_Qt_Prefix_Treated_As_Segment_Linux(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.StartsWith("@@abcd", result); + } + [Theory] [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs index 2af5321e..59ba2b54 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -138,6 +138,38 @@ public partial class FileSafetyTests Assert.Equal(input, result); } + [Theory] + [InlineData("foo/.")] + [InlineData("foo/..")] + [InlineData("foo\\..")] + public void Sanitize_True_Replaces_Traversal_As_Last_Path_Segment(string input) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: true); + + Assert.Equal("_", result); + } + + [Theory] + [InlineData("foo/.", ".")] + [InlineData("foo/..", "..")] + [InlineData("foo\\..", "..")] + public void Sanitize_False_Preserves_Traversal_As_Last_Path_Segment(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: false); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo//bar.flac", "bar.flac")] + [InlineData("foo\\\\bar.flac", "bar.flac")] + public void Returns_Filename_Given_Double_Separator(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + [Theory] [InlineData("@@abcde/song.flac", "song.flac")] [InlineData("@@abcde\\song.flac", "song.flac")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs index df81c8e2..771a1ea0 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -22,6 +22,9 @@ public partial class FileSafetyTests [InlineData("C:\\Users\\Ünïcödé\\Music")] [InlineData("C:\\Users\\пользователь\\Музыка")] [InlineData("C:\\Users\\用户\\音乐")] + // lowercase drive letters + [InlineData("c:\\Music")] + [InlineData("a:/path")] // UNC paths (\\ prefix) [InlineData("\\\\server\\share")] [InlineData("\\\\server\\share\\folder")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index a6909438..f0fc196c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -20,6 +20,8 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] + [InlineData("/", "/")] + [InlineData("\\", "/")] public void Linux_NormalizesToForwardSlash(string input, string expected) { var result = FileSafety.LocalizePath(input, OperatingSystem.Linux); @@ -40,6 +42,8 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] + [InlineData("/", "\\")] + [InlineData("\\", "\\")] public void Windows_NormalizesToBackslash(string input, string expected) { var result = FileSafety.LocalizePath(input, OperatingSystem.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 8985edd4..c53b95fc 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -153,6 +153,22 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Fact] + public void Linux_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file\0name", '.', OperatingSystem.Linux); + + Assert.Equal("file.name", result); + } + + [Fact] + public void Windows_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file*name", '.', OperatingSystem.Windows); + + Assert.Equal("file.name", result); + } + [Fact] public void Returns_Null_Given_Null() { diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 82a583c0..230c9a89 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -123,6 +123,7 @@ public partial class FileSafetyTests [Theory] [InlineData("*")] [InlineData("*?")] + [InlineData("*.")] // one invalid char + one period → ".." public void Windows_Returns_EmptyString_When_Period_Replacement_Produces_Traversal(string input) { var result = FileSafety.SanitizePathSegment(input, replacement: '.', os: OperatingSystem.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 12ebdefa..61233e44 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -129,5 +129,41 @@ public partial class FileSafetyTests Assert.False(result.StartsWith('/') || result.StartsWith('\\')); } + + [Fact] + public void Linux_NeverReturns_LeadingSlash_When_First_Segment_Sanitizes_To_Empty() + { + // '\0' replaced with '.' produces "." — SanitizePathSegment converts that to "" + // joining ["", "foo"] with '/' would yield "/foo" without a guard + var result = FileSafety.SanitizePath("\0/foo", replacement: '.', os: OperatingSystem.Linux); + + Assert.False(result.StartsWith('/') || result.StartsWith('\\')); + } + + [Theory] + [InlineData("../..")] + [InlineData("./.")] + public void Linux_Replaces_All_Traversal_Segments(string input) + { + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); + + Assert.Equal("_/_", result); + } + + [Fact] + public void Linux_Handles_SoulseekQt_Prefixed_Path() + { + var result = FileSafety.SanitizePath("@@abcde/foo/bar", os: OperatingSystem.Linux); + + Assert.Equal("@@abcde/foo/bar", result); + } + + [Fact] + public void Windows_Sanitizes_Colon_In_Drive_Like_Segment() + { + var result = FileSafety.SanitizePath("C:/Music/song.flac", os: OperatingSystem.Windows); + + Assert.Equal("C_\\Music\\song.flac", result); + } } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index 469f5335..d547843b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -121,6 +121,24 @@ public partial class FileSafetyTests Assert.StartsWith("@@", result); } + [Fact] + public void Linux_Strips_Bare_SoulseekQtPrefix_Returning_Empty() + { + var result = FileSafety.StripPathRoot("@@abcde", OperatingSystem.Linux); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("//")] + public void Linux_ReturnsUnchanged_Given_Slash_Only_Path(string input) + { + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); + + Assert.Equal(input, result); + } + [Theory] [InlineData("Music/Artist", "Music/Artist")] [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] -- cgit v1.2.3 From 62134e78472a51ef0becff9c0850f635933ab506 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:16:57 -0500 Subject: stop using any Path.* method, because they are all fucked up and untestable --- src/slskd/Common/FileSafety.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index bf81da0e..1634ca7a 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,15 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } + root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + + if (segments.Length == 0) + { + return root; + } + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); + var sep = isWindows ? '\\' : '/'; foreach (var segment in segments) { @@ -139,11 +147,17 @@ public static class FileSafety } } - var combined = Path.Combine(root, Path.Combine(segments)); + segments = [.. segments + .Where(s => !string.IsNullOrEmpty(s)) + .Select(s => LocalizePath(s))]; + + var combined = string.Join(sep, [root, .. segments]); // 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))) + var expectedPrefix = root + sep; + + if (combined != root && !combined.StartsWith(expectedPrefix)) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } -- cgit v1.2.3 From 5ed58b906b98c0f1b06147ed4db18c9bc2f1ffdf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:18:18 -0500 Subject: small tweaks --- src/slskd/Common/FileSafety.cs | 14 ++++++---- .../Common/Validation/AbsolutePathAttribute.cs | 2 +- .../Common/Validation/RelativePathAttribute.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Common/FileSafety/CombineSafelyTests.cs | 32 +++------------------- .../Validation/RelativePathAttributeTests.cs | 2 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- .../DownloadService/DeriveDestinationTests.cs | 2 -- 8 files changed, 19 insertions(+), 43 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1634ca7a..bf8302d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + root = root.TrimEnd('/').TrimEnd('\\'); if (segments.Length == 0) { @@ -148,16 +148,18 @@ public static class FileSafety } segments = [.. segments - .Where(s => !string.IsNullOrEmpty(s)) - .Select(s => LocalizePath(s))]; + .Where(s => !string.IsNullOrEmpty(s))]; var combined = string.Join(sep, [root, .. segments]); + if (combined.TrimEnd('/').TrimEnd('\\') == root.TrimEnd('/').TrimEnd('\\')) + { + return combined; + } + // 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 - var expectedPrefix = root + sep; - - if (combined != root && !combined.StartsWith(expectedPrefix)) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index f2615315..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,7 +49,7 @@ namespace slskd.Validation OS = os; } - public OperatingSystem? OS { get; } + public OperatingSystem OS { get; } private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f691d4e5..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -63,7 +63,7 @@ namespace slskd.Validation { if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); } return ValidationResult.Success; @@ -72,7 +72,7 @@ namespace slskd.Validation // OS == OperatingSystem.All or .Any; if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0f7805ba..ad91ba2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -815,7 +815,7 @@ namespace slskd.Transfers.Downloads // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' // retains the path root, if there is one (Soulseek NS does this), which may not be what // people want, so possibly revisit and add StripPathRoot() - source_path = (FileSafety.GetDirectoryNameSafely(filename) ?? string.Empty).TrimEnd('/', '\\'); + source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\'); // name of the remote parent directory, so using the example above, 'Baz' source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); @@ -1249,7 +1249,7 @@ namespace slskd.Transfers.Downloads var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); - var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index c3b69b12..e40ce743 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -169,21 +169,9 @@ public partial class FileSafetyTests [InlineData("C:relative")] public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.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(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -201,21 +189,9 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.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(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/\\Music", result); } [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 8d1c16b3..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -130,7 +130,7 @@ public class RelativePathAttributeTests // Note: the implementation uses the same message for Current as for Any/All. // "on all operating systems" is misleading here since Current only validates // against the current (or injected) OS. - Assert.Equal("The Field field must be a relative path on all operating systems.", msg); + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); } [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 4d4e4969..370a722d 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -285,7 +285,7 @@ public class QueueDownloadBatchRequestTests 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); + Assert.Equal("The Destination field must be a relative path on all operating systems.", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index 4da05b24..f35ff452 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -499,7 +499,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; @@ -513,7 +512,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; -- cgit v1.2.3 From 12cf9ad6b33ae29e9e7caea20b205fadd45798bf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:18:18 -0500 Subject: small tweaks --- src/slskd/Common/FileSafety.cs | 14 ++++++---- .../Common/Validation/AbsolutePathAttribute.cs | 2 +- .../Common/Validation/RelativePathAttribute.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Common/FileSafety/CombineSafelyTests.cs | 32 +++------------------- .../Validation/RelativePathAttributeTests.cs | 2 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 4 +-- .../DownloadService/DeriveDestinationTests.cs | 2 -- 8 files changed, 20 insertions(+), 44 deletions(-) (limited to 'src/slskd/Common/FileSafety.cs') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1634ca7a..bf8302d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + root = root.TrimEnd('/').TrimEnd('\\'); if (segments.Length == 0) { @@ -148,16 +148,18 @@ public static class FileSafety } segments = [.. segments - .Where(s => !string.IsNullOrEmpty(s)) - .Select(s => LocalizePath(s))]; + .Where(s => !string.IsNullOrEmpty(s))]; var combined = string.Join(sep, [root, .. segments]); + if (combined.TrimEnd('/').TrimEnd('\\') == root.TrimEnd('/').TrimEnd('\\')) + { + return combined; + } + // 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 - var expectedPrefix = root + sep; - - if (combined != root && !combined.StartsWith(expectedPrefix)) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index f2615315..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,7 +49,7 @@ namespace slskd.Validation OS = os; } - public OperatingSystem? OS { get; } + public OperatingSystem OS { get; } private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f691d4e5..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -63,7 +63,7 @@ namespace slskd.Validation { if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); } return ValidationResult.Success; @@ -72,7 +72,7 @@ namespace slskd.Validation // OS == OperatingSystem.All or .Any; if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0f7805ba..ad91ba2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -815,7 +815,7 @@ namespace slskd.Transfers.Downloads // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' // retains the path root, if there is one (Soulseek NS does this), which may not be what // people want, so possibly revisit and add StripPathRoot() - source_path = (FileSafety.GetDirectoryNameSafely(filename) ?? string.Empty).TrimEnd('/', '\\'); + source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\'); // name of the remote parent directory, so using the example above, 'Baz' source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); @@ -1249,7 +1249,7 @@ namespace slskd.Transfers.Downloads var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); - var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index c3b69b12..e40ce743 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -169,21 +169,9 @@ public partial class FileSafetyTests [InlineData("C:relative")] public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.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(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -201,21 +189,9 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.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(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/\\Music", result); } [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 8d1c16b3..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -130,7 +130,7 @@ public class RelativePathAttributeTests // Note: the implementation uses the same message for Current as for Any/All. // "on all operating systems" is misleading here since Current only validates // against the current (or injected) OS. - Assert.Equal("The Field field must be a relative path on all operating systems.", msg); + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); } [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 4d4e4969..f608467b 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -285,7 +285,7 @@ public class QueueDownloadBatchRequestTests 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); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } @@ -300,7 +300,7 @@ public class QueueDownloadBatchRequestTests 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); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index 4da05b24..f35ff452 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -499,7 +499,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; @@ -513,7 +512,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; -- cgit v1.2.3