diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-04-23 18:40:41 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-04-23 18:40:41 -0500 |
| commit | fc722e4a78aa5369fcd5ca0d8e88bd98d874a1d8 (patch) | |
| tree | 1ebad506bc42f3bc20e6825bf9f03715031c06ba | |
| parent | 7961741f740abd240754ff6e39cda6d69f727268 (diff) | |
| parent | 2f20ac833dca19e87e7980ac83f94206685409d9 (diff) | |
| download | slskd-fc722e4a78aa5369fcd5ca0d8e88bd98d874a1d8.tar.gz | |
Merge pull request #1713 from slskd/blacklist-regex
Allow blacklisting of username patterns
| -rw-r--r-- | .gitignore | 4 | ||||
| -rw-r--r-- | config/slskd.example.yml | 2 | ||||
| -rw-r--r-- | docs/config.md | 4 | ||||
| -rw-r--r-- | src/slskd/Application.cs | 11 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 13 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/ConversationsController.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Users/API/Controllers/UsersController.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Users/IUserService.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Users/Types/User.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Users/UserService.cs | 134 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Core/Options/TransfersOptions.GroupsOptions.BlacklistedOptionsTests.cs | 130 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Users/UserServiceTests.cs | 304 |
13 files changed, 631 insertions, 30 deletions
@@ -14,4 +14,6 @@ coverage.json # global.json is (at the time this was added) being used to pin the SDK to 9.0.203, which is the most recent # version of the SDK that _doesn't_ strip colors from 'dotnet watch' output. once this problem is fixed, remove # this entry and the file doing the pinning. this may not be until .NET 10 reaches GA. -global.json
\ No newline at end of file +global.json + +.claude
\ No newline at end of file diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 72aadaed..ee72a2e0 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -112,6 +112,8 @@ # blacklisted: # members: # - <username to blacklist> +# patterns: +# - <regular expression to match against usernames> # cidrs: # - <CIDR to blacklist, e.g. 255.255.255.255/32> # user_defined: diff --git a/docs/config.md b/docs/config.md index aac89f9a..b4e8fa47 100644 --- a/docs/config.md +++ b/docs/config.md @@ -491,6 +491,8 @@ Private and chat room messages from blacklisted users are also ignored. Users can be blacklisted by adding their username to the `members` list. Additionally, users can be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. +The `patterns` list accepts regular expressions matched against usernames. Any username matching one or more patterns will be blacklisted. This is useful for blocking bots or automated clients that share a common username prefix or suffix — for example, `^user` would block any username starting with `user`, and `_bot$` would block any username ending with `_bot`. Patterns follow the same case sensitivity rules as other user-defined regular expressions in the application — case insensitive by default, controlled by the `flags.case_sensitive_regex` option. + Users added to the blacklist will be blocked from enqueueing any new files. Any existing active or queued transfers will need to be cancelled manually. A managed blacklist file may also be used to achieve the same effects. Read more about this in the [Managed Blacklist](#managed-blacklist) section below. @@ -501,6 +503,8 @@ groups: blacklisted: members: - <username to blacklist> + patterns: + - <regular expression to match against usernames> cidrs: - <CIDR to blacklist, e.g. 255.255.255.255/32> ``` diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 86dd9dd1..e36a5539 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -94,6 +94,7 @@ namespace slskd /// <summary> /// The name of the blacklisted user group. /// </summary> + [Obsolete("use IsBlacklisted instead")] public const string BlacklistedGroup = "blacklisted"; private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; @@ -1380,6 +1381,12 @@ namespace slskd private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename) { + if (Users.IsBlacklisted(username, endpoint.Address)) + { + Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); + return Task.FromResult<int?>(null); + } + try { var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); @@ -1651,7 +1658,9 @@ namespace slskd var sw = new Stopwatch(); sw.Start(); - if (Users.IsBlacklisted(username)) + // opportunistically try and avoid performing the search if we have a cached blacklisted value, otherwise + // hold off on computing it and filling the cache until we have the user's IP + if (Users.IsBlacklisted(username, bypassCache: false)) { return null; } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7b38143e..fcc65c3b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1150,6 +1150,11 @@ namespace slskd public string[] Members { get; init; } = Array.Empty<string>(); /// <summary> + /// Gets the list of regular expression patterns matched against usernames. + /// </summary> + public string[] Patterns { get; init; } = Array.Empty<string>(); + + /// <summary> /// Gets the list of group CIDRs. /// </summary> public string[] Cidrs { get; init; } = Array.Empty<string>(); @@ -1163,6 +1168,14 @@ namespace slskd { var results = new List<ValidationResult>(); + foreach (var pattern in Patterns ?? Array.Empty<string>()) + { + if (!pattern.IsValidRegex()) + { + results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression")); + } + } + foreach (var cidr in Cidrs ?? Array.Empty<string>()) { try diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index c60d0c2f..7ed0a92c 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -40,6 +40,7 @@ namespace slskd.Messaging.API using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using slskd.Users; /// <summary> /// Conversations. @@ -56,19 +57,23 @@ namespace slskd.Messaging.API /// </summary> /// <param name="applicationStateMonitor"></param> /// <param name="messagingService"></param> + /// <param name="userService"></param> /// <param name="optionsSnapshot"></param> public ConversationsController( IStateMonitor<State> applicationStateMonitor, IMessagingService messagingService, + IUserService userService, IOptionsSnapshot<Options> optionsSnapshot) { ApplicationStateMonitor = applicationStateMonitor; Messages = messagingService; + Users = userService; OptionsSnapshot = optionsSnapshot; } private IStateMonitor<State> ApplicationStateMonitor { get; } private IMessagingService Messages { get; } + private IUserService Users { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } /// <summary> @@ -264,6 +269,11 @@ namespace slskd.Messaging.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return StatusCode(200); + } + if (string.IsNullOrEmpty(message)) { return BadRequest(); diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 2ffd50d4..494ee722 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -44,6 +44,8 @@ namespace slskd.Transfers.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; + using slskd.Users; + using Soulseek; /// <summary> /// Transfers. @@ -58,17 +60,21 @@ namespace slskd.Transfers.API /// Initializes a new instance of the <see cref="TransfersController"/> class. /// </summary> /// <param name="optionsSnapshot"></param> + /// <param name="userService"></param> /// <param name="transferService"></param> public TransfersController( ITransferService transferService, + IUserService userService, IOptionsSnapshot<Options> optionsSnapshot) { Transfers = transferService; + Users = userService; OptionsSnapshot = optionsSnapshot; } private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2); private ITransferService Transfers { get; } + private IUserService Users { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>(); @@ -253,6 +259,13 @@ namespace slskd.Transfers.API try { + var endpoint = await Users.GetIPEndPointAsync(username); + + if (Users.IsBlacklisted(username, endpoint.Address)) + { + throw new UserOfflineException($"User {username} appears to be offline"); + } + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); @@ -382,6 +395,11 @@ namespace slskd.Transfers.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + if (!Guid.TryParse(id, out var guid)) { return BadRequest(); diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 2a6f535f..8029b5e0 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -93,6 +93,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var endpoint = await Users.GetIPEndPointAsync(username); @@ -120,6 +125,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var result = await Client.BrowseAsync(username); @@ -184,6 +194,11 @@ namespace slskd.Users.API return BadRequest(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var result = await Client.GetDirectoryContentsAsync(username, request.Directory); @@ -214,6 +229,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var response = await Users.GetInfoAsync(username); @@ -241,6 +261,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var response = await Users.GetStatusAsync(username); diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index f2cfa5f1..28bb6459 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -144,8 +144,9 @@ namespace slskd.Users /// </summary> /// <param name="username">The username to check.</param> /// <param name="ipAddress">The IPAddress to check, if available.</param> + /// <param name="bypassCache">A value indicating whether to compute blacklisted status on a cache miss.</param> /// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns> - bool IsBlacklisted(string username, IPAddress ipAddress = null); + bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true); /// <summary> /// Retrieves a value indicating whether the specified peer is privileged. diff --git a/src/slskd/Users/Types/User.cs b/src/slskd/Users/Types/User.cs index 7297d747..473bedfb 100644 --- a/src/slskd/Users/Types/User.cs +++ b/src/slskd/Users/Types/User.cs @@ -42,6 +42,9 @@ namespace slskd.Users /// <summary> /// Gets the user's configured group. /// </summary> + /// <remarks> + /// This is the group under which the username appears in config, *not* the group derived at runtime. + /// </remarks> public string Group { get; init; } /// <summary> diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index d8b24f4d..3ce827c8 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -34,11 +34,15 @@ using Microsoft.Extensions.Options; namespace slskd.Users { + using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; + using System.Text.RegularExpressions; using System.Threading.Tasks; + using Microsoft.Extensions.Caching.Memory; + using Microsoft.Extensions.Internal; using NetTools; using Serilog; using Soulseek; @@ -85,15 +89,20 @@ namespace slskd.Users /// </summary> /// <param name="soulseekClient"></param> /// <param name="optionsMonitor"></param> + /// <param name="systemClock"></param> public UserService( ISoulseekClient soulseekClient, - IOptionsMonitor<Options> optionsMonitor) + IOptionsMonitor<Options> optionsMonitor, + ISystemClock systemClock = null) { Client = soulseekClient; OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); + InjectedClock = systemClock ?? new SystemClock(); + BlacklistDecisionCache = new MemoryCache(new MemoryCacheOptions { Clock = InjectedClock, ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); + // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause // multiple redundant round trips when initially watching a user or when explicitly requesting via // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. @@ -137,6 +146,9 @@ namespace slskd.Users private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); + private IReadOnlyCollection<Regex> CompiledBlacklistPatterns { get; set; } = []; + private ISystemClock InjectedClock { get; } + private MemoryCache BlacklistDecisionCache { get; } /// <summary> /// Gets or sets the internal cache of User data. @@ -162,31 +174,45 @@ namespace slskd.Users private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>(); /// <summary> - /// Gets the name of the group for the specified <paramref name="username"/>. + /// Gets the name of the group for the specified <paramref name="username"/> from cached data. /// </summary> - /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks> + /// <remarks> + /// <para> + /// Excludes the 'blacklisted' group for performance; use <see cref="IsBlacklisted"/> to guard network operations instead. + /// </para> + /// <para> + /// This is an extremely hot path, and the value returned may be approximated or incorrect in the case of a + /// cache miss in order to provide low latency values. + /// </para> + /// </remarks> /// <param name="username">The username of the peer.</param> /// <returns>The group for the specified username.</returns> public string GetGroup(string username) { - // note: this is an extremely hot path; keep the work done to an absolute minimum. + // users end up in this dictionary for a few reasons, including but maybe not limited to: + // * they show up in the user defined group list somewhere + // * the server told us they have privileges when we logged in + // * we 'watched' them + // * we fetched statistics or status for them + // if we handle any of their data they'll probably wind up here. if they show up in the config, + // their Group property will be set. otherwise we must resolve their group dynamically. if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) { - if (IsBlacklisted(user.Username)) - { - return Application.BlacklistedGroup; - } - + // privileged users trump everything, and we resolve their group accordingly regardless of all other factors if (user.Status?.IsPrivileged ?? false) { return Application.PrivilegedGroup; } + // if the user isn't privileged and the user has put their username in any user defined group, that's + // their group. they aren't subjected to leecher checks. if (user.Group != null) { return user.Group; } + // check to see if they are a leecher. they may be in the dictionary because we checked their stats. + // if we don't have their stats we don't have enough info to make the call, group is inconclusive so fall through var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) @@ -286,33 +312,79 @@ namespace slskd.Users /// <summary> /// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted. /// </summary> + /// <remarks> + /// This method may be taxing if the user has defined a blacklist file or large number of patterns. Call it to 'guard' + /// actions at the network level (with the exception of search results where latency is sensitive), but don't + /// use it to check once the user is 'in' the system (e.g. don't call this in the upload governor or queue logic). + /// </remarks> /// <param name="username">The username to check.</param> /// <param name="ipAddress">The IPAddress to check, if available.</param> + /// <param name="bypassCache">A value indicating whether to compute blacklisted status on a cache miss.</param> /// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns> - public bool IsBlacklisted(string username, IPAddress ipAddress = null) + public bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true) { - var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; + ArgumentNullException.ThrowIfNull(username); - if (blacklist.Members.Contains(username)) + if (BlacklistDecisionCache.TryGetValue<bool>(username, out var cached)) { - return true; + return cached; } - // check the user-curated list of blacklisted CIDRs that exists along with the list of - // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a - // blacklist supplied by a third party (but might?) - if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) + // if we have a cache miss and the caller has specified bypassCache = false, assume that a cache miss + // means that the user is not blacklisted. we will only specify bypassCache = false when we're checking + // in a hot path, which at the time of this writing is only when determining whether to search shares for a + // request. we will check again before sending the results with bypassCache = true, and we should always + // follow this pattern when using bypassCache = false (specifically, check again before sending something) + if (!bypassCache) { - return true; + return false; } - // check the managed blacklist loaded from a third party blacklist file - if (ipAddress is not null && Blacklist.Contains(ipAddress)) + var blacklisted = IsBlacklistedInternal(username, ipAddress); + + BlacklistDecisionCache.Set( + key: username, + value: blacklisted, + options: new MemoryCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), + Size = 1, + }); + + return blacklisted; + + bool IsBlacklistedInternal(string username, IPAddress iPAddress = null) { - return true; - } + // first, check to see if the name appears explicitly in the config + var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; - return false; + if (blacklist.Members.Contains(username)) + { + return true; + } + + // check to see if the username matches any patterns + if (CompiledBlacklistPatterns.Any(pattern => pattern.IsMatch(username))) + { + return true; + } + + // check the user-curated list of blacklisted CIDRs that exists along with the list of + // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a + // blacklist supplied by a third party (but might?) + if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) + { + return true; + } + + // check the managed blacklist loaded from a third party blacklist file + if (ipAddress is not null && Blacklist.Contains(ipAddress)) + { + return true; + } + + return false; + } } /// <summary> @@ -419,6 +491,19 @@ namespace slskd.Users LastOptionsHash = optionsHash; } + // recompile blacklist patterns, regardless of whether they changed (this cheap to do) + var regexOptions = RegexOptions.Compiled; + + if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx) + { + regexOptions |= RegexOptions.IgnoreCase; + } + + CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns + .Select(f => new Regex(f, regexOptions)) + .ToList() + .AsReadOnly(); + var blacklistOptionsHash = Compute.Sha1Hash(options.Blacklist.ToJson()); // there's no forced re-config of the blacklist; either the config changed or it didn't. @@ -464,6 +549,9 @@ namespace slskd.Users LastBlacklistOptionsHash = blacklistOptionsHash; } + + // invalidate cached blacklist decisions + BlacklistDecisionCache.Clear(); } private void Reset() diff --git a/tests/slskd.Tests.Unit/Core/Options/TransfersOptions.GroupsOptions.BlacklistedOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/TransfersOptions.GroupsOptions.BlacklistedOptionsTests.cs new file mode 100644 index 00000000..2c77a8ba --- /dev/null +++ b/tests/slskd.Tests.Unit/Core/Options/TransfersOptions.GroupsOptions.BlacklistedOptionsTests.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Xunit; +using static slskd.Options; + +namespace slskd.Tests.Unit.Core.Options; + +using BlacklistedOptions = TransfersOptions.GroupsOptions.BlacklistedOptions; + +public class BlacklistedOptionsTests +{ + private static List<ValidationResult> Validate(BlacklistedOptions options) + { + var context = new ValidationContext(options); + var results = new List<ValidationResult>(); + Validator.TryValidateObject(options, context, results, validateAllProperties: true); + return results; + } + + public class Patterns + { + [Fact] + public void Valid_regex_produces_no_errors() + { + var options = new BlacklistedOptions { Patterns = [".*", "^foo$", @"\d+"] }; + Assert.Empty(Validate(options)); + } + + [Theory] + [InlineData("[invalid")] + [InlineData("(unclosed")] + [InlineData("*noanchor")] + public void Invalid_regex_produces_error(string pattern) + { + var options = new BlacklistedOptions { Patterns = [pattern] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains(pattern, results[0].ErrorMessage); + } + + [Fact] + public void Multiple_invalid_regexes_each_produce_an_error() + { + var options = new BlacklistedOptions { Patterns = ["[bad", "(also bad"] }; + Assert.Equal(2, Validate(options).Count); + } + + [Fact] + public void Mixed_valid_and_invalid_regexes_only_errors_on_invalid() + { + var options = new BlacklistedOptions { Patterns = ["valid.*", "[invalid"] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("[invalid", results[0].ErrorMessage); + } + + [Fact] + public void Empty_patterns_produces_no_errors() + { + var options = new BlacklistedOptions { Patterns = [] }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Null_patterns_produces_no_errors() + { + var options = new BlacklistedOptions { Patterns = null }; + Assert.Empty(Validate(options)); + } + } + + public class Cidrs + { + [Theory] + [InlineData("192.168.1.0/24")] + [InlineData("10.0.0.0/8")] + [InlineData("1.2.3.4/32")] + [InlineData("0.0.0.0/0")] + public void Valid_cidr_produces_no_errors(string cidr) + { + var options = new BlacklistedOptions { Cidrs = [cidr] }; + Assert.Empty(Validate(options)); + } + + [Theory] + [InlineData("not-a-cidr")] + [InlineData("999.999.999.999/24")] + [InlineData("192.168.1.0/33")] + public void Invalid_cidr_produces_error(string cidr) + { + var options = new BlacklistedOptions { Cidrs = [cidr] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains(cidr, results[0].ErrorMessage); + } + + [Theory] + [InlineData("::ffff:192.168.1.1")] + [InlineData("::FFFF:10.0.0.1")] + [InlineData("::ffff:0:0/96")] + public void IPv4_mapped_IPv6_address_produces_error(string cidr) + { + var options = new BlacklistedOptions { Cidrs = [cidr] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains(cidr, results[0].ErrorMessage); + } + + [Fact] + public void Multiple_invalid_cidrs_each_produce_an_error() + { + var options = new BlacklistedOptions { Cidrs = ["bad1", "bad2"] }; + Assert.Equal(2, Validate(options).Count); + } + + [Fact] + public void Empty_cidrs_produces_no_errors() + { + var options = new BlacklistedOptions { Cidrs = [] }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Null_cidrs_produces_no_errors() + { + var options = new BlacklistedOptions { Cidrs = null }; + Assert.Empty(Validate(options)); + } + } +} diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs index 95e17e32..7cd4c492 100644 --- a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs +++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs @@ -1,7 +1,13 @@ namespace slskd.Tests.Unit.Users { + using System; using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Threading.Tasks; using AutoFixture.Xunit2; + using Microsoft.Extensions.Caching.Memory; + using Microsoft.Extensions.Internal; using Moq; using slskd.Users; using Soulseek; @@ -56,6 +62,195 @@ namespace slskd.Tests.Unit.Users } } + public class IsBlacklisted + { + [Fact] + public void Throws_If_Username_Is_Null() + { + var (service, _) = GetFixture(); + + Assert.Throws<ArgumentNullException>(() => service.IsBlacklisted(null)); + } + + [Theory, AutoData] + public void Returns_Cached_Value_On_Cache_Hit(string username) + { + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Members = new[] { username }, + } + } + } + }; + + var (service, _) = GetFixture(options); + + // prime the cache with a computed result + service.IsBlacklisted(username); + + // bypassCache = false returns false on a cache miss; if the result is still true, + // the value was returned from cache rather than computed again + Assert.True(service.IsBlacklisted(username, bypassCache: false)); + } + + [Theory, AutoData] + public void Returns_False_On_Cache_Miss_With_BypassCache_False(string username) + { + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Members = new[] { username }, + } + } + } + }; + + var (service, _) = GetFixture(options); + + // the user is blacklisted, but bypassCache = false on a cache miss returns false + // without computing, so the result is false even though the user is blacklisted + Assert.False(service.IsBlacklisted(username, bypassCache: false)); + } + + [Theory, AutoData] + public void Returns_True_If_Username_Is_Blacklisted_And_BypassCache_True(string username) + { + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Members = new[] { username }, + } + } + } + }; + + var (service, _) = GetFixture(options); + + Assert.True(service.IsBlacklisted(username, bypassCache: true)); + } + + [Theory, AutoData] + public void Returns_True_If_Username_Matches_Blacklist_Pattern(string prefix, string suffix) + { + var username = $"{prefix}_blacklisted_{suffix}"; + + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Patterns = new[] { @".*_blacklisted_.*" }, + } + } + } + }; + + var (service, _) = GetFixture(options); + + Assert.True(service.IsBlacklisted(username)); + } + + [Theory, AutoData] + public void Returns_True_If_IP_Address_Is_In_Blacklisted_CIDR(string username) + { + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Cidrs = new[] { "192.168.100.0/24" }, + } + } + } + }; + + var (service, _) = GetFixture(options); + + Assert.True(service.IsBlacklisted(username, IPAddress.Parse("192.168.100.5"))); + } + + [Theory, AutoData] + public async Task Returns_True_If_IP_Address_Is_In_Blacklist_File(string username) + { + var tempFile = Path.GetTempFileName(); + + try + { + System.IO.File.WriteAllText(tempFile, "192.168.200.0/24\n"); + + var (service, _) = GetFixture(); + + var blacklist = new Blacklist(); + await blacklist.Load(tempFile, BlacklistFormat.CIDR); + + service.SetField("<Blacklist>k__BackingField", blacklist); + + Assert.True(service.IsBlacklisted(username, IPAddress.Parse("192.168.200.5"))); + } + finally + { + System.IO.File.Delete(tempFile); + } + } + + [Theory, AutoData] + public void Returns_False_If_Not_Blacklisted_By_Any_Method(string username) + { + var (service, _) = GetFixture(); + + Assert.False(service.IsBlacklisted(username, IPAddress.Parse("10.0.0.1"))); + } + + [Theory, AutoData] + public void Caches_Result_Of_IsBlacklistedInternal(string username) + { + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Members = new[] { username }, + } + } + } + }; + + var (service, _) = GetFixture(options); + + // first call: cache miss, IsBlacklistedInternal is called, result is cached + Assert.True(service.IsBlacklisted(username)); + + // second call with bypassCache = false: returns cached true rather than the + // false that a cache miss would produce, confirming the result was cached + Assert.True(service.IsBlacklisted(username, bypassCache: false)); + } + } + public class Configuration { [Theory, AutoData] @@ -131,25 +326,126 @@ namespace slskd.Tests.Unit.Users } } - private static (UserService service, Mocks mocks) GetFixture(Options options = null) + public class BlacklistDecisionCache { - var mocks = new Mocks(options); + [Theory, AutoData] + public void Clears_Cache_When_Options_Change(string username) + { + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Members = new[] { username }, + } + } + } + }; + + var (service, mocks) = GetFixture(options); + + Assert.True(service.IsBlacklisted(username)); + Assert.True(service.IsBlacklisted(username, bypassCache: false)); + + mocks.OptionsMonitor.RaiseOnChange(new Options()); + + Assert.False(service.IsBlacklisted(username, bypassCache: false)); + } + + [Theory, AutoData] + public void Clears_Cache_When_Options_Change_Verified(string username) + { + var (service, mocks) = GetFixture(); + + var cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000 }); + service.SetField("<BlacklistDecisionCache>k__BackingField", cache); + + cache.Set(username, true, new MemoryCacheEntryOptions { Size = 1 }); + Assert.True(cache.TryGetValue(username, out _)); + + mocks.OptionsMonitor.RaiseOnChange(new Options()); + + Assert.False(cache.TryGetValue(username, out _)); + } + + [Theory, AutoData] + public void Expires_Cache_Entries_After_10_Minutes(string username) + { + var clock = new TestSystemClock(); + + var options = new Options() + { + Transfers = new Options.TransfersOptions + { + Groups = new Options.TransfersOptions.GroupsOptions + { + Blacklisted = new Options.TransfersOptions.GroupsOptions.BlacklistedOptions + { + Members = new[] { username }, + } + } + } + }; + + var (service, _) = GetFixture(options, clock); + + Assert.True(service.IsBlacklisted(username)); + Assert.True(service.IsBlacklisted(username, bypassCache: false)); + + clock.UtcNow = clock.UtcNow.AddMinutes(11); + + Assert.False(service.IsBlacklisted(username, bypassCache: false)); + } + + [Theory, AutoData] + public void Expires_Cache_Entries_After_10_Minutes_Verified(string username) + { + var clock = new TestSystemClock(); + + var (service, _) = GetFixture(); + + var cache = new MemoryCache(new MemoryCacheOptions { Clock = clock, SizeLimit = 1000 }); + service.SetField("<BlacklistDecisionCache>k__BackingField", cache); + + service.IsBlacklisted(username); + Assert.True(cache.TryGetValue(username, out _)); + + clock.UtcNow = clock.UtcNow.AddMinutes(11); + + Assert.False(cache.TryGetValue(username, out _)); + } + } + + private static (UserService service, Mocks mocks) GetFixture(Options options = null, ISystemClock systemClock = null) + { + var mocks = new Mocks(options, systemClock); var service = new UserService( mocks.SoulseekClient.Object, - mocks.OptionsMonitor); + mocks.OptionsMonitor, + mocks.SystemClock); return (service, mocks); } private class Mocks { - public Mocks(Options options = null) + public Mocks(Options options = null, ISystemClock systemClock = null) { OptionsMonitor = new TestOptionsMonitor<Options>(options ?? new Options()); + SystemClock = systemClock; } public Mock<ISoulseekClient> SoulseekClient { get; } = new Mock<ISoulseekClient>(); public TestOptionsMonitor<Options> OptionsMonitor { get; init; } + public ISystemClock SystemClock { get; init; } + } + + private class TestSystemClock : ISystemClock + { + public DateTimeOffset UtcNow { get; set; } = DateTimeOffset.UtcNow; } } } |
