From b3041a9daffa98a0acda701e5e6b26345a185bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:41:23 -0500 Subject: add validation and tests for batch request DTO --- .../API/DTO/QueueDownloadBatchRequestTests.cs | 212 +++++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs (limited to 'tests') diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs new file mode 100644 index 00000000..3863c649 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -0,0 +1,212 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using slskd.Transfers.API; +using Xunit; + +namespace slskd.Tests.Unit.Transfers.API.DTO; + +public class QueueDownloadBatchRequestTests +{ + private static (bool IsValid, List Results) Validate(object obj) + { + var results = new List(); + var isValid = Validator.TryValidateObject(obj, new ValidationContext(obj), results, validateAllProperties: true); + return (isValid, results); + } + + private static QueueDownloadBatchRequest ValidRequest() => new() + { + Username = "testuser", + }; + + public class Id_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Id = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-guid")] + [InlineData("b5bde3d1-4aba-4d64-b64a")] + public void NonGuid_Fails(string value) + { + var (isValid, _) = Validate(ValidRequest() with { Id = value }); + Assert.False(isValid); + } + + [Theory] + [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")] + [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")] + [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")] + public void ValidGuid_Passes(string value) + { + var (isValid, _) = Validate(ValidRequest() with { Id = value }); + Assert.True(isValid); + } + } + + public class SearchId_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-guid")] + [InlineData("b5bde3d1-4aba-4d64-b64a")] + public void NonGuid_Fails(string value) + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.False(isValid); + } + + [Theory] + [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")] + [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")] + [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")] + public void ValidGuid_Passes(string value) + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.True(isValid); + } + } + + public class Username_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = null }); + Assert.False(isValid); + } + + [Fact] + public void Empty_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + Assert.False(isValid); + } + + [Fact] + public void OneChar_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "a" }); + Assert.True(isValid); + } + + [Fact] + public void FiveHundredChars_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 500) }); + Assert.True(isValid); + } + + [Fact] + public void FiveHundredOneChars_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + } + } + + public class Files_Item + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void NullFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void EmptyFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void ValidFilename_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }); + Assert.True(isValid); + } + + [Fact] + public void NegativeSize_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + Assert.False(isValid); + } + + [Fact] + public void ZeroSize_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }); + Assert.True(isValid); + } + + [Fact] + public void PositiveSize_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 }); + Assert.True(isValid); + } + } + + public class Options_Destination + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + public void RelativePath_Passes(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.True(isValid); + } + + [Theory] + [InlineData("C:\\Music")] + [InlineData("/music")] + [InlineData("\\\\server\\share")] + public void AbsolutePath_Fails(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + } + } +} -- cgit v1.2.3 From c86fbec378b42dbd5ae6133c8ac706669f5709bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:59:32 -0500 Subject: require at least 1 file --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 + .../API/DTO/QueueDownloadBatchRequestTests.cs | 61 ++++++++++++++++++---- 2 files changed, 54 insertions(+), 9 deletions(-) (limited to 'tests') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 6d08f8f3..823a4e40 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -64,6 +64,8 @@ public record QueueDownloadBatchRequest /// /// The list of files to download. /// + [Required] + [MinLength(1)] public List Files { get; init; } = []; /// diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 3863c649..1f12d787 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -17,6 +17,7 @@ public class QueueDownloadBatchRequestTests private static QueueDownloadBatchRequest ValidRequest() => new() { Username = "testuser", + Files = [new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }], }; public class Id_Field @@ -38,8 +39,10 @@ public class QueueDownloadBatchRequestTests [InlineData("b5bde3d1-4aba-4d64-b64a")] public void NonGuid_Fails(string value) { - var (isValid, _) = Validate(ValidRequest() with { Id = value }); + var (isValid, results) = Validate(ValidRequest() with { Id = value }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Id field must be a valid GUID/UUIDv4", results[0].ErrorMessage); } [Theory] @@ -72,8 +75,10 @@ public class QueueDownloadBatchRequestTests [InlineData("b5bde3d1-4aba-4d64-b64a")] public void NonGuid_Fails(string value) { - var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + var (isValid, results) = Validate(ValidRequest() with { SearchId = value }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The SearchId field must be a valid GUID/UUIDv4", results[0].ErrorMessage); } [Theory] @@ -95,15 +100,19 @@ public class QueueDownloadBatchRequestTests [Fact] public void Omitted_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = null }); + var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Username field is required.", results[0].ErrorMessage); } [Fact] public void Empty_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Username field is required.", results[0].ErrorMessage); } [Fact] @@ -123,8 +132,34 @@ public class QueueDownloadBatchRequestTests [Fact] public void FiveHundredOneChars_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + } + } + + public class Files_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Fails_WithRequiredMessage() + { + var (isValid, results) = Validate(ValidRequest() with { Files = null }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Files field is required.", results[0].ErrorMessage); + } + + [Fact] + public void EmptyList_Fails_WithMinLengthMessage() + { + var (isValid, results) = Validate(ValidRequest() with { Files = [] }); + Assert.False(isValid); + Assert.Single(results); + Assert.Contains("minimum length of '1'", results[0].ErrorMessage); } } @@ -136,15 +171,19 @@ public class QueueDownloadBatchRequestTests [Fact] public void NullFilename_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Filename field is required.", results[0].ErrorMessage); } [Fact] public void EmptyFilename_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); + Assert.Single(results); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -157,8 +196,10 @@ public class QueueDownloadBatchRequestTests [Fact] public void NegativeSize_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The field Size must be between 0 and 9.223372036854776E+18.", results[0].ErrorMessage); } [Fact] @@ -205,8 +246,10 @@ public class QueueDownloadBatchRequestTests [InlineData("\\\\server\\share")] public void AbsolutePath_Fails(string value) { - var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = 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); } } } -- cgit v1.2.3 From c00f611d37342dab1d0c0c5f5cd3264b2c8d0616 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:02:06 -0500 Subject: strip path traversal segments from configured paths --- .../Common/Validation/AbsolutePathAttribute.cs | 15 +- .../Common/Validation/RelativePathAttribute.cs | 15 +- .../Validation/AbsolutePathAttributeTests.cs | 231 +++++++++++++++++++++ .../Validation/RelativePathAttributeTests.cs | 131 ++++++++++++ 4 files changed, 372 insertions(+), 20 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs (limited to 'tests') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 9f6184ce..0eeb4a38 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -43,26 +43,21 @@ namespace slskd.Validation { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - var segments = path.Split('/', '\\'); - - if (segments.Any(s => string.IsNullOrEmpty(s))) + if (!Path.IsPathRooted(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); } + var segments = path.Split('/', '\\'); + if (segments.Any(s => s == ".." || s == ".")) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } - - if (!string.IsNullOrEmpty(path) && !Path.IsPathRooted(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); - } } return ValidationResult.Success; diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 3bd48766..824ff18d 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -43,26 +43,21 @@ namespace slskd.Validation { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - var segments = path.Split('/', '\\'); - - if (segments.Any(s => string.IsNullOrEmpty(s))) + if (Path.IsPathRooted(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } + var segments = path.Split('/', '\\'); + if (segments.Any(s => s == ".." || s == ".")) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } - - if (!string.IsNullOrEmpty(path) && Path.IsPathRooted(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } } return ValidationResult.Success; diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs new file mode 100644 index 00000000..03729eab --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -0,0 +1,231 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class AbsolutePathAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value) + { + var attribute = new AbsolutePathAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // paths can be null or empty; [Required] dictates whether they must be defined + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class Passes + { + // 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 — IsPathRooted returns true + [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); IsPathRooted returns true + public void Windows_DriveLetterPaths_Pass(string value) + { + var (isValid, _) = Validate(value); + 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 + public void Windows_RootPaths_Pass(string value) + { + var (isValid, _) = Validate(value); + 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) + { + var (isValid, _) = Validate(value); + 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) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // Unix/Linux absolute paths — always start with a leading / + [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 + public void Unix_Paths_Pass(string value) + { + var (isValid, _) = Validate(value); + 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) + { + var (isValid, _) = Validate(value); + 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) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + } + + // Paths containing . or .. segments, which are valid directory names in isolation + // but indicate traversal or ambiguity and must be rejected regardless of whether + // the path is otherwise absolute or relative. + public class Traversal_Fails + { + [Theory] + // Windows-style traversal + [InlineData("C:\\Music\\..\\Windows")] // traversal to sibling via backslash + [InlineData("C:\\Music\\.\\Artist")] // current-dir segment via backslash + [InlineData("C:/Music/../Windows")] // traversal via forward slash + [InlineData("C:/Music/./Artist")] // current-dir via forward slash + [InlineData("C:\\..")] // traversal at drive root + [InlineData("D:\\a\\b\\..\\c")] // traversal deep in path + // Unix-style traversal + [InlineData("/../etc")] // traversal at Unix root + [InlineData("/home/user/../etc")] // traversal to sibling on Unix + [InlineData("/home/user/./Music")] // current-dir on Unix + [InlineData("/home/../../etc")] // double traversal on Unix + // UNC traversal (backslash) + [InlineData("\\\\server\\..\\Windows")] // traversal past UNC server + [InlineData("\\\\server\\share\\..\\other")] // traversal within UNC share + [InlineData("\\\\server\\share\\.\\folder")] // current-dir within UNC share + // UNC traversal (forward slash) + [InlineData("//server/../share")] // traversal past server, forward slash + [InlineData("//server/share/../other")] // traversal within share, forward slash + public void TraversalSegment_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Contains("traversal segments", errorMessage); + } + } + + // Relative paths that have no empty segments and no traversal reach the + // final IsPathRooted check and fail there. + public class Relative_Fails + { + [Theory] + [InlineData("subdir")] // simple name + [InlineData("sub/dir")] // forward slash + [InlineData("sub\\dir")] // backslash + [InlineData("Artist\\Album")] // multi-level + [InlineData("music.flac")] // file name with extension + [InlineData("My Music")] // spaces + [InlineData("Ünïcödé")] // latin extended, still relative + [InlineData("Artist/Album/Song")] // deep relative + [InlineData("...dir")] // three dots — relative, not traversal + [InlineData(".hidden")] // dotfile — relative, not traversal + [InlineData("..")] // traversal-like but fundamentally not absolute + [InlineData(".")] // current-dir but fundamentally not absolute + public void RelativePath_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must specify 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 new file mode 100644 index 00000000..1692bceb --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -0,0 +1,131 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class RelativePathAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value) + { + var attribute = new RelativePathAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null and empty are explicitly allowed; presence is enforced by [Required] separately + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class Passes + { + [Theory] + [InlineData("Artist")] // simple name + [InlineData("music.flac")] // file with extension + [InlineData("My Artist")] // spaces + [InlineData("Artist.Name")] // dots that are not traversal + [InlineData("Artist/Album")] // forward slash + [InlineData("Artist\\Album")] // backslash + [InlineData("Artist/Album/Song.flac")] // multi-level forward slash + [InlineData("Artist\\Album\\Song.flac")] // multi-level backslash + [InlineData("Artist/Album\\Song.flac")] // mixed separators + [InlineData("...dir")] // three dots — not a traversal segment + [InlineData("..hidden")] // starts with .. but is a name, not traversal + [InlineData(".hidden")] // dotfile name, not a traversal segment + [InlineData("dir/..dir")] // segment starts with .. but is not exactly .. + [InlineData("Ünïcödé Àrtïst")] // latin extended + [InlineData("Ünïcödé/Àrtïst/Àlbüm")] // latin extended, forward slash + [InlineData("Ünïcödé\\Àrtïst\\Àlbüm")] // latin extended, backslash + [InlineData("пользователь/Музыка")] // Cyrillic, forward slash + [InlineData("пользователь\\Музыка\\Альбом")] // Cyrillic, backslash + [InlineData("用户/音乐/专辑")] // Chinese, forward slash + [InlineData("用户\\音乐\\专辑")] // Chinese, backslash + [InlineData("ユーザー/音楽/アルバム")] // Japanese, forward slash + [InlineData("ユーザー\\音楽\\アルバム")] // Japanese, backslash + [InlineData("사용자/음악/앨범")] // Korean, forward slash + [InlineData("사용자\\음악\\앨범")] // Korean, backslash + [InlineData("مستخدم/موسيقى")] // Arabic + [InlineData("χρήστης/μουσική")] // Greek + [InlineData("משתמש/מוזיקה")] // Hebrew + public void RelativePath_Passes(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + } + + public class Traversal_Fails + { + [Theory] + [InlineData("..")] // bare traversal + [InlineData(".")] // bare current-dir + [InlineData("../music")] // traversal prefix, forward slash + [InlineData("./music")] // current-dir prefix + [InlineData("music/../other")] // traversal in middle + [InlineData("music/./other")] // current-dir in middle + [InlineData("sub/../../escape")] // double traversal + [InlineData("music\\..")] // traversal via backslash + [InlineData("music\\.")] // current-dir via backslash + [InlineData("music/dir/..")] // traversal at end + [InlineData("a/b/c/../../d")] // multi-level traversal + [InlineData("Ünïcödé/../escape")] // latin extended with traversal + [InlineData("пользователь/../etc")] // Cyrillic with traversal + [InlineData("用户/音乐/../../escape")] // Chinese with deep traversal + [InlineData("ユーザー\\..\\escape")] // Japanese with backslash traversal + public void TraversalSegment_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Contains("traversal segments", errorMessage); + } + } + + public class Absolute_Fails + { + [Theory] + // Windows drive-letter paths + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("D:\\path\\to\\file")] + [InlineData("Z:/downloads")] + [InlineData("C:")] + // Windows root-relative (no drive letter) + [InlineData("\\Music")] + [InlineData("\\Music\\Artist\\Album")] + // Windows UNC + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\192.168.1.1\\share")] + // Unix/Linux + [InlineData("/")] + [InlineData("/home/user")] + [InlineData("/etc/hosts")] + [InlineData("/usr/local/bin")] + // macOS + [InlineData("/Users/username")] + [InlineData("/Volumes/External Drive")] + // Unix-style UNC (// prefix) + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + // Windows drive-relative (no separator after colon; still rooted) + [InlineData("C:Music")] + public void AbsolutePath_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must be a relative path.", errorMessage); + } + } +} -- cgit v1.2.3 From 6a6de665cd23a651a5fdb8df37034b0b07c93c98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 11:32:13 -0500 Subject: ensure traversal segments fail --- .../API/DTO/QueueDownloadBatchRequestTests.cs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 1f12d787..9fa4d304 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -241,9 +241,11 @@ public class QueueDownloadBatchRequestTests } [Theory] - [InlineData("C:\\Music")] - [InlineData("/music")] - [InlineData("\\\\server\\share")] + [InlineData("C:\\Music")] // Windows absolute + [InlineData("C:/Music")] // Windows absolute, forward slash + [InlineData("/music")] // Unix absolute + [InlineData("/home/user/Music")] // Unix absolute, deep + [InlineData("\\\\server\\share")] // UNC public void AbsolutePath_Fails(string value) { var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); @@ -251,5 +253,19 @@ public class QueueDownloadBatchRequestTests Assert.Single(results); Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); } + + [Theory] + [InlineData("../escape")] // traversal prefix + [InlineData("./music")] // current-dir prefix + [InlineData("music/../other")] // traversal in middle + [InlineData("sub/../../escape")] // double traversal + [InlineData("music\\..")] // traversal via backslash + public void TraversalSegment_Fails(string value) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + Assert.Single(results); + Assert.Contains("traversal segments", results[0].ErrorMessage); + } } } -- cgit v1.2.3 From 5de28546177a57b086e299d98d3077721aa9d868 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 15:57:52 -0500 Subject: add file safety functions --- src/slskd/Common/FileSafety.cs | 103 ++++++ tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 417 +++++++++++++++++++++++ 2 files changed, 520 insertions(+) create mode 100644 src/slskd/Common/FileSafety.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafetyTests.cs (limited to 'tests') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs new file mode 100644 index 00000000..a3899397 --- /dev/null +++ b/src/slskd/Common/FileSafety.cs @@ -0,0 +1,103 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 (Path.IsPathRooted(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; +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs new file mode 100644 index 00000000..ab4df5c4 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs @@ -0,0 +1,417 @@ +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 + { + // Paths that are rooted on all platforms + [Theory] + [InlineData("/Music")] // Unix absolute / Windows root-relative via forward slash + [InlineData("//server/share")] // Unix-style UNC + public void Throws_ArgumentException(string segment) + { + var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + // Paths that are only rooted on Windows; on Linux/macOS backslash is a valid filename character + // and "C:" is not a special prefix, so IsPathRooted returns false and they would not be rejected. + [Theory] + [InlineData("C:\\Music")] // Windows drive-letter absolute, backslash + [InlineData("C:/Music")] // Windows drive-letter absolute, forward slash + [InlineData("D:\\path")] // alternate drive letter + [InlineData("C:relative")] // Windows drive-relative; IsPathRooted returns true + [InlineData("\\Music")] // Windows root-relative, backslash + [InlineData("\\\\server\\share")] // Windows UNC + public void Throws_ArgumentException_WindowsOnly(string segment) + { + if (!OperatingSystem.IsWindows()) { return; } + + 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_WindowsOnly() + { + if (!OperatingSystem.IsWindows()) { return; } + + 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_WindowsOnly() + { + if (!OperatingSystem.IsWindows()) { return; } + + 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 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); + } + } +} -- cgit v1.2.3 From 166addef37753e1cb116721973b0fca8e25506ba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 17:50:33 -0500 Subject: GetInvalidPathChars() is invalid garbage --- src/slskd/Common/CommonExtensions.cs | 20 +-- .../ReplaceInvalidFileNameCharactersTests.cs | 144 +++++++++++++++++++++ 2 files changed, 145 insertions(+), 19 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs (limited to 'tests') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 89f1c328..8e6d5603 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -463,7 +463,7 @@ namespace slskd } var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidDirectoryNameCharacters(); + var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); return Path.Combine(directory, file); } @@ -486,24 +486,6 @@ namespace slskd return sanitized; } - /// - /// Replaces any occurrence of an invalid directory character with the specified . - /// - /// The path to sanitize. - /// The character with which to replace invalid characters. - /// The sanitized path. - public static string ReplaceInvalidDirectoryNameCharacters(this string path, char replacement = '_') - { - var sanitized = path; - - foreach (var c in Path.GetInvalidPathChars()) - { - sanitized = sanitized.Replace(c, replacement); - } - - return sanitized; - } - /// /// Converts a ModelStateDictionary into a human-readable format. /// diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs new file mode 100644 index 00000000..eff24587 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs @@ -0,0 +1,144 @@ +namespace slskd.Tests.Unit.Common.Extensions +{ + using System; + using System.IO; + using System.Linq; + using Xunit; + + public class ReplaceInvalidFileNameCharactersTests + { + [Fact] + public void Throws_NullReferenceException_Given_Null() + { + string path = null; + Assert.Throws(() => path.ReplaceInvalidFileNameCharacters()); + } + + [Fact] + public void Returns_Empty_String_Given_Empty_Input() + { + Assert.Equal(string.Empty, string.Empty.ReplaceInvalidFileNameCharacters()); + } + + [Fact] + public void Returns_Input_Unchanged_When_No_Invalid_Characters_Present() + { + var valid = "valid_filename.ext"; + Assert.Equal(valid, valid.ReplaceInvalidFileNameCharacters()); + } + + [Fact] + public void Preserves_Valid_Characters() + { + // Common valid filename chars that must not be touched + var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._- "; + Assert.Equal(valid, valid.ReplaceInvalidFileNameCharacters()); + } + + [Fact] + public void Default_Replacement_Character_Is_Underscore() + { + var c = Path.GetInvalidFileNameChars().First(); + var result = $"a{c}b".ReplaceInvalidFileNameCharacters(); + Assert.Equal("a_b", result); + } + + [Fact] + public void Replaces_Each_Invalid_Filename_Character_With_Default_Replacement() + { + // Each invalid char is tested individually so failures identify the exact offending char + Assert.All(Path.GetInvalidFileNameChars(), c => + { + var result = $"prefix{c}suffix".ReplaceInvalidFileNameCharacters(); + Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced"); + Assert.Equal("prefix_suffix", result); + }); + } + + [Fact] + public void Replaces_All_Invalid_Filename_Characters_Simultaneously() + { + var invalidChars = Path.GetInvalidFileNameChars(); + var allInvalid = new string(invalidChars); + var result = allInvalid.ReplaceInvalidFileNameCharacters(); + + Assert.All(invalidChars, c => + Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} remained after sanitization")); + } + + [Fact] + public void Result_Contains_Only_Replacement_Character_When_All_Input_Characters_Are_Invalid() + { + var invalidChars = Path.GetInvalidFileNameChars(); + var allInvalid = new string(invalidChars); + var result = allInvalid.ReplaceInvalidFileNameCharacters(); + + Assert.Equal(new string('_', invalidChars.Length), result); + } + + [Fact] + public void Uses_Custom_Replacement_Character() + { + char replacement = '-'; + + Assert.All(Path.GetInvalidFileNameChars(), c => + { + var result = $"a{c}b".ReplaceInvalidFileNameCharacters(replacement); + Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced"); + Assert.Equal("a-b", result); + }); + } + + [Fact] + public void Replaces_Consecutive_Invalid_Characters() + { + var chars = Path.GetInvalidFileNameChars(); + if (chars.Length < 2) + { + return; + } + + var input = $"a{chars[0]}{chars[1]}b"; + var result = input.ReplaceInvalidFileNameCharacters(); + + Assert.Equal("a__b", result); + } + + [Fact] + public void Replaces_Invalid_Character_At_Start_Of_String() + { + var c = Path.GetInvalidFileNameChars().First(); + var result = $"{c}filename.ext".ReplaceInvalidFileNameCharacters(); + Assert.Equal("_filename.ext", result); + } + + [Fact] + public void Replaces_Invalid_Character_At_End_Of_String() + { + var c = Path.GetInvalidFileNameChars().First(); + var result = $"filename.ext{c}".ReplaceInvalidFileNameCharacters(); + Assert.Equal("filename.ext_", result); + } + + [Fact] + public void Result_Contains_No_Invalid_Filename_Characters() + { + var invalidChars = Path.GetInvalidFileNameChars(); + var input = "valid" + new string(invalidChars) + "also_valid"; + var result = input.ReplaceInvalidFileNameCharacters(); + + Assert.All(invalidChars, c => + Assert.False(result.Contains(c), $"Character U+{(int)c:X4} remained after sanitization")); + } + + [Fact] + public void Valid_Characters_Surrounding_Invalid_Characters_Are_Preserved() + { + var c = Path.GetInvalidFileNameChars().First(); + var result = $"before{c}after".ReplaceInvalidFileNameCharacters(); + + Assert.StartsWith("before", result); + Assert.EndsWith("after", result); + } + } +} -- cgit v1.2.3 From fadc47b83a1d510ec10417010fba57fe39fb099b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 17:51:53 -0500 Subject: more tests for ToLocalRelativeFilename --- .../Extensions/ToLocalRelativeFilenameTests.cs | 141 ++++++++++++++++++--- 1 file changed, 124 insertions(+), 17 deletions(-) (limited to 'tests') diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs index 1012ddfa..2df21dd1 100644 --- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs @@ -1,6 +1,8 @@ namespace slskd.Tests.Unit.Common.Extensions { using System; + using System.IO; + using System.Linq; using Xunit; public class ToLocalRelativeFilenameTests @@ -18,36 +20,141 @@ namespace slskd.Tests.Unit.Common.Extensions } [Fact] - public void Returns_Localized_Filename_And_Parent_Directory() + public void Returns_Last_Directory_And_Filename_From_Deep_Path() { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) + var expected = "path" + Path.DirectorySeparatorChar + "file.ext"; + Assert.Equal(expected, @"deeply\nested\path\file.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Returns_Just_Filename_If_No_Directory_Given() + { + Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Replaces_Invalid_Characters_In_Filename() + { + // Exclude backslash and forward slash — they act as segment separators in the input + // and would cause the dirty string to be split rather than treated as a filename. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + var dirtyName = new string(invalidChars); + var result = $@"a\b\{dirtyName}".ToLocalRelativeFilename(); + var filename = Path.GetFileName(result); + + Assert.All(invalidChars, c => + Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename")); + } + + [Fact] + public void Replaces_Invalid_Characters_In_Directory() + { + // Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so the full + // GetInvalidFileNameChars() set applies (excluding path separators, which split the input). + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + var dirtyName = new string(invalidChars); + var result = $@"a\{dirtyName}\file.ext".ToLocalRelativeFilename(); + var directory = Path.GetDirectoryName(result); + + Assert.All(invalidChars, c => + Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory")); + } + + [Fact] + public void Replaces_Each_Invalid_Filename_Character_Individually() + { + // Tests each invalid filename char in isolation so that failures identify the exact + // offending character rather than only reporting that something in a concatenated + // string was not replaced. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + Assert.All(invalidChars, c => { - Assert.Equal(@"path\file.ext", "deeply/nested/path/file.ext".ToLocalRelativeFilename()); - } - else + var result = $@"a\b\prefix{c}suffix.ext".ToLocalRelativeFilename(); + var filename = Path.GetFileName(result); + Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename"); + }); + } + + [Fact] + public void Replaces_Each_Invalid_Filename_Character_In_Directory_Individually() + { + // Tests each invalid filename char in the directory segment in isolation so that + // failures identify the exact offending character. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + Assert.All(invalidChars, c => { - Assert.Equal(@"path/file.ext", @"C:\deeply\nested\path\file.ext".ToLocalRelativeFilename()); - } + var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); + var directory = Path.GetDirectoryName(result); + Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory"); + }); + } + [Fact] + public void Returns_Last_Directory_And_Filename_From_Two_Segment_Path() + { + var expected = "dir" + Path.DirectorySeparatorChar + "file.ext"; + Assert.Equal(expected, @"dir\file.ext".ToLocalRelativeFilename()); } [Fact] - public void Returns_Just_File_If_Only_File_Given() + public void Handles_Forward_Slash_As_Segment_Separator() { - Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); + // LocalizePath normalizes '/' to Path.DirectorySeparatorChar before splitting, + // so forward-slash paths must produce the same result as backslash paths. + var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; + Assert.Equal(expected, "a/b/c.ext".ToLocalRelativeFilename()); } [Fact] - public void Removes_Invalid_Characters_From_Path_And_Filename() + public void Handles_Mixed_Slash_Separators() { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - Assert.Equal(@"p_a_t_h\fi_le.ext", @"p?a|tle.ext".ToLocalRelativeFilename()); - } - else + var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; + Assert.Equal(expected, @"a/b\c.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Preserves_Spaces_In_Filename() + { + // Spaces are valid in file names and must survive sanitization. + var expected = "dir" + Path.DirectorySeparatorChar + "file name.ext"; + Assert.Equal(expected, @"root\dir\file name.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Preserves_Spaces_In_Directory() + { + var expected = "my dir" + Path.DirectorySeparatorChar + "file.ext"; + Assert.Equal(expected, @"root\my dir\file.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Directory_Segment_Contains_No_Characters_Invalid_For_Directory_Names() + { + // All GetInvalidFileNameChars() (minus separators) must be absent from the directory + // segment. Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so + // the full filename-invalid set applies. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + Assert.All(invalidChars, c => { - Assert.Equal(@"_", $"{'\0'}".ToLocalRelativeFilename()); - } + var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); + var directory = Path.GetDirectoryName(result); + Assert.False(directory.Contains(c), $"Character U+{(int)c:X4} is invalid for directory names but was not replaced"); + }); } } } -- cgit v1.2.3 From 298539af4b3d49733073bedd68862973596b9b00 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 12 May 2026 18:59:16 -0500 Subject: add DisallowedCharacters attribute, ensure no slashes in instance/agent name --- .../Validation/DisallowedCharactersAttribute.cs | 71 ++++++ src/slskd/Core/Options.cs | 2 + .../DisallowedCharactersAttributeTests.cs | 254 +++++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs (limited to 'tests') diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs new file mode 100644 index 00000000..90ed3d81 --- /dev/null +++ b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs @@ -0,0 +1,71 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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.Validation; + +using System.ComponentModel.DataAnnotations; +using System.Linq; + +/// +/// Validates that the value does not contain any of the characters. +/// +public class DisallowedCharactersAttribute : ValidationAttribute +{ + public DisallowedCharactersAttribute(params char[] disallowed) + { + Disallowed = disallowed; + } + + /// + /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . + /// + public bool IgnoreCase { get; set; } = true; + + private char[] Disallowed { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value is not null and string str) + { + var invalid = IgnoreCase + ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))) + : str.Where(c => Disallowed.Contains(c)); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + } + + return ValidationResult.Success; + } +} \ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7c391959..90a72f7d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,6 +198,7 @@ namespace slskd [Argument('i', "instance-name")] [EnvironmentVariable("INSTANCE_NAME")] [Description("optional; a unique name for this instance")] + [DisallowedCharacters('/', '\\')] [RequiresRestart] public string InstanceName { get; init; } = "default"; @@ -654,6 +655,7 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] + [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs new file mode 100644 index 00000000..4654fd25 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs @@ -0,0 +1,254 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class DisallowedCharactersAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + { + var attribute = new DisallowedCharactersAttribute(disallowed) { IgnoreCase = ignoreCase }; + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null and empty pass — [Required] handles presence; this attribute only checks content + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null, ['!']); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty, ['!']); + Assert.True(isValid); + } + + public class Passes + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + // Punctuation has no case variants — IgnoreCase must not affect the result either way + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NoDisallowedCharsPresent_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello", ['!', '@'], ignoreCase); + Assert.True(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void EmptyDisallowedSet_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!@#", [], ignoreCase); + Assert.True(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Unicode_AllowedChars_Pass_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("пользователь/音楽", ['!', '@'], ignoreCase); + Assert.True(isValid); + } + + [Fact] + public void NonString_Passes() + { + var attribute = new DisallowedCharactersAttribute('!'); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(42, context); + Assert.Equal(ValidationResult.Success, result); + } + + // IgnoreCase = false only: a disallowed letter in one case does not block the other case + [Fact] + public void CaseSensitive_LowerCaseDisallowed_DoesNotBlock_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: false); + Assert.True(isValid); + } + + [Fact] + public void CaseSensitive_UpperCaseDisallowed_DoesNotBlock_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: false); + Assert.True(isValid); + } + } + + public class Fails + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + // Punctuation has no case variants — IgnoreCase must not affect the result either way + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SingleDisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharAtStart_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("!hello", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharAtEnd_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharInMiddle_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hel!lo", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void OneOfMultipleDisallowedCharsPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MultipleDisallowedCharsAllPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharRepeated_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("he!lo!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AllCharsDisallowed_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("!@#", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Unicode_DisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("пользователь", ['е'], ignoreCase); + Assert.False(isValid); + } + + // IgnoreCase = true only: a disallowed letter blocks its other-case equivalent + [Fact] + public void IgnoreCase_LowerCaseDisallowed_Blocks_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: true); + Assert.False(isValid); + } + + [Fact] + public void IgnoreCase_UpperCaseDisallowed_Blocks_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: true); + Assert.False(isValid); + } + + [Fact] + public void CaseSensitive_ExactMatch_Fails() + { + var (isValid, _) = Validate("hello", ['h'], ignoreCase: false); + Assert.False(isValid); + } + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + [Fact] + public void DisplayName() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("Field", errorMessage); + } + + [Fact] + public void TheDisallowedChar() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("'!'", errorMessage); + } + + [Fact] + public void AllPresentDisallowedChars() + { + var (_, errorMessage) = Validate("h!@l", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.Contains("'@'", errorMessage); + } + + [Fact] + public void EachOccurrenceOfRepeatedChar() + { + // "he!lo!" has two '!' — both occurrences are listed + var (_, errorMessage) = Validate("he!lo!", ['!']); + Assert.Equal(2, errorMessage.Split("'!'").Length - 1); + } + + [Fact] + public void OnlyCharsActuallyPresent_NotAllDisallowedChars() + { + // '@' is disallowed but not in the value — must not appear in the message + var (_, errorMessage) = Validate("hello!", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.DoesNotContain("'@'", errorMessage); + } + + [Fact] + public void IgnoreCase_ShowsActualChar_NotDisallowedChar() + { + // 'a' is disallowed (lowercase); value contains 'A' (uppercase). + // The message reports what the user supplied ('A'), not the disallowed definition ('a'). + var (_, errorMessage) = Validate("A", ['a'], ignoreCase: true); + Assert.Contains("'A'", errorMessage); + Assert.DoesNotContain("'a'", errorMessage); + } + } +} -- cgit v1.2.3 From 8336a3c3ebdfc65dd7d7419f27c195a4aa729856 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 18:15:16 -0500 Subject: write our own logic for path relative/absolute --- src/slskd/Common/FileSafety.cs | 48 +++++- .../Common/Validation/AbsolutePathAttribute.cs | 11 +- .../Common/Validation/RelativePathAttribute.cs | 9 +- tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 176 ++++++++++++++++++--- .../Validation/AbsolutePathAttributeTests.cs | 8 +- 5 files changed, 209 insertions(+), 43 deletions(-) (limited to 'tests') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a3899397..f94b9c7b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -68,7 +68,7 @@ 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 (Path.IsPathRooted(segment)) + if (IsPathAbsolute(segment)) { throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); } @@ -100,4 +100,50 @@ public static class FileSafety /// 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 diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 0eeb4a38..4c9f5e53 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,8 +33,6 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.IO; - using System.Linq; /// /// Validates that the specified path is absolute. @@ -47,14 +45,13 @@ namespace slskd.Validation { var path = value.ToString(); - if (!Path.IsPathRooted(path)) + if (!FileSafety.IsPathAbsolute(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } - var segments = path.Split('/', '\\'); - - if (segments.Any(s => s == ".." || s == ".")) + // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here + if (FileSafety.ContainsTraversalSegments(path)) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 824ff18d..e8865554 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,8 +33,6 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.IO; - using System.Linq; /// /// Validates that the specified path is relative. @@ -47,14 +45,13 @@ namespace slskd.Validation { var path = value.ToString(); - if (Path.IsPathRooted(path)) + if (!FileSafety.IsPathRelative(path)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } - var segments = path.Split('/', '\\'); - - if (segments.Any(s => s == ".." || s == ".")) + // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here + if (FileSafety.ContainsTraversalSegments(path)) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs index ab4df5c4..a37e9e74 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs @@ -258,29 +258,17 @@ public class FileSafetyTests public class CombineSafely_Throws_ForRootedSegment { - // Paths that are rooted on all platforms [Theory] - [InlineData("/Music")] // Unix absolute / Windows root-relative via forward slash - [InlineData("//server/share")] // Unix-style UNC - public void Throws_ArgumentException(string segment) - { - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - // Paths that are only rooted on Windows; on Linux/macOS backslash is a valid filename character - // and "C:" is not a special prefix, so IsPathRooted returns false and they would not be rejected. - [Theory] - [InlineData("C:\\Music")] // Windows drive-letter absolute, backslash - [InlineData("C:/Music")] // Windows drive-letter absolute, forward slash + [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; IsPathRooted returns true + [InlineData("C:relative")] // Windows drive-relative [InlineData("\\Music")] // Windows root-relative, backslash [InlineData("\\\\server\\share")] // Windows UNC - public void Throws_ArgumentException_WindowsOnly(string segment) + public void Throws_ArgumentException(string segment) { - if (!OperatingSystem.IsWindows()) { return; } - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); Assert.Contains("Rooted", ex.Message); } @@ -294,10 +282,8 @@ public class FileSafetyTests } [Fact] - public void Throws_WhenLaterSegmentIsRooted_WindowsOnly() + public void Throws_WhenLaterSegmentIsRooted_Windows() { - if (!OperatingSystem.IsWindows()) { return; } - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, "valid", "C:\\escape")); Assert.Contains("Rooted", ex.Message); @@ -312,10 +298,8 @@ public class FileSafetyTests } [Fact] - public void Throws_WhenLastSegmentIsRooted_WindowsOnly() + public void Throws_WhenLastSegmentIsRooted_Windows() { - if (!OperatingSystem.IsWindows()) { return; } - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, "sub", "dir", "C:\\escape")); Assert.Contains("Rooted", ex.Message); @@ -371,6 +355,150 @@ public class FileSafetyTests } } + 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] diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 03729eab..53e25ac6 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -41,7 +41,7 @@ public class AbsolutePathAttributeTests [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 — IsPathRooted returns true + [InlineData("C:")] // bare drive [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic [InlineData("C:\\Users\\用户\\音乐")] // Chinese @@ -49,7 +49,7 @@ public class AbsolutePathAttributeTests [InlineData("C:\\Users\\사용자\\음악")] // Korean [InlineData("C:\\Users\\مستخدم\\موسيقى")] // Arabic [InlineData("C:\\Users\\χρήστης\\μουσική")] // Greek - [InlineData("C:Music")] // drive-relative (no separator); IsPathRooted returns true + [InlineData("C:Music")] // drive-relative (no separator) public void Windows_DriveLetterPaths_Pass(string value) { var (isValid, _) = Validate(value); @@ -204,8 +204,6 @@ public class AbsolutePathAttributeTests } } - // Relative paths that have no empty segments and no traversal reach the - // final IsPathRooted check and fail there. public class Relative_Fails { [Theory] @@ -225,7 +223,7 @@ public class AbsolutePathAttributeTests { var (isValid, errorMessage) = Validate(value); Assert.False(isValid); - Assert.Equal("The Field field must specify an absolute file path.", errorMessage); + Assert.Equal("The Field field must be an absolute file path.", errorMessage); } } } -- cgit v1.2.3 From 9039fd194f1f9cac0a6de54a68c17dead2eb65d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 09:32:13 -0500 Subject: add tests for GuidAttribute --- .../Common/Validation/GuidAttributeTests.cs | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs (limited to 'tests') diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs new file mode 100644 index 00000000..85522c18 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -0,0 +1,74 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class GuidAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(object value) + { + var attribute = new GuidAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null is allowed; [Required] dictates whether the field must be defined + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + public class Passes + { + [Theory] + [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens + [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens + [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) + [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format + [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format + [InlineData("00000000-0000-0000-0000-000000000000")] // all zeros + [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's + public void ValidGuidString_Passes(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + } + + public class Fails + { + [Fact] + public void EmptyString_Fails() + { + var (isValid, errorMessage) = Validate(string.Empty); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + } + + [Theory] + [InlineData("not-a-guid")] // arbitrary string + [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short + [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z + [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long + [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g + [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens + public void InvalidGuidString_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + } + + [Fact] + public void NonStringValue_Fails() + { + var (isValid, errorMessage) = Validate(42); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + } + } +} -- cgit v1.2.3 From c2055a762d3d5df2ac26845ca7a45a292cc6b6e1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 22:04:37 -0500 Subject: fix tests --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 2 +- tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs | 6 +++--- .../Transfers/API/DTO/QueueDownloadBatchRequestTests.cs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'tests') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 4fcb8d5a..ee3dfe2d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -351,7 +351,7 @@ namespace slskd.Transfers.API catch (Exception ex) { Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message); - return BadRequest("One or more provided identifiers is not a valid GUID/UUIDv4"); + return BadRequest("One or more provided identifiers is not a valid GUID/UUID"); } batchId ??= Guid.NewGuid(); diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index 85522c18..e574c130 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -46,7 +46,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(string.Empty); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } [Theory] @@ -60,7 +60,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(value); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } [Fact] @@ -68,7 +68,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(42); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } } } diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 9fa4d304..019e8cd5 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -42,7 +42,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Id = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Id field must be a valid GUID/UUIDv4", results[0].ErrorMessage); + Assert.Equal("The Id field must be a valid GUID/UUID", results[0].ErrorMessage); } [Theory] @@ -78,7 +78,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { SearchId = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The SearchId field must be a valid GUID/UUIDv4", results[0].ErrorMessage); + Assert.Equal("The SearchId field must be a valid GUID/UUID", results[0].ErrorMessage); } [Theory] -- cgit v1.2.3 From 8265857697b6116f97fc435d7313f0a8161b9e13 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:53:34 -0500 Subject: add NonTraversingPathAttribute --- .../Validation/NonTraversingPathAttribute.cs | 57 +++++++++++++ .../Validation/NonTraversingPathAttributeTests.cs | 94 ++++++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 src/slskd/Common/Validation/NonTraversingPathAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs (limited to 'tests') diff --git a/src/slskd/Common/Validation/NonTraversingPathAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs new file mode 100644 index 00000000..1e2616bd --- /dev/null +++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs @@ -0,0 +1,57 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the specified path does not contain traversal segments '.' or '..'. + /// + public class NonTraversingPathAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null && value is string str && !string.IsNullOrEmpty(str)) + { + var path = value.ToString(); + + if (FileSafety.ContainsTraversalSegments(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); + } + } + + return ValidationResult.Success; + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs new file mode 100644 index 00000000..12efb899 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs @@ -0,0 +1,94 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class NonTraversingPathAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value) + { + var attribute = new NonTraversingPathAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // paths can be null or empty; [Required] dictates whether they must be defined + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class NonTraversal_Passes + { + [Theory] + // Windows-style + [InlineData("C:\\Music\\foo\\Windows")] + [InlineData("C:/Music/foo/Windows")] + // Unix-style + [InlineData("/home/user/foo/etc")] + [InlineData("\\home\\user\\foo\\etc")] + // UNC (backslash) + [InlineData("\\\\server\\share\\foo\\folder")] + // UNC (forward slash) + [InlineData("//server/foo/share")] + // soulseek + [InlineData("@foo/bar/baz")] + [InlineData("@foo\\bar\\baz")] + // filenames + [InlineData("@foo/bar/baz/baz../..qux/file.ext")] + public void NonTraversalSegment_Passes(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.True(isValid); + Assert.Null(errorMessage); + } + } + + // Paths containing . or .. segments, which are valid directory names in isolation + // but indicate traversal or ambiguity and must be rejected regardless of whether + // the path is otherwise absolute or relative. + public class Traversal_Fails + { + [Theory] + // Windows-style + [InlineData("C:\\Music\\..\\Windows")] + [InlineData("C:\\Music\\.\\Artist")] + [InlineData("C:/Music/../Windows")] + [InlineData("C:/Music/./Artist")] + [InlineData("C:\\..")] + [InlineData("D:\\a\\b\\..\\c")] + // Unix-style + [InlineData("/../etc")] + [InlineData("/home/user/../etc")] + [InlineData("/home/user/./Music")] + [InlineData("/home/../../etc")] + // UNC (backslash) + [InlineData("\\\\server\\..\\Windows")] + [InlineData("\\\\server\\share\\..\\other")] + [InlineData("\\\\server\\share\\.\\folder")] + // UNC (forward slash) + [InlineData("//server/../share")] + [InlineData("//server/share/../other")] + // soulseek + [InlineData("@foo/bar/baz/baz/../file.ext")] + [InlineData("@foo/bar/baz/./../file.ext")] + [InlineData("@foo/bar/baz/./baz/file.ext")] + public void TraversalSegment_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Contains("traversal segments", errorMessage); + } + } +} -- cgit v1.2.3 From 8dc86c07d7e3c0ad82ad8e1c1c64b26a460774ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:14 -0500 Subject: tweak validation on batch request --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +++- .../API/DTO/QueueDownloadBatchRequestTests.cs | 47 ++++++++++++++++++---- 2 files changed, 45 insertions(+), 9 deletions(-) (limited to 'tests') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index fe539ce7..05a913bd 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -58,7 +58,8 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [StringLength(500, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [StringLength(maximumLength: 500)] public string Username { get; init; } /// @@ -80,7 +81,8 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] - [StringLength(int.MaxValue, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [NonTraversingPath] public string Filename { get; init; } /// @@ -96,5 +98,6 @@ public record EnqueueDownloadBatchOptions /// The destination directory for the files, relative to the configured download directory. /// [RelativePath] + [NonTraversingPath] public string Destination { get; init; } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 019e8cd5..2440291c 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -102,8 +102,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -111,8 +110,15 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); + } + + [Fact] + public void Whitespace_Fails() + { + var (isValid, results) = Validate(ValidRequest() with { Username = " " }); + Assert.False(isValid); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -173,8 +179,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Filename field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -182,7 +187,14 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); - Assert.Single(results); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); + } + + [Fact] + public void WhitespaceFilename_Fails() + { + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = " ", Size = 0 }); + Assert.False(isValid); Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } @@ -215,6 +227,27 @@ public class QueueDownloadBatchRequestTests var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 }); Assert.True(isValid); } + + [Theory] + [InlineData("@foo/bar/../baz/file.mp3")] + [InlineData("@foo/bar/./baz/file.mp3")] + [InlineData("@foo\\bar\\..\\baz\\file.mp3")] + public void TraversalSegmentInFilename_Fails(string value) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 }); + Assert.False(isValid); + Assert.Contains(results, r => r.ErrorMessage != null && r.ErrorMessage.Contains("traversal segments")); + } + + [Theory] + [InlineData("@foo/bar/baz/file.mp3")] + [InlineData("@foo/bar/baz/file..ext")] + [InlineData("@foo\\bar\\baz\\file.mp3")] + public void NonTraversalFilename_Passes(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 }); + Assert.True(isValid); + } } public class Options_Destination -- cgit v1.2.3 From 74810d42ea08d9782bd83a02d06eaca9c2ecd9a5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:53:07 -0500 Subject: add StringAttribute to cover all string related validation --- .../Validation/DisallowedCharactersAttribute.cs | 71 --- src/slskd/Common/Validation/StringAttribute.cs | 92 ++++ .../DisallowedCharactersAttributeTests.cs | 254 ---------- .../Common/Validation/StringAttributeTests.cs | 517 +++++++++++++++++++++ 4 files changed, 609 insertions(+), 325 deletions(-) delete mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 src/slskd/Common/Validation/StringAttribute.cs delete mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs (limited to 'tests') diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs deleted file mode 100644 index 90ed3d81..00000000 --- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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.Validation; - -using System.ComponentModel.DataAnnotations; -using System.Linq; - -/// -/// Validates that the value does not contain any of the characters. -/// -public class DisallowedCharactersAttribute : ValidationAttribute -{ - public DisallowedCharactersAttribute(params char[] disallowed) - { - Disallowed = disallowed; - } - - /// - /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . - /// - public bool IgnoreCase { get; set; } = true; - - private char[] Disallowed { get; } - - protected override ValidationResult IsValid(object value, ValidationContext validationContext) - { - if (value is not null and string str) - { - var invalid = IgnoreCase - ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))) - : str.Where(c => Disallowed.Contains(c)); - - if (invalid.Any()) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); - } - } - - return ValidationResult.Success; - } -} \ No newline at end of file diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs new file mode 100644 index 00000000..2fcf4283 --- /dev/null +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -0,0 +1,92 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.Linq; + using System.Text.RegularExpressions; + + /// + /// Validates that the value is not null or whitespace. + /// + public class StringAttribute : ValidationAttribute + { + public bool AllowNull { get; set; } = true; + public bool AllowEmpty { get; set; } = true; + public bool AllowWhiteSpace { get; set; } = true; + public char[] DisallowedCharacters { get; set; } = []; + public int MinimumLength { get; set; } = 0; + public int MaximumLength { get; set; } = int.MaxValue; + public Regex Pattern { get; set; } = null; + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + var val = (string)value; + + if (!AllowNull && val is null) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + } + + if (!AllowEmpty && val is "") + { + return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character"); + } + + // check this after empty to avoid overlap + if (!AllowWhiteSpace && string.IsNullOrWhiteSpace(val)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace"); + } + + if (val.Length < MinimumLength || val.Length > MaximumLength) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters"); + } + + var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + + if (Pattern is not null && Pattern.IsMatch(val)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}"); + } + + return ValidationResult.Success; + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs deleted file mode 100644 index 4654fd25..00000000 --- a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs +++ /dev/null @@ -1,254 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using slskd.Validation; -using Xunit; - -namespace slskd.Tests.Unit.Common.Validation; - -public class DisallowedCharactersAttributeTests -{ - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) - { - var attribute = new DisallowedCharactersAttribute(disallowed) { IgnoreCase = ignoreCase }; - var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; - var result = attribute.GetValidationResult(value, context); - return (result == null, result?.ErrorMessage); - } - - // null and empty pass — [Required] handles presence; this attribute only checks content - [Fact] - public void Null_Passes() - { - var (isValid, _) = Validate(null, ['!']); - Assert.True(isValid); - } - - [Fact] - public void EmptyString_Passes() - { - var (isValid, _) = Validate(string.Empty, ['!']); - Assert.True(isValid); - } - - public class Passes - { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) - => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); - - // Punctuation has no case variants — IgnoreCase must not affect the result either way - [Theory] - [InlineData(true)] - [InlineData(false)] - public void NoDisallowedCharsPresent_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("hello", ['!', '@'], ignoreCase); - Assert.True(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void EmptyDisallowedSet_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("hello!@#", [], ignoreCase); - Assert.True(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void Unicode_AllowedChars_Pass_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("пользователь/音楽", ['!', '@'], ignoreCase); - Assert.True(isValid); - } - - [Fact] - public void NonString_Passes() - { - var attribute = new DisallowedCharactersAttribute('!'); - var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; - var result = attribute.GetValidationResult(42, context); - Assert.Equal(ValidationResult.Success, result); - } - - // IgnoreCase = false only: a disallowed letter in one case does not block the other case - [Fact] - public void CaseSensitive_LowerCaseDisallowed_DoesNotBlock_UpperCase() - { - var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: false); - Assert.True(isValid); - } - - [Fact] - public void CaseSensitive_UpperCaseDisallowed_DoesNotBlock_LowerCase() - { - var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: false); - Assert.True(isValid); - } - } - - public class Fails - { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) - => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); - - // Punctuation has no case variants — IgnoreCase must not affect the result either way - [Theory] - [InlineData(true)] - [InlineData(false)] - public void SingleDisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("hello!", ['!'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void DisallowedCharAtStart_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("!hello", ['!'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void DisallowedCharAtEnd_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("hello!", ['!'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void DisallowedCharInMiddle_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("hel!lo", ['!'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void OneOfMultipleDisallowedCharsPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("hello!", ['!', '@', '#'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void MultipleDisallowedCharsAllPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void DisallowedCharRepeated_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("he!lo!", ['!'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void AllCharsDisallowed_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("!@#", ['!', '@', '#'], ignoreCase); - Assert.False(isValid); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void Unicode_DisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) - { - var (isValid, _) = Validate("пользователь", ['е'], ignoreCase); - Assert.False(isValid); - } - - // IgnoreCase = true only: a disallowed letter blocks its other-case equivalent - [Fact] - public void IgnoreCase_LowerCaseDisallowed_Blocks_UpperCase() - { - var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: true); - Assert.False(isValid); - } - - [Fact] - public void IgnoreCase_UpperCaseDisallowed_Blocks_LowerCase() - { - var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: true); - Assert.False(isValid); - } - - [Fact] - public void CaseSensitive_ExactMatch_Fails() - { - var (isValid, _) = Validate("hello", ['h'], ignoreCase: false); - Assert.False(isValid); - } - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) - => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); - - [Fact] - public void DisplayName() - { - var (_, errorMessage) = Validate("hello!", ['!']); - Assert.Contains("Field", errorMessage); - } - - [Fact] - public void TheDisallowedChar() - { - var (_, errorMessage) = Validate("hello!", ['!']); - Assert.Contains("'!'", errorMessage); - } - - [Fact] - public void AllPresentDisallowedChars() - { - var (_, errorMessage) = Validate("h!@l", ['!', '@']); - Assert.Contains("'!'", errorMessage); - Assert.Contains("'@'", errorMessage); - } - - [Fact] - public void EachOccurrenceOfRepeatedChar() - { - // "he!lo!" has two '!' — both occurrences are listed - var (_, errorMessage) = Validate("he!lo!", ['!']); - Assert.Equal(2, errorMessage.Split("'!'").Length - 1); - } - - [Fact] - public void OnlyCharsActuallyPresent_NotAllDisallowedChars() - { - // '@' is disallowed but not in the value — must not appear in the message - var (_, errorMessage) = Validate("hello!", ['!', '@']); - Assert.Contains("'!'", errorMessage); - Assert.DoesNotContain("'@'", errorMessage); - } - - [Fact] - public void IgnoreCase_ShowsActualChar_NotDisallowedChar() - { - // 'a' is disallowed (lowercase); value contains 'A' (uppercase). - // The message reports what the user supplied ('A'), not the disallowed definition ('a'). - var (_, errorMessage) = Validate("A", ['a'], ignoreCase: true); - Assert.Contains("'A'", errorMessage); - Assert.DoesNotContain("'a'", errorMessage); - } - } -} diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs new file mode 100644 index 00000000..dfa964f7 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -0,0 +1,517 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Text.RegularExpressions; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class StringAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + { + var attr = new StringAttribute(); + configure?.Invoke(attr); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attr.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // empty string passes all default checks — [Required] handles presence + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class DisallowedCharacters + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => StringAttributeTests.Validate(value, a => a.DisallowedCharacters = disallowed); + + public class Passes + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => DisallowedCharacters.Validate(value, disallowed); + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty, ['!']); + Assert.True(isValid); + } + + [Fact] + public void NoDisallowedCharsPresent_Passes() + { + var (isValid, _) = Validate("hello", ['!', '@']); + Assert.True(isValid); + } + + [Fact] + public void EmptyDisallowedSet_Passes() + { + var (isValid, _) = Validate("hello!@#", []); + Assert.True(isValid); + } + + [Fact] + public void Unicode_AllowedChars_Pass() + { + var (isValid, _) = Validate("пользователь/音楽", ['!', '@']); + Assert.True(isValid); + } + + // Case-insensitive matching only folds the declared disallowed chars, not all letters; + // a disallowed lower-case letter does not block an entirely different upper-case letter. + [Fact] + public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter() + { + var (isValid, _) = Validate("B", ['a']); + Assert.True(isValid); + } + } + + public class Fails + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => DisallowedCharacters.Validate(value, disallowed); + + [Fact] + public void SingleDisallowedChar_Fails() + { + var (isValid, _) = Validate("hello!", ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharAtStart_Fails() + { + var (isValid, _) = Validate("!hello", ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharAtEnd_Fails() + { + var (isValid, _) = Validate("hello!", ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharInMiddle_Fails() + { + var (isValid, _) = Validate("hel!lo", ['!']); + Assert.False(isValid); + } + + [Fact] + public void OneOfMultipleDisallowedCharsPresent_Fails() + { + var (isValid, _) = Validate("hello!", ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void MultipleDisallowedCharsAllPresent_Fails() + { + var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharRepeated_Fails() + { + var (isValid, _) = Validate("he!lo!", ['!']); + Assert.False(isValid); + } + + [Fact] + public void AllCharsDisallowed_Fails() + { + var (isValid, _) = Validate("!@#", ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void Unicode_DisallowedChar_Fails() + { + var (isValid, _) = Validate("пользователь", ['е']); + Assert.False(isValid); + } + + // character matching is always case-insensitive + [Fact] + public void LowerCaseDisallowed_Blocks_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o']); + Assert.False(isValid); + } + + [Fact] + public void UpperCaseDisallowed_Blocks_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O']); + Assert.False(isValid); + } + + [Fact] + public void ExactMatch_Fails() + { + var (isValid, _) = Validate("hello", ['h']); + Assert.False(isValid); + } + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => DisallowedCharacters.Validate(value, disallowed); + + [Fact] + public void TheDisallowedChar() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("'!'", errorMessage); + } + + [Fact] + public void AllPresentDisallowedChars() + { + var (_, errorMessage) = Validate("h!@l", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.Contains("'@'", errorMessage); + } + + [Fact] + public void EachOccurrenceOfRepeatedChar() + { + // "he!lo!" has two '!' — both occurrences are listed + var (_, errorMessage) = Validate("he!lo!", ['!']); + Assert.Equal(2, errorMessage.Split("'!'").Length - 1); + } + + [Fact] + public void OnlyCharsActuallyPresent_NotAllDisallowedChars() + { + // '@' is disallowed but not in the value — must not appear in the message + var (_, errorMessage) = Validate("hello!", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.DoesNotContain("'@'", errorMessage); + } + + [Fact] + public void ShowsActualChar_NotDisallowedChar() + { + // 'a' is disallowed (lowercase); value contains 'A' (uppercase). + // The message reports what the user supplied ('A'), not the disallowed definition ('a'). + var (_, errorMessage) = Validate("A", ['a']); + Assert.Contains("'A'", errorMessage); + Assert.DoesNotContain("'a'", errorMessage); + } + } + } + + // ----------------------------------------------------------------------- + // AllowNull + // ----------------------------------------------------------------------- + public class AllowNull + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void Null_Fails_When_AllowNull_Is_False() + { + var (isValid, _) = Validate(null, a => a.AllowNull = false); + Assert.False(isValid); + } + + [Fact] + public void NonNull_Passes_When_AllowNull_Is_False() + { + var (isValid, _) = Validate("hello", a => a.AllowNull = false); + Assert.True(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => AllowNull.Validate(value, configure); + + [Fact] + public void Null_Keyword() + { + var (_, message) = Validate(null, a => a.AllowNull = false); + Assert.Contains("null", message); + } + } + } + + // ----------------------------------------------------------------------- + // AllowEmpty + // ----------------------------------------------------------------------- + public class AllowEmpty + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + [Fact] + public void Empty_Fails_When_AllowEmpty_Is_False() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.False(isValid); + } + + [Fact] + public void NonEmpty_Passes_When_AllowEmpty_Is_False() + { + var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); + Assert.True(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => AllowEmpty.Validate(value, configure); + + [Fact] + public void Character_Keyword() + { + var (_, message) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.Contains("character", message); + } + } + } + + // ----------------------------------------------------------------------- + // AllowWhiteSpace + // ----------------------------------------------------------------------- + public class AllowWhiteSpace + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() + { + var (isValid, _) = Validate(" "); + Assert.True(isValid); + } + + [Fact] + public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() + { + var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.False(isValid); + } + + [Fact] + public void NonWhiteSpace_Passes_When_AllowWhiteSpace_Is_False() + { + var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); + Assert.True(isValid); + } + + // IsNullOrWhiteSpace("") is true, so empty string also fails the whitespace check + // when AllowEmpty=true (default) and AllowWhiteSpace=false + [Fact] + public void EmptyString_Fails_When_AllowWhiteSpace_Is_False_And_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowWhiteSpace = false); + Assert.False(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => AllowWhiteSpace.Validate(value, configure); + + [Fact] + public void Whitespace_Keyword() + { + var (_, message) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.Contains("whitespace", message); + } + } + } + + // ----------------------------------------------------------------------- + // Length (MinimumLength / MaximumLength) + // ----------------------------------------------------------------------- + public class Length + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void Within_Range_Passes() + { + var (isValid, _) = Validate("hello", a => { a.MinimumLength = 3; a.MaximumLength = 10; }); + Assert.True(isValid); + } + + [Fact] + public void ExactlyAtMinimumLength_Passes() + { + var (isValid, _) = Validate("hi", a => a.MinimumLength = 2); + Assert.True(isValid); + } + + [Fact] + public void ExactlyAtMaximumLength_Passes() + { + var (isValid, _) = Validate("hello", a => a.MaximumLength = 5); + Assert.True(isValid); + } + + [Fact] + public void BelowMinimumLength_Fails() + { + var (isValid, _) = Validate("hi", a => a.MinimumLength = 5); + Assert.False(isValid); + } + + [Fact] + public void ExceedsMaximumLength_Fails() + { + var (isValid, _) = Validate("hello world", a => a.MaximumLength = 5); + Assert.False(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => Length.Validate(value, configure); + + [Fact] + public void MinimumLength_Value() + { + var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; }); + Assert.Contains("5", message); + } + + [Fact] + public void MaximumLength_Value() + { + var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; }); + Assert.Contains("20", message); + } + } + } + + // ----------------------------------------------------------------------- + // Pattern + // ----------------------------------------------------------------------- + // The Pattern check fails validation when the value *matches* the regex — + // Pattern acts as a "disallowed pattern" rather than a "required pattern". + public class Pattern + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void NullPattern_Passes() + { + // Pattern defaults to null; any value passes the pattern check + var (isValid, _) = Validate("hello"); + Assert.True(isValid); + } + + [Fact] + public void ValueMatchingPattern_Fails() + { + var (isValid, _) = Validate("hello1", a => a.Pattern = new Regex("[0-9]")); + Assert.False(isValid); + } + + [Fact] + public void ValueNotMatchingPattern_Passes() + { + var (isValid, _) = Validate("hello", a => a.Pattern = new Regex("[0-9]")); + Assert.True(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => Pattern.Validate(value, configure); + + [Fact] + public void RegularExpression_Keyword() + { + var (_, message) = Validate("hello1", a => a.Pattern = new Regex("[0-9]")); + Assert.Contains("regular expression", message); + } + } + } + + // ----------------------------------------------------------------------- + // Check ordering + // ----------------------------------------------------------------------- + // Validation checks run in declaration order; when a value violates multiple + // conditions the error from the first check in code is the one returned. + public class CheckOrdering + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + // AllowNull is checked before AllowEmpty: + // null with both disabled returns the null error, not the empty error. + [Fact] + public void Null_ReturnsNullError_Not_EmptyError() + { + var (_, message) = Validate(null, a => { a.AllowNull = false; a.AllowEmpty = false; }); + Assert.Contains("null", message); + Assert.DoesNotContain("character", message); + } + + // AllowEmpty is checked before AllowWhiteSpace: + // "" with both disabled returns the empty error, not the whitespace error. + [Fact] + public void Empty_ReturnsEmptyError_Not_WhitespaceError() + { + var (_, message) = Validate(string.Empty, a => { a.AllowEmpty = false; a.AllowWhiteSpace = false; }); + Assert.Contains("character", message); + Assert.DoesNotContain("whitespace", message); + } + + // AllowWhiteSpace is checked before the length check: + // a whitespace string that is also below MinimumLength returns the whitespace error. + [Fact] + public void Whitespace_ReturnsWhitespaceError_Not_LengthError() + { + var (_, message) = Validate(" ", a => { a.AllowWhiteSpace = false; a.MinimumLength = 10; }); + Assert.Contains("whitespace", message); + Assert.DoesNotContain("between", message); + } + + // Length is checked before DisallowedCharacters: + // a too-short string that also contains a disallowed character returns the length error. + [Fact] + public void TooShort_ReturnsLengthError_Not_DisallowedCharsError() + { + var (_, message) = Validate("hi!", a => { a.MinimumLength = 10; a.DisallowedCharacters = ['!']; }); + Assert.Contains("between", message); + Assert.DoesNotContain("disallowed", message); + } + + // DisallowedCharacters is checked before Pattern: + // a string with a disallowed character that also matches the pattern returns the disallowed-chars error. + [Fact] + public void DisallowedChar_ReturnsDisallowedError_Not_PatternError() + { + var (_, message) = Validate("hello!1", a => { a.DisallowedCharacters = ['!']; a.Pattern = new Regex("[0-9]"); }); + Assert.Contains("disallowed", message); + Assert.DoesNotContain("expression", message); + } + } +} -- cgit v1.2.3 From 0346199c4ed5edb0d502f2e3f5972aafeea6c923 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 19:01:50 -0500 Subject: fix test --- src/slskd/Common/Validation/StringAttribute.cs | 13 ++++++++++--- .../Common/Validation/StringAttributeTests.cs | 7 +++++++ 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs index 2fcf4283..bb323ba2 100644 --- a/src/slskd/Common/Validation/StringAttribute.cs +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -53,9 +53,16 @@ namespace slskd.Validation { var val = (string)value; - if (!AllowNull && val is null) + if (val is null) { - return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + if (!AllowNull) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + } + else + { + return ValidationResult.Success; + } } if (!AllowEmpty && val is "") @@ -64,7 +71,7 @@ namespace slskd.Validation } // check this after empty to avoid overlap - if (!AllowWhiteSpace && string.IsNullOrWhiteSpace(val)) + if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c))) { return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace"); } diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index dfa964f7..71e6ce8b 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -221,6 +221,13 @@ public class StringAttributeTests private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) => StringAttributeTests.Validate(value, configure); + [Fact] + public void Null_Passes_When_AllowNull_Is_True() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + [Fact] public void Null_Fails_When_AllowNull_Is_False() { -- cgit v1.2.3 From 946333991d4f06aa139e9659952b2ce2ca9e988d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 13:40:48 -0500 Subject: mess with tests and validation --- .../Common/Validation/AbsolutePathAttribute.cs | 6 - src/slskd/Common/Validation/GuidAttribute.cs | 26 +- .../Common/Validation/RelativePathAttribute.cs | 6 - src/slskd/Core/Options.cs | 3 + .../API/Controllers/TransfersController.cs | 4 +- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 3 +- .../Validation/AbsolutePathAttributeTests.cs | 33 --- .../Common/Validation/GuidAttributeTests.cs | 120 +++++--- .../Validation/RelativePathAttributeTests.cs | 26 -- .../Common/Validation/StringAttributeTests.cs | 308 +++++++-------------- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- 11 files changed, 211 insertions(+), 326 deletions(-) (limited to 'tests') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 4c9f5e53..1999220f 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } - - // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here - if (FileSafety.ContainsTraversalSegments(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); - } } return ValidationResult.Success; diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs index 5728b8f6..f61527a4 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -32,6 +32,8 @@ namespace slskd.Validation { + using System; + using System.ComponentModel.DataAnnotations; /// @@ -39,6 +41,13 @@ namespace slskd.Validation /// public class GuidAttribute : ValidationAttribute { + public GuidAttribute(bool allowEmpty = false) + { + AllowEmpty = allowEmpty; + } + + public bool AllowEmpty { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value is null) @@ -46,8 +55,23 @@ namespace slskd.Validation return ValidationResult.Success; } - if (value is string str && System.Guid.TryParse(str, out _)) + if (value is Guid guid) { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + if (value is string str && Guid.TryParse(str, out guid)) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + return ValidationResult.Success; } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index e8865554..64e418b1 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } - - // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here - if (FileSafety.ContainsTraversalSegments(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); - } } return ValidationResult.Success; diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 21f2c75f..3d9c8fb2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -766,6 +766,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -777,6 +778,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -2013,6 +2015,7 @@ namespace slskd [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] [AbsolutePath] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 01dd61bd..3191e3a8 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -385,7 +385,7 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, batchId, failed); + Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed); } // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) @@ -488,7 +488,7 @@ namespace slskd.Transfers.API if (!Guid.TryParse(id, out var guid)) { - return BadRequest(); + return BadRequest($"The specified id {id} is not a valid GUID/UUID"); } try diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 53f5290f..c1b7d725 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -61,8 +61,7 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [NotNullOrWhiteSpace] - [StringLength(maximumLength: 500)] + [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] public string Username { get; init; } /// diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 53e25ac6..bc8601c5 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -171,39 +171,6 @@ public class AbsolutePathAttributeTests } } - // Paths containing . or .. segments, which are valid directory names in isolation - // but indicate traversal or ambiguity and must be rejected regardless of whether - // the path is otherwise absolute or relative. - public class Traversal_Fails - { - [Theory] - // Windows-style traversal - [InlineData("C:\\Music\\..\\Windows")] // traversal to sibling via backslash - [InlineData("C:\\Music\\.\\Artist")] // current-dir segment via backslash - [InlineData("C:/Music/../Windows")] // traversal via forward slash - [InlineData("C:/Music/./Artist")] // current-dir via forward slash - [InlineData("C:\\..")] // traversal at drive root - [InlineData("D:\\a\\b\\..\\c")] // traversal deep in path - // Unix-style traversal - [InlineData("/../etc")] // traversal at Unix root - [InlineData("/home/user/../etc")] // traversal to sibling on Unix - [InlineData("/home/user/./Music")] // current-dir on Unix - [InlineData("/home/../../etc")] // double traversal on Unix - // UNC traversal (backslash) - [InlineData("\\\\server\\..\\Windows")] // traversal past UNC server - [InlineData("\\\\server\\share\\..\\other")] // traversal within UNC share - [InlineData("\\\\server\\share\\.\\folder")] // current-dir within UNC share - // UNC traversal (forward slash) - [InlineData("//server/../share")] // traversal past server, forward slash - [InlineData("//server/share/../other")] // traversal within share, forward slash - public void TraversalSegment_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Contains("traversal segments", errorMessage); - } - } - public class Relative_Fails { [Theory] diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index e574c130..a26bb160 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -1,3 +1,4 @@ +using System; using System.ComponentModel.DataAnnotations; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class GuidAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(object value) + private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false) { - var attribute = new GuidAttribute(); + var attribute = new GuidAttribute(allowEmpty); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); @@ -22,53 +23,84 @@ public class GuidAttributeTests Assert.True(isValid); } - public class Passes + [Fact] + public void Empty_String_Fails_If_AllowEmpty_False() + { + var (isValid, message) = Validate("00000000-0000-0000-0000-000000000000", allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void Empty_Guid_Fails_If_AllowEmpty_False() { - [Theory] - [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens - [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens - [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) - [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format - [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format - [InlineData("00000000-0000-0000-0000-000000000000")] // all zeros - [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's - public void ValidGuidString_Passes(string value) - { - var (isValid, _) = Validate(value); - Assert.True(isValid); - } + var (isValid, message) = Validate(Guid.Empty, allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); } - public class Fails + [Fact] + public void AllowEmpty_Guid_Defaults_False() { - [Fact] - public void EmptyString_Fails() - { - var (isValid, errorMessage) = Validate(string.Empty); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + var (isValid, message) = Validate(Guid.Empty); + Assert.False(isValid); + Assert.Contains("empty", message); + } - [Theory] - [InlineData("not-a-guid")] // arbitrary string - [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short - [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z - [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long - [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g - [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens - public void InvalidGuidString_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [Fact] + public void AllowEmpty_String_Defaults_False() + { + var (isValid, message) = Validate(Guid.Empty.ToString()); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void Empty_String_Passes_If_AllowEmpty_True() + { + var (isValid, _) = Validate(Guid.Empty.ToString(), allowEmpty: true); + Assert.True(isValid); + } - [Fact] - public void NonStringValue_Fails() - { - var (isValid, errorMessage) = Validate(42); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [Fact] + public void Empty_Guid_Passes_If_AllowEmpty_True() + { + var (isValid, _) = Validate(Guid.Empty, allowEmpty: true); + Assert.True(isValid); + } + + [Theory] + [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens + [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens + [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) + [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format + [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format + [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's + public void ValidGuidString_Passes(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + [Theory] + [InlineData("not-a-guid")] // arbitrary string + [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short + [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z + [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long + [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g + [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens + public void InvalidGuidString_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); + } + + [Fact] + public void NonStringValue_Fails() + { + var (isValid, errorMessage) = Validate(42); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 1692bceb..bc581bf1 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -66,32 +66,6 @@ public class RelativePathAttributeTests } } - public class Traversal_Fails - { - [Theory] - [InlineData("..")] // bare traversal - [InlineData(".")] // bare current-dir - [InlineData("../music")] // traversal prefix, forward slash - [InlineData("./music")] // current-dir prefix - [InlineData("music/../other")] // traversal in middle - [InlineData("music/./other")] // current-dir in middle - [InlineData("sub/../../escape")] // double traversal - [InlineData("music\\..")] // traversal via backslash - [InlineData("music\\.")] // current-dir via backslash - [InlineData("music/dir/..")] // traversal at end - [InlineData("a/b/c/../../d")] // multi-level traversal - [InlineData("Ünïcödé/../escape")] // latin extended with traversal - [InlineData("пользователь/../etc")] // Cyrillic with traversal - [InlineData("用户/音乐/../../escape")] // Chinese with deep traversal - [InlineData("ユーザー\\..\\escape")] // Japanese with backslash traversal - public void TraversalSegment_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Contains("traversal segments", errorMessage); - } - } - public class Absolute_Fails { [Theory] diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index 71e6ce8b..dbc82736 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -17,49 +17,119 @@ public class StringAttributeTests return (result == null, result?.ErrorMessage); } - // empty string passes all default checks — [Required] handles presence - [Fact] - public void EmptyString_Passes() + public class Null { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); + [Fact] + public void Passes_When_AllowNull() + { + var (isValid, message) = Validate(null, a => a.AllowNull = true); + Assert.True(isValid); + } + + [Fact] + public void Fails_When_Not_AllowNull() + { + var (isValid, message) = Validate(null, a => a.AllowNull = false); + Assert.False(isValid); + Assert.Contains("must not be null", message); + } + + [Fact] + public void NonNull_Passes_Regardless() + { + var (isValid, message) = Validate("foo", a => a.AllowNull = true); + Assert.True(isValid); + + var (isValid2, message2) = Validate("foo", a => a.AllowNull = false); + Assert.True(isValid); + } } - public class DisallowedCharacters + public class Empty { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => StringAttributeTests.Validate(value, a => a.DisallowedCharacters = disallowed); + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true); + Assert.True(isValid); + } - public class Passes + [Fact] + public void Empty_Fails_When_AllowEmpty_Is_False() + { + var (isValid, message) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.False(isValid); + Assert.Contains("at least one character", message); + } + + [Fact] + public void NonEmpty_Passes_Regardless() + { + var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); + Assert.True(isValid); + + var (isValid2, _) = Validate("hello", a => a.AllowEmpty = true); + Assert.True(isValid); + } + } + + public class WhiteSpace + { + [Fact] + public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() + { + var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = true); + Assert.True(isValid); + } + + [Fact] + public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() + { + var (isValid, message) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.False(isValid); + Assert.Contains("whitespace", message); + } + + [Fact] + public void NonWhiteSpace_Passes_Regardless() { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); + var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); + Assert.True(isValid); + var (isValid2, _) = Validate("hello", a => a.AllowWhiteSpace = true); + Assert.True(isValid); + } + } + + public class DisallowedCharacters + { + public class Passes + { [Fact] public void EmptyString_Passes() { - var (isValid, _) = Validate(string.Empty, ['!']); + var (isValid, _) = Validate(string.Empty, a => a.DisallowedCharacters = ['!']); Assert.True(isValid); } [Fact] public void NoDisallowedCharsPresent_Passes() { - var (isValid, _) = Validate("hello", ['!', '@']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } [Fact] public void EmptyDisallowedSet_Passes() { - var (isValid, _) = Validate("hello!@#", []); + var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []); Assert.True(isValid); } [Fact] public void Unicode_AllowedChars_Pass() { - var (isValid, _) = Validate("пользователь/音楽", ['!', '@']); + var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } @@ -68,76 +138,73 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter() { - var (isValid, _) = Validate("B", ['a']); + var (isValid, _) = Validate("B", a => a.DisallowedCharacters = ['a']); Assert.True(isValid); } } public class Fails { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void SingleDisallowedChar_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtStart_Fails() { - var (isValid, _) = Validate("!hello", ['!']); + var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtEnd_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharInMiddle_Fails() { - var (isValid, _) = Validate("hel!lo", ['!']); + var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void OneOfMultipleDisallowedCharsPresent_Fails() { - var (isValid, _) = Validate("hello!", ['!', '@', '#']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void MultipleDisallowedCharsAllPresent_Fails() { - var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#']); + var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void DisallowedCharRepeated_Fails() { - var (isValid, _) = Validate("he!lo!", ['!']); + var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void AllCharsDisallowed_Fails() { - var (isValid, _) = Validate("!@#", ['!', '@', '#']); + var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void Unicode_DisallowedChar_Fails() { - var (isValid, _) = Validate("пользователь", ['е']); + var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']); Assert.False(isValid); } @@ -145,41 +212,38 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_Blocks_UpperCase() { - var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o']); + var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']); Assert.False(isValid); } [Fact] public void UpperCaseDisallowed_Blocks_LowerCase() { - var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']); Assert.False(isValid); } [Fact] public void ExactMatch_Fails() { - var (isValid, _) = Validate("hello", ['h']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']); Assert.False(isValid); } } public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void TheDisallowedChar() { - var (_, errorMessage) = Validate("hello!", ['!']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.Contains("'!'", errorMessage); } [Fact] public void AllPresentDisallowedChars() { - var (_, errorMessage) = Validate("h!@l", ['!', '@']); + var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.Contains("'@'", errorMessage); } @@ -188,7 +252,7 @@ public class StringAttributeTests public void EachOccurrenceOfRepeatedChar() { // "he!lo!" has two '!' — both occurrences are listed - var (_, errorMessage) = Validate("he!lo!", ['!']); + var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.Equal(2, errorMessage.Split("'!'").Length - 1); } @@ -196,7 +260,7 @@ public class StringAttributeTests public void OnlyCharsActuallyPresent_NotAllDisallowedChars() { // '@' is disallowed but not in the value — must not appear in the message - var (_, errorMessage) = Validate("hello!", ['!', '@']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.DoesNotContain("'@'", errorMessage); } @@ -206,159 +270,15 @@ public class StringAttributeTests { // 'a' is disallowed (lowercase); value contains 'A' (uppercase). // The message reports what the user supplied ('A'), not the disallowed definition ('a'). - var (_, errorMessage) = Validate("A", ['a']); + var (_, errorMessage) = Validate("A", a => a.DisallowedCharacters = ['a']); Assert.Contains("'A'", errorMessage); Assert.DoesNotContain("'a'", errorMessage); } } } - // ----------------------------------------------------------------------- - // AllowNull - // ----------------------------------------------------------------------- - public class AllowNull - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Null_Passes_When_AllowNull_Is_True() - { - var (isValid, _) = Validate(null); - Assert.True(isValid); - } - - [Fact] - public void Null_Fails_When_AllowNull_Is_False() - { - var (isValid, _) = Validate(null, a => a.AllowNull = false); - Assert.False(isValid); - } - - [Fact] - public void NonNull_Passes_When_AllowNull_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowNull = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowNull.Validate(value, configure); - - [Fact] - public void Null_Keyword() - { - var (_, message) = Validate(null, a => a.AllowNull = false); - Assert.Contains("null", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowEmpty - // ----------------------------------------------------------------------- - public class AllowEmpty - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Empty_Passes_When_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); - } - - [Fact] - public void Empty_Fails_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.False(isValid); - } - - [Fact] - public void NonEmpty_Passes_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowEmpty.Validate(value, configure); - - [Fact] - public void Character_Keyword() - { - var (_, message) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.Contains("character", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowWhiteSpace - // ----------------------------------------------------------------------- - public class AllowWhiteSpace - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() - { - var (isValid, _) = Validate(" "); - Assert.True(isValid); - } - - [Fact] - public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - [Fact] - public void NonWhiteSpace_Passes_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); - Assert.True(isValid); - } - - // IsNullOrWhiteSpace("") is true, so empty string also fails the whitespace check - // when AllowEmpty=true (default) and AllowWhiteSpace=false - [Fact] - public void EmptyString_Fails_When_AllowWhiteSpace_Is_False_And_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowWhiteSpace.Validate(value, configure); - - [Fact] - public void Whitespace_Keyword() - { - var (_, message) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.Contains("whitespace", message); - } - } - } - - // ----------------------------------------------------------------------- - // Length (MinimumLength / MaximumLength) - // ----------------------------------------------------------------------- public class Length { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void Within_Range_Passes() { @@ -396,9 +316,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Length.Validate(value, configure); - [Fact] public void MinimumLength_Value() { @@ -415,16 +332,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Pattern - // ----------------------------------------------------------------------- - // The Pattern check fails validation when the value *matches* the regex — - // Pattern acts as a "disallowed pattern" rather than a "required pattern". public class Pattern { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void NullPattern_Passes() { @@ -449,9 +358,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Pattern.Validate(value, configure); - [Fact] public void RegularExpression_Keyword() { @@ -461,16 +367,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Check ordering - // ----------------------------------------------------------------------- - // Validation checks run in declaration order; when a value violates multiple - // conditions the error from the first check in code is the one returned. public class CheckOrdering { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - // AllowNull is checked before AllowEmpty: // null with both disabled returns the null error, not the empty error. [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 2440291c..a9f30129 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -141,7 +141,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + Assert.Contains("between 1 and 500 characters", results[0].ErrorMessage); } } -- cgit v1.2.3 From 3c799f205ce56e250883efd1deda798b758bb788 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 17:39:43 -0500 Subject: add test for greedy bracket change --- .../Core/Options/SharesOptionsTests.cs | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs (limited to 'tests') diff --git a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs new file mode 100644 index 00000000..35ff53e6 --- /dev/null +++ b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Xunit; +using static slskd.Options; + +namespace slskd.Tests.Unit.Core.Options; + +public class SharesOptionsTests +{ + private static List Validate(SharesOptions options) + { + var context = new ValidationContext(options); + var results = new List(); + Validator.TryValidateObject(options, context, results, validateAllProperties: true); + return results; + } + + public class Directories + { + public class Digest + { + [Fact] + public void Alias_Uses_First_Closing_Bracket_When_Path_Contains_Brackets() + { + // [foo]/bar/[baz]/ should digest to alias "foo" and path "/bar/[baz]" + var options = new SharesOptions + { + Directories = [@"[foo]/bar/[baz]/"] + }; + + var results = Validate(options); + + Assert.DoesNotContain(results, r => r.ErrorMessage?.Contains("aliases may not contain path separators") == true); + } + } + } +} -- cgit v1.2.3 From f402e6f074b49d2344ba6d839f58298b87971f40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 17:42:34 -0500 Subject: leave some notes --- tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'tests') diff --git a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs index 35ff53e6..7eacb95d 100644 --- a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs +++ b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs @@ -28,6 +28,9 @@ public class SharesOptionsTests Directories = [@"[foo]/bar/[baz]/"] }; + // todo: fix this so that it fully validates on all platforms; currently this fails + // validation on Windows and would fail on Linux if i were to use backslashes + // the assertion for the alias proves we have fixed an aliasing bug so it's fine for now var results = Validate(options); Assert.DoesNotContain(results, r => r.ErrorMessage?.Contains("aliases may not contain path separators") == true); -- cgit v1.2.3