diff options
8 files changed, 20 insertions, 44 deletions
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<ArgumentException>(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<ArgumentException>(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 }; |
