From fb600f5b90e6c313635687414b50869bf86ab653 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:13:28 -0500 Subject: add a validator for relative paths --- .../Common/Validation/RelativePathAttribute.cs | 72 ++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/slskd/Common/Validation/RelativePathAttribute.cs (limited to 'src/slskd/Common/Validation/RelativePathAttribute.cs') diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs new file mode 100644 index 00000000..05f7630d --- /dev/null +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -0,0 +1,72 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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; + using System.ComponentModel.DataAnnotations; + using System.IO; + + /// + /// Validates that the specified path is relative and contains no path traversal segments. + /// + public class RelativePathAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null) + { + var path = value.ToString(); + + if (!string.IsNullOrEmpty(path)) + { + if (Path.IsPathRooted(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + + // use a dummy absolute base to normalize the path; GetFullPath resolves all .. and . segments + var dummyBase = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + var combined = Path.GetFullPath(Path.Combine(dummyBase, path)); + + if (!combined.StartsWith(dummyBase, StringComparison.OrdinalIgnoreCase)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain path traversal segments."); + } + } + } + + return ValidationResult.Success; + } + } +} -- cgit v1.2.3 From 51a5f28e8a946287cf883ccb4403a0efabe3c426 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:14:36 -0500 Subject: punt on traversal for now --- src/slskd/Common/Validation/RelativePathAttribute.cs | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) (limited to 'src/slskd/Common/Validation/RelativePathAttribute.cs') diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 05f7630d..6cf87e7a 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -32,7 +32,6 @@ namespace slskd.Validation { - using System; using System.ComponentModel.DataAnnotations; using System.IO; @@ -47,22 +46,9 @@ namespace slskd.Validation { var path = value.ToString(); - if (!string.IsNullOrEmpty(path)) + if (!string.IsNullOrEmpty(path) && Path.IsPathRooted(path)) { - if (Path.IsPathRooted(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - - // use a dummy absolute base to normalize the path; GetFullPath resolves all .. and . segments - var dummyBase = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) - + Path.DirectorySeparatorChar; - var combined = Path.GetFullPath(Path.Combine(dummyBase, path)); - - if (!combined.StartsWith(dummyBase, StringComparison.OrdinalIgnoreCase)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must not contain path traversal segments."); - } + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } } -- cgit v1.2.3 From bd07234c29601c2c491d6582c58b257ea4e03296 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 15:58:34 -0500 Subject: check for malformed paths in relative/absolute validation --- src/slskd/Common/Validation/AbsolutePathAttribute.cs | 17 +++++++++++++++-- src/slskd/Common/Validation/RelativePathAttribute.cs | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 3 deletions(-) (limited to 'src/slskd/Common/Validation/RelativePathAttribute.cs') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index ef6db8ca..9f6184ce 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -34,6 +34,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using System.IO; + using System.Linq; /// /// Validates that the specified path is absolute. @@ -44,9 +45,21 @@ namespace slskd.Validation { if (value != null) { - var filePath = value.ToString(); + var path = value.ToString(); - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) + var segments = path.Split('/', '\\'); + + if (segments.Any(s => string.IsNullOrEmpty(s))) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + } + + 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."); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 6cf87e7a..3bd48766 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -34,9 +34,10 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using System.IO; + using System.Linq; /// - /// Validates that the specified path is relative and contains no path traversal segments. + /// Validates that the specified path is relative. /// public class RelativePathAttribute : ValidationAttribute { @@ -46,6 +47,18 @@ namespace slskd.Validation { var path = value.ToString(); + var segments = path.Split('/', '\\'); + + if (segments.Any(s => string.IsNullOrEmpty(s))) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + } + + 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."); -- 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 'src/slskd/Common/Validation/RelativePathAttribute.cs') 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 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 'src/slskd/Common/Validation/RelativePathAttribute.cs') 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 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 'src/slskd/Common/Validation/RelativePathAttribute.cs') 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