aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-05-13 20:40:53 -0500
committerJP Dillingham <jp@dillingham.me>2026-05-13 20:40:53 -0500
commitaffd1cd7d6ceefd978431f421df4041d6d57f3da (patch)
tree911ef82cd2f75a3dba52c5fba683f468618016c3
parent18234fd844cdf2b31b5cb3e39587524f97ddcc26 (diff)
downloadslskd-affd1cd7d6ceefd978431f421df4041d6d57f3da.tar.gz
add validator for disallowed characters
-rw-r--r--src/slskd/Common/Validation/DisallowedCharactersAttribute.cs71
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs254
2 files changed, 325 insertions, 0 deletions
diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs
new file mode 100644
index 00000000..90ed3d81
--- /dev/null
+++ b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs
@@ -0,0 +1,71 @@
+// <copyright file="DisallowedCharactersAttribute.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;
+
+/// <summary>
+/// Validates that the value does not contain any of the <see cref="Disallowed"/> characters.
+/// </summary>
+public class DisallowedCharactersAttribute : ValidationAttribute
+{
+ public DisallowedCharactersAttribute(params char[] disallowed)
+ {
+ Disallowed = disallowed;
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>.
+ /// </summary>
+ public bool IgnoreCase { get; set; } = true;
+
+ private char[] Disallowed { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value is not null and string str)
+ {
+ var invalid = IgnoreCase
+ ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)))
+ : str.Where(c => Disallowed.Contains(c));
+
+ if (invalid.Any())
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs
new file mode 100644
index 00000000..f430c181
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs
@@ -0,0 +1,254 @@
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class DisallowedCharactersAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
+ {
+ var attribute = new DisallowedCharactersAttribute(disallowed) { IgnoreCase = ignoreCase };
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attribute.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ // null and empty pass — [Required] handles presence; this attribute only checks content
+ [Fact]
+ public void Null_Passes()
+ {
+ var (isValid, _) = Validate(null, ['!']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void EmptyString_Passes()
+ {
+ var (isValid, _) = Validate(string.Empty, ['!']);
+ Assert.True(isValid);
+ }
+
+ public class Passes
+ {
+ private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
+ => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase);
+
+ // Punctuation has no case variants — IgnoreCase must not affect the result either way
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void NoDisallowedCharsPresent_Passes_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("hello", ['!', '@'], ignoreCase);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void EmptyDisallowedSet_Passes_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("hello!@#", [], ignoreCase);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void Unicode_AllowedChars_Pass_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("пользователь/音楽", ['!', '@'], ignoreCase);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void NonString_Passes()
+ {
+ var attribute = new DisallowedCharactersAttribute('!');
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attribute.GetValidationResult(42, context);
+ Assert.Equal(ValidationResult.Success, result);
+ }
+
+ // IgnoreCase = false only: a disallowed letter in one case does not block the other case
+ [Fact]
+ public void CaseSensitive_LowerCaseDisallowed_DoesNotBlock_UpperCase()
+ {
+ var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: false);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void CaseSensitive_UpperCaseDisallowed_DoesNotBlock_LowerCase()
+ {
+ var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: false);
+ Assert.True(isValid);
+ }
+ }
+
+ public class Fails
+ {
+ private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
+ => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase);
+
+ // Punctuation has no case variants — IgnoreCase must not affect the result either way
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void SingleDisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("hello!", ['!'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void DisallowedCharAtStart_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("!hello", ['!'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void DisallowedCharAtEnd_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("hello!", ['!'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void DisallowedCharInMiddle_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("hel!lo", ['!'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void OneOfMultipleDisallowedCharsPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("hello!", ['!', '@', '#'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void MultipleDisallowedCharsAllPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void DisallowedCharRepeated_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("he!lo!", ['!'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void AllCharsDisallowed_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("!@#", ['!', '@', '#'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void Unicode_DisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
+ {
+ var (isValid, _) = Validate("пользователь", ['е'], ignoreCase);
+ Assert.False(isValid);
+ }
+
+ // IgnoreCase = true only: a disallowed letter blocks its other-case equivalent
+ [Fact]
+ public void IgnoreCase_LowerCaseDisallowed_Blocks_UpperCase()
+ {
+ var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: true);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void IgnoreCase_UpperCaseDisallowed_Blocks_LowerCase()
+ {
+ var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: true);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void CaseSensitive_ExactMatch_Fails()
+ {
+ var (isValid, _) = Validate("hello", ['h'], ignoreCase: false);
+ Assert.False(isValid);
+ }
+ }
+
+ public class ErrorMessage_Contains
+ {
+ private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
+ => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase);
+
+ [Fact]
+ public void DisplayName()
+ {
+ var (_, errorMessage) = Validate("hello!", ['!']);
+ Assert.Contains("Field", errorMessage);
+ }
+
+ [Fact]
+ public void TheDisallowedChar()
+ {
+ var (_, errorMessage) = Validate("hello!", ['!']);
+ Assert.Contains("'!'", errorMessage);
+ }
+
+ [Fact]
+ public void AllPresentDisallowedChars()
+ {
+ var (_, errorMessage) = Validate("h!@l", ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.Contains("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void EachOccurrenceOfRepeatedChar()
+ {
+ // "he!lo!" has two '!' — both occurrences are listed
+ var (_, errorMessage) = Validate("he!lo!", ['!']);
+ Assert.Equal(2, errorMessage.Split("'!'").Length - 1);
+ }
+
+ [Fact]
+ public void OnlyCharsActuallyPresent_NotAllDisallowedChars()
+ {
+ // '@' is disallowed but not in the value — must not appear in the message
+ var (_, errorMessage) = Validate("hello!", ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.DoesNotContain("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void IgnoreCase_ShowsActualChar_NotDisallowedChar()
+ {
+ // 'a' is disallowed (lowercase); value contains 'A' (uppercase).
+ // The message reports what the user supplied ('A'), not the disallowed definition ('a').
+ var (_, errorMessage) = Validate("A", ['a'], ignoreCase: true);
+ Assert.Contains("'A'", errorMessage);
+ Assert.DoesNotContain("'a'", errorMessage);
+ }
+ }
+} \ No newline at end of file