aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-05-17 15:55:56 -0500
committerGitHub <noreply@github.com>2026-05-17 15:55:56 -0500
commitc9acb8fbbb045c8b710fb3430084bd3e6490f00b (patch)
treeb097960843f3e84af6567cce6f473bf79c1f1806
parente3b6bd9954ea330402f1c44719a82fd56f173196 (diff)
parent338ed57cd52806e3684ccaedd1f19f5eafd4123a (diff)
downloadslskd-c9acb8fbbb045c8b710fb3430084bd3e6490f00b.tar.gz
Merge pull request #1733 from slskd/validation
Add or adjust several new validation classes
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs6
-rw-r--r--src/slskd/Common/Validation/GuidAttribute.cs81
-rw-r--r--src/slskd/Common/Validation/NonTraversingPathAttribute.cs (renamed from src/slskd/Common/Validation/DisallowedCharactersAttribute.cs)44
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs6
-rw-r--r--src/slskd/Common/Validation/StringAttribute.cs99
-rw-r--r--src/slskd/Core/Options.cs11
-rw-r--r--tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs2
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafetyTests.cs2
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs33
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs254
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs106
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs94
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs26
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs422
14 files changed, 828 insertions, 358 deletions
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
new file mode 100644
index 00000000..7c04f1f9
--- /dev/null
+++ b/src/slskd/Common/Validation/GuidAttribute.cs
@@ -0,0 +1,81 @@
+// <copyright file="GuidAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ 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
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System;
+
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the value is a valid Guid.
+ /// </summary>
+ 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)
+ {
+ return ValidationResult.Success;
+ }
+
+ 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;
+ }
+
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID");
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
index 90ed3d81..1e2616bd 100644
--- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs
+++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
@@ -1,4 +1,4 @@
-// <copyright file="DisallowedCharactersAttribute.cs" company="JP Dillingham">
+// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -30,42 +30,28 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
-namespace slskd.Validation;
-
-using System.ComponentModel.DataAnnotations;
-using System.Linq;
-
-/// <summary>
-/// Validates that the value does not contain any of the <see cref="Disallowed"/> characters.
-/// </summary>
-public class DisallowedCharactersAttribute : ValidationAttribute
+namespace slskd.Validation
{
- public DisallowedCharactersAttribute(params char[] disallowed)
- {
- Disallowed = disallowed;
- }
+ using System.ComponentModel.DataAnnotations;
/// <summary>
- /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>.
+ /// Validates that the specified path does not contain traversal segments '.' or '..'.
/// </summary>
- public bool IgnoreCase { get; set; } = true;
-
- private char[] Disallowed { get; }
-
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ public class NonTraversingPathAttribute : ValidationAttribute
{
- if (value is not null and string str)
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
- var invalid = IgnoreCase
- ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)))
- : str.Where(c => Disallowed.Contains(c));
-
- if (invalid.Any())
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
- return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ 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;
+ return ValidationResult.Success;
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
index edaef1be..edbb3483 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/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs
new file mode 100644
index 00000000..807fef4c
--- /dev/null
+++ b/src/slskd/Common/Validation/StringAttribute.cs
@@ -0,0 +1,99 @@
+// <copyright file="StringAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ 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
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+
+ /// <summary>
+ /// Validates that the value is not null or whitespace.
+ /// </summary>
+ 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 (val is null)
+ {
+ if (!AllowNull)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not be null");
+ }
+ else
+ {
+ return ValidationResult.Success;
+ }
+ }
+
+ 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 && val.All(c => char.IsWhiteSpace(c)))
+ {
+ 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;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 51b3cab1..f952f014 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -198,7 +198,6 @@ 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";
@@ -655,7 +654,6 @@ namespace slskd
[Description("the name for this agent")]
[StringLength(255, MinimumLength = 1)]
[NotNullOrWhiteSpace]
- [DisallowedCharacters('/', '\\')]
[Secret]
public string InstanceName { get; init; }
@@ -768,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;
@@ -779,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;
@@ -845,6 +845,12 @@ namespace slskd
directories?.Where(share => !IsAbsolutePath(share)).ToList()
.ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported.")));
+ // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /..
+ // which is resolved by some OS and will cause weird, unintended side effects
+ bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$");
+ directories?.Where(share => ContainsTraversalSegments(share)).ToList()
+ .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment.")));
+
(string Raw, string Alias, string Path) Digest(string share)
{
var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$");
@@ -2015,6 +2021,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/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs
index f6264661..eff24587 100644
--- a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs
+++ b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs
@@ -141,4 +141,4 @@ namespace slskd.Tests.Unit.Common.Extensions
Assert.EndsWith("after", result);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
index ae1efccf..a37e9e74 100644
--- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
+++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
@@ -542,4 +542,4 @@ public class FileSafetyTests
Assert.NotNull(result);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
index 5013ec3a..10d62bc9 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/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs
deleted file mode 100644
index f430c181..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);
- }
- }
-} \ No newline at end of file
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..f44b1f57
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs
@@ -0,0 +1,106 @@
+using System;
+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, bool allowEmpty = false)
+ {
+ 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);
+ }
+
+ // null is allowed; [Required] dictates whether the field must be defined
+ [Fact]
+ public void Null_Passes()
+ {
+ var (isValid, _) = Validate(null);
+ Assert.True(isValid);
+ }
+
+ [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()
+ {
+ var (isValid, message) = Validate(Guid.Empty, allowEmpty: false);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void AllowEmpty_Guid_Defaults_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [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 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);
+ }
+} \ 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..b70d2603
--- /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);
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs
index 647bc05f..0006d91d 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
new file mode 100644
index 00000000..e344798f
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs
@@ -0,0 +1,422 @@
+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<StringAttribute> 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);
+ }
+
+ public class Null
+ {
+ [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 Empty
+ {
+ [Fact]
+ public void Empty_Passes_When_AllowEmpty_Is_True()
+ {
+ var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true);
+ Assert.True(isValid);
+ }
+
+ [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()
+ {
+ 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, a => a.DisallowedCharacters = ['!']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void NoDisallowedCharsPresent_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void EmptyDisallowedSet_Passes()
+ {
+ var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Unicode_AllowedChars_Pass()
+ {
+ var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']);
+ 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 => a.DisallowedCharacters = ['a']);
+ Assert.True(isValid);
+ }
+ }
+
+ public class Fails
+ {
+ [Fact]
+ public void SingleDisallowedChar_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharAtStart_Fails()
+ {
+ var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharAtEnd_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharInMiddle_Fails()
+ {
+ var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void OneOfMultipleDisallowedCharsPresent_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void MultipleDisallowedCharsAllPresent_Fails()
+ {
+ var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharRepeated_Fails()
+ {
+ var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void AllCharsDisallowed_Fails()
+ {
+ var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void Unicode_DisallowedChar_Fails()
+ {
+ var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']);
+ Assert.False(isValid);
+ }
+
+ // character matching is always case-insensitive
+ [Fact]
+ public void LowerCaseDisallowed_Blocks_UpperCase()
+ {
+ var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void UpperCaseDisallowed_Blocks_LowerCase()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ExactMatch_Fails()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']);
+ Assert.False(isValid);
+ }
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void TheDisallowedChar()
+ {
+ var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.Contains("'!'", errorMessage);
+ }
+
+ [Fact]
+ public void AllPresentDisallowedChars()
+ {
+ var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.Contains("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void EachOccurrenceOfRepeatedChar()
+ {
+ // "he!lo!" has two '!' — both occurrences are listed
+ var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']);
+ 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!", a => a.DisallowedCharacters = ['!', '@']);
+ 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 => a.DisallowedCharacters = ['a']);
+ Assert.Contains("'A'", errorMessage);
+ Assert.DoesNotContain("'a'", errorMessage);
+ }
+ }
+ }
+
+ public class Length
+ {
+ [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
+ {
+ [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);
+ }
+ }
+ }
+
+ public class Pattern
+ {
+ [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
+ {
+ [Fact]
+ public void RegularExpression_Keyword()
+ {
+ var (_, message) = Validate("hello1", a => a.Pattern = new Regex("[0-9]"));
+ Assert.Contains("regular expression", message);
+ }
+ }
+ }
+
+ public class CheckOrdering
+ {
+ // 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);
+ }
+ }
+} \ No newline at end of file