diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-04-27 20:36:53 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-04-27 20:36:53 -0500 |
| commit | 8c611f627b1859a1d9963388fb40f7dfeaeda652 (patch) | |
| tree | 6564d337d0fe73a3c2f93b601e3e782e42f964c1 | |
| parent | cb4d254099cf846f918214c2be07341d93d90900 (diff) | |
| parent | 2b97e3ef7f65b57c3cbe2f3298aef4f856a47985 (diff) | |
| download | slskd-8c611f627b1859a1d9963388fb40f7dfeaeda652.tar.gz | |
Merge branch 'master' into docker-volume
27 files changed, 1508 insertions, 86 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..e68baae2 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -73,6 +73,11 @@ # download: # slots: 500 # speed_limit: 1000 +# retry: +# incomplete: resume # 'overwrite' or 'resume' +# attempts: 3 +# delay: 5000 # initial time between retries, in milliseconds +# max_delay: 60000 # maximum time between retries, in milliseconds # groups: # default: # upload: @@ -112,6 +117,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..14f1ae24 100644 --- a/docs/config.md +++ b/docs/config.md @@ -332,7 +332,7 @@ relay: downloads: false ``` -# Limits and User Groups +# Transfer Behavior, Limits, and User Groups ## Global Slot and Speed Limits @@ -358,6 +358,23 @@ transfers: speed_limit: 1000 ``` +## Retry Behavior + +Failed downloads can be retried automatically up to the configured number of attempts. If an attempt fails initially, the application delays the second attempt by the configured delay, and an exponential backoff is used to compute the delay for all subsequent events, up to the configured maximum delay. + +By default, partial downloads are resumed based on the size of the incomplete file. Users can choose to always overwrite files if they wish. + +**YAML** +```yaml +transfers: + download: + retry: + incomplete: resume # 'overwrite' or 'resume' + attempts: 3 + delay: 5000 # initial time between retries, in milliseconds + max_delay: 60000 # maximum time between retries, in milliseconds +``` + ## Global Upload Limits Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. @@ -491,6 +508,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 +520,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 a8a7883a..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); @@ -1452,7 +1459,7 @@ namespace slskd foreach (var (property, fqn, left, right) in diff) { - static bool HasAttribute<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + static bool HasAttribute<T>(PropertyInfo property) => property?.CustomAttributes.Any(a => a.AttributeType == typeof(T)) ?? false; var requiresRestart = HasAttribute<RequiresRestartAttribute>(property); var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property); @@ -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/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 88e6d3c8..77db91ef 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -111,20 +111,41 @@ namespace slskd /// <returns>A list of differences between the two objects.</returns> public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) { - if (left?.GetType() != right?.GetType()) + if (left is null || right is null) { - throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}"); + if (left is null == right is null) + { + return []; + } + + return [(null, parentFqn ?? string.Empty, left, right)]; + } + + if (left.GetType() != right.GetType()) + { + throw new InvalidCastException($"Unable to diff types {left.GetType()} and {right.GetType()}"); } var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); - foreach (var prop in left?.GetType().GetProperties()) + foreach (var prop in left.GetType().GetProperties()) { var leftVal = prop.GetValue(left); var rightVal = prop.GetValue(right); var propType = prop.PropertyType; var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); + if (leftVal is null || rightVal is null) + { + if (leftVal is null == rightVal is null) + { + continue; + } + + differences.Add((prop, fqn, leftVal, rightVal)); + continue; + } + if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>))) { if (leftVal.ToJson() != rightVal.ToJson()) diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index 53aa59db..a14d2def 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -52,6 +52,7 @@ namespace slskd /// <param name="maxAttempts">The maximum number of retry attempts.</param> /// <param name="baseDelayInMilliseconds">The base delay in milliseconds.</param> /// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param> + /// <param name="exceptionHistoryLimit">The maximum number of Exceptions to keep in history.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The execution context.</returns> public static async Task Do( @@ -62,13 +63,14 @@ namespace slskd int maxAttempts = 3, int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue, + int exceptionHistoryLimit = 5, CancellationToken cancellationToken = default) { await Do<object>(async () => { await task(); return Task.FromResult<object>(null); - }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken); + }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, exceptionHistoryLimit, cancellationToken); } /// <summary> @@ -81,6 +83,7 @@ namespace slskd /// <param name="maxAttempts">The maximum number of retry attempts.</param> /// <param name="baseDelayInMilliseconds">The base delay in milliseconds.</param> /// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param> + /// <param name="exceptionHistoryLimit">The maximum number of Exceptions to keep in history.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <typeparam name="T">The Type of the logic return value.</typeparam> /// <returns>The execution context.</returns> @@ -92,11 +95,12 @@ namespace slskd int maxAttempts = 3, int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue, + int exceptionHistoryLimit = 5, CancellationToken cancellationToken = default) { isRetryable ??= (_, _) => true; - var exceptions = new List<Exception>(); + var exceptions = new Queue<Exception>(); for (int attempts = 0; attempts < maxAttempts; attempts++) { @@ -119,7 +123,12 @@ namespace slskd } catch (Exception ex) { - exceptions.Add(ex); + exceptions.Enqueue(ex); + + if (exceptions.Count > exceptionHistoryLimit) + { + exceptions.Dequeue(); + } try { diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7b38143e..8cc369af 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -50,6 +50,7 @@ namespace slskd using slskd.Events; using slskd.Relay; using slskd.Shares; + using slskd.Transfers; using slskd.Validation; using Utility.CommandLine; using Utility.EnvironmentVariables; @@ -1010,6 +1011,42 @@ namespace slskd [Description("the total download speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; + + /// <summary> + /// Gets download retry options. + /// </summary> + [Validate] + public RetryOptions Retry { get; init; } = new RetryOptions(); + + /// <summary> + /// Download retry options. + /// </summary> + public class RetryOptions + { + /// <summary> + /// Gets the maximum number of times to retry a failed transfer. + /// </summary> + [Range(1, int.MaxValue)] + public int Attempts { get; init; } = 3; + + /// <summary> + /// Gets the base time to wait between retry attempts, in milliseconds. + /// </summary> + [Range(1000, int.MaxValue)] + public int Delay { get; init; } = 5000; + + /// <summary> + /// Gets the maximum time to wait between retry attempts, in milliseconds. + /// </summary> + [Range(30_000, int.MaxValue)] + public int MaxDelay { get; init; } = 60_000; + + /// <summary> + /// Gets the strategy for handling incomplete files upon retry. + /// </summary> + [Enum(typeof(RetryIncompleteStrategy))] + public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant(); + } } /// <summary> @@ -1150,6 +1187,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 +1205,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/Program.cs b/src/slskd/Program.cs index 25077de7..42f43918 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -706,11 +706,11 @@ namespace slskd new SoulseekClient( minorVersion: NetworkMinorVersion, options: new SoulseekClientOptions( - maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots, - maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(), - maximumConcurrentSearches: 2, - raiseEventsAsynchronously: true))); + maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots, + maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots, + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(), + maximumConcurrentSearches: 2, + raiseEventsAsynchronously: true))); // add the core application service to DI as well as a hosted service so that other services can // access instance methods diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 53e2830f..8430164c 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -109,7 +109,6 @@ namespace slskd.Relay private IOptionsMonitor<Options> OptionsMonitor { get; } private OptionsAtStartup OptionsAtStartup { get; } private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>(); - private IPAddress RemoteIpAddress => Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress; /// <summary> /// Executed when a new connection is established. @@ -119,13 +118,13 @@ namespace slskd.Relay { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { - Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, RemoteIpAddress); + Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, GetRemoteIPAddress()); Context.Abort(); } var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); - Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, RemoteIpAddress, token); + Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, GetRemoteIPAddress(), token); await Clients.Caller.Challenge(token); } @@ -138,7 +137,7 @@ namespace slskd.Relay { if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record)) { - Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress()); Relay.TryDeregisterAgent(record.Agent.Name, out _); } @@ -170,23 +169,25 @@ namespace slskd.Relay return false; } + var remoteIP = GetRemoteIPAddress(); + if (!TryGetAgentConfig(agent, out var agentOptions)) { - Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, remoteIP); throw new UnauthorizedAccessException(); } if (!agentOptions.Cidr.Split(',') .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(RemoteIpAddress))) + .Any(range => range.Contains(remoteIP))) { - Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, RemoteIpAddress, agentOptions.Cidr); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, remoteIP, agentOptions.Cidr); throw new UnauthorizedAccessException(); } if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { - Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, remoteIP); Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! throw new UnauthorizedAccessException(); } @@ -208,12 +209,12 @@ namespace slskd.Relay if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { // this can happen if the agent attempts to upload before logging in - Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } var token = Relay.GenerateShareUploadToken(record.Agent.Name); - Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, RemoteIpAddress, token); + Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, GetRemoteIPAddress(), token); return token; } @@ -227,11 +228,11 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } - Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, RemoteIpAddress, id, exception.Message); + Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, GetRemoteIPAddress(), id, exception.Message); Relay.NotifyFileStreamException(record.Agent.Name, id, exception); } @@ -247,13 +248,26 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } - Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, RemoteIpAddress, id, exists, length); + Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress(), id, exists, length); Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } + + private IPAddress GetRemoteIPAddress() + { + var ip = Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress; + + // looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4 + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + return ip; + } } }
\ No newline at end of file diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 6fb2f360..9aec7b00 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -362,11 +362,6 @@ namespace slskd.Relay LoggedInTaskCompletionSource.TrySetResult(); } - catch (UnauthorizedAccessException) - { - await HubConnection.StopAsync(); - Log.Error("Relay controller authentication failed. Check configuration."); - } catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); @@ -532,6 +527,8 @@ namespace slskd.Relay Log.Information("Uploading shares..."); await UploadSharesAsync(); + + Log.Information("Shares uploaded. Ready to relay files."); } catch (Exception ex) { @@ -542,8 +539,6 @@ namespace slskd.Relay await StopAsync(); _ = StartAsync(); } - - Log.Information("Shares uploaded. Ready to relay files."); } private Task HubConnection_Reconnecting(Exception arg) diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index cab4e406..ae2d1129 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -38,6 +38,7 @@ using System.Linq; using Dapper; using Microsoft.Data.Sqlite; using Serilog; +using slskd.Transfers; using Soulseek; /// <summary> @@ -99,6 +100,7 @@ public class ReportsService FROM Transfers WHERE EndedAt IS NOT NULL AND EndedAt BETWEEN @Start AND @End + AND State IN ({string.Join(", ", TransferStateCategories.Completed.Select(s => (int)s))}) {(direction is not null ? "AND Direction = @Direction" : string.Empty)} {(username is not null ? "AND Username = @Username" : string.Empty)} GROUP BY Direction, StateDescription @@ -186,6 +188,7 @@ public class ReportsService FROM Transfers WHERE EndedAt IS NOT NULL AND EndedAt BETWEEN @Start AND @End + AND State IN ({string.Join(", ", TransferStateCategories.Completed.Select(s => (int)s))}) {(direction is not null ? "AND Direction = @Direction" : string.Empty)} {(username is not null ? "AND Username = @Username" : string.Empty)} GROUP BY Interval, Direction, StateDescription 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/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs new file mode 100644 index 00000000..ce3331ca --- /dev/null +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -0,0 +1,57 @@ +// <copyright file="EnqueueDownloadBatchRequest.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> + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace slskd.Transfers.API; + +public record EnqueueDownloadBatchRequest +{ + public Guid? BatchId { get; init; } + public Guid? SearchId { get; init; } + + [Required] + [StringLength(500, MinimumLength = 1)] + public string Username { get; init; } + public List<EnqueueDownloadBatchItem> Files { get; init; } = []; +} + +public record EnqueueDownloadBatchItem +{ + [Required] + public string Filename { get; set; } + + [Range(0, int.MaxValue)] + public long Size { get; set; } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c8e10fe6..d4d8004a 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -937,6 +937,7 @@ namespace slskd.Transfers.Downloads using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None); cancellationToken = cts.Token; + var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry; var updateSyncRoot = new SemaphoreSlim(1, 1); try @@ -967,6 +968,16 @@ namespace slskd.Transfers.Downloads transfer.EnqueuedAt ??= DateTime.UtcNow; } + // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer + // *might* still have remaining retry attempts. leave this non-committal for now, and allow + // the final update after all retry attempts have been exhausted to add it. + // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all + // retries is to look for this flag + if (transfer.Attempts < retryOptions.Attempts) + { + transfer.State &= ~TransferStates.Completed; // remove the Completed flag + } + // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } @@ -1017,26 +1028,79 @@ namespace slskd.Transfers.Downloads ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; + // if the transfer has an associated batch id, store the incomplete file in a directory of the same name + // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file) + var incompleteFilename = transfer.Filename.ToLocalFilename( + baseDirectory: System.IO.Path.Combine( + OptionsMonitor.CurrentValue.Directories.Incomplete, + transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); + transfer.Attempts = 1; + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + + var completedTransfer = await Retry.Do(() => + { + var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename); + var incompleteStrategy = retryOptions.Incomplete.ToEnum<RetryIncompleteStrategy>(); + + var shouldResume = false; + var startOffset = 0L; - var completedTransfer = await Client.DownloadAsync( - username: transfer.Username, - remoteFilename: transfer.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions + if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0) + { + if (incompleteStrategy == RetryIncompleteStrategy.Resume) + { + shouldResume = true; + startOffset = incompleteFileInfo.Length; + Log.Information("Resuming download of {Filename} from user {Username} at offset {Offet}", transfer.Filename, transfer.Username, incompleteFileInfo.Length); + } + else { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = unixFileMode, - })), - size: transfer.Size, - startOffset: 0, - token: null, - cancellationToken: cancellationToken, - options: topts); + Log.Information("Overwriting partial download of {Length} bytes for download of {Filename} from user {Username} at offset {Offet}", incompleteFileInfo.Length, transfer.Filename, transfer.Username); + } + } + + return Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: incompleteFilename, + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = shouldResume ? System.IO.FileMode.Append : System.IO.FileMode.Create, + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = unixFileMode, + })), + size: transfer.Size, + startOffset: startOffset, + token: null, + cancellationToken: cancellationToken, + options: topts); + }, + isRetryable: (attempts, ex) => + ex is not OperationCanceledException + && ex is not TransferRejectedException + && ex is not DuplicateTransferException + && ex is not TransferSizeMismatchException, + onRetry: (attempts, delay) => + { + Log.Information("Waiting about {Delay} second(s) to retry attempt #{Attempt} to download {Filename} from user {Username} in {Delay}ms", (int)Math.Ceiling((double)delay / 1000), attempts, transfer.Filename, transfer.Username); + + transfer.Attempts = attempts; + transfer.State = TransferStates.Queued | TransferStates.Locally; + SynchronizedUpdate(transfer, updateSyncRoot); + }, + onFailure: (attempts, ex) => + { + Log.Warning("Failed attempt #{Attempts} to download {Filename} from user {Username}: {Message}", attempts, transfer.Filename, transfer.Username, ex.Message); + }, + maxAttempts: retryOptions.Attempts, + baseDelayInMilliseconds: retryOptions.Delay, + maxDelayInMilliseconds: retryOptions.MaxDelay, + cancellationToken: cancellationToken); Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); @@ -1053,8 +1117,28 @@ namespace slskd.Transfers.Downloads Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); - // move the file from incomplete to complete - var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + /* + move the file from incomplete to complete + + users have a lot of strong opinions about this! + */ + string destinationDirectory; + + if (transfer.BatchId is not null) + { + // if the transfer has an associated batch id, then: + // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext + destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); + } + else + { + // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so: + // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext + // this is "legacy" behavior that will be familiar to most Soulseek users + destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + } + + Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); var finalFilename = Files.MoveFile( sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index 1c5ff4b5..48179ff2 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -53,6 +53,7 @@ namespace slskd.Transfers BytesTransferred = t.BytesTransferred, AverageSpeed = t.AverageSpeed, Exception = t.Exception?.Message, + Attempts = transfer.Attempts, }; } } diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs new file mode 100644 index 00000000..9ac8d8e2 --- /dev/null +++ b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs @@ -0,0 +1,49 @@ +// <copyright file="RetryIncompleteStrategy.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.Transfers; + +/// <summary> +/// Strategy for retrying incomplete files. +/// </summary> +public enum RetryIncompleteStrategy +{ + /// <summary> + /// Overwrite the existing file. + /// </summary> + Overwrite = 0, + + /// <summary> + /// Resume the transfer using the size of the incomplete file as the initial offset. + /// </summary> + Resume = 1, +}
\ No newline at end of file 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/src/web/package-lock.json b/src/web/package-lock.json index f309d9af..22d9c714 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -10906,9 +10906,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", - "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", "funding": [ { "type": "individual", diff --git a/src/web/src/components/Transfers/TransferDetails.jsx b/src/web/src/components/Transfers/TransferDetails.jsx index 256ddcac..2ec890e9 100644 --- a/src/web/src/components/Transfers/TransferDetails.jsx +++ b/src/web/src/components/Transfers/TransferDetails.jsx @@ -79,6 +79,8 @@ const TransferDetails = ({ file }) => { 'elapsedTime', 'percentComplete', 'remainingTime', + 'attempts', + 'exception', ]; return ( diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index 4bd1e14e..42e58933 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -163,6 +163,9 @@ class TransferList extends Component { padding: 7, }} {...getColor(f.state)} + {...(!getColor(f.state).color && f.attempts > 1 + ? { color: 'yellow' } + : {})} active={f.direction === 'Upload'} onClick={() => this.handleClick(f)} > @@ -176,6 +179,7 @@ class TransferList extends Component { )} {f.state} {f.placeInQueue ? ` (#${f.placeInQueue})` : ''} + {f.attempts > 1 ? ` (Retry #${f.attempts})` : ''} </Button> )} </Table.Cell> diff --git a/tests/slskd.Tests.Unit/Common/CommonExtensionsTests.cs b/tests/slskd.Tests.Unit/Common/CommonExtensionsTests.cs new file mode 100644 index 00000000..d22a3bbe --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/CommonExtensionsTests.cs @@ -0,0 +1,523 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public class CommonExtensionsTests +{ + private class Simple + { + public int IntProp { get; set; } + public string StringProp { get; set; } + public bool BoolProp { get; set; } + public decimal DecimalProp { get; set; } + } + + private class WithNullable + { + public int? NullableInt { get; set; } + public string StringProp { get; set; } + } + + private class WithEnum + { + public DayOfWeek EnumProp { get; set; } + } + + private class WithArray + { + public int[] ArrayProp { get; set; } + } + + private class WithDictionary + { + public Dictionary<string, int> DictProp { get; set; } + } + + private class Nested + { + public string Name { get; set; } + public Simple Inner { get; set; } + } + + public class DiffWith_NullHandling + { + [Fact] + public void Both_Null_Returns_Empty() + { + object left = null; + object right = null; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Left_Null_Right_NonNull_Returns_Difference() + { + object left = null; + object right = new Simple(); + + var result = left.DiffWith(right); + + var (_, _, leftVal, rightVal) = Assert.Single(result); + Assert.Null(leftVal); + Assert.NotNull(rightVal); + } + + [Fact] + public void Left_NonNull_Right_Null_Returns_Difference() + { + object left = new Simple(); + object right = null; + + var result = left.DiffWith(right); + + var (_, _, leftVal, rightVal) = Assert.Single(result); + Assert.NotNull(leftVal); + Assert.Null(rightVal); + } + + [Fact] + public void Left_Null_Right_NonNull_FQN_Is_ParentFqn() + { + object left = null; + object right = new Simple(); + + var result = left.DiffWith(right, "root"); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("root", fqn); + } + + [Fact] + public void Left_Null_Right_NonNull_FQN_Is_Empty_When_No_ParentFqn() + { + object left = null; + object right = new Simple(); + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal(string.Empty, fqn); + } + + [Fact] + public void Right_Null_Left_NonNull_FQN_Is_Empty_When_No_ParentFqn() + { + object left = new Simple(); + object right = null; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal(string.Empty, fqn); + } + + [Fact] + public void Mismatched_Types_Throws_InvalidCastException() + { + object left = new Simple(); + object right = new WithNullable(); + + Assert.Throws<InvalidCastException>(() => left.DiffWith(right)); + } + + [Fact] + public void Left_Null_Right_NonNull_Any_Type_Returns_Difference() + { + object left = null; + object right = 42; + + var result = left.DiffWith(right); + + var (_, _, leftVal, rightVal) = Assert.Single(result); + Assert.Null(leftVal); + Assert.Equal(42, rightVal); + } + + [Fact] + public void Right_Null_Left_NonNull_Any_Type_Returns_Difference() + { + object left = 42; + object right = null; + + var result = left.DiffWith(right); + + var (_, _, leftVal, rightVal) = Assert.Single(result); + Assert.Equal(42, leftVal); + Assert.Null(rightVal); + } + } + + public class DiffWith_PrimitiveProperties + { + [Fact] + public void Identical_Objects_Returns_Empty() + { + var left = new Simple { IntProp = 1, StringProp = "a", BoolProp = true, DecimalProp = 1.5m }; + var right = new Simple { IntProp = 1, StringProp = "a", BoolProp = true, DecimalProp = 1.5m }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Different_Int_Returns_Difference() + { + var left = new Simple { IntProp = 1 }; + var right = new Simple { IntProp = 2 }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("IntProp", fqn); + Assert.Equal(1, leftVal); + Assert.Equal(2, rightVal); + } + + [Fact] + public void Different_String_Returns_Difference() + { + var left = new Simple { StringProp = "foo" }; + var right = new Simple { StringProp = "bar" }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("StringProp", fqn); + } + + [Fact] + public void Different_Bool_Returns_Difference() + { + var left = new Simple { BoolProp = true }; + var right = new Simple { BoolProp = false }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("BoolProp", fqn); + } + + [Fact] + public void Different_Decimal_Returns_Difference() + { + var left = new Simple { DecimalProp = 1.1m }; + var right = new Simple { DecimalProp = 2.2m }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("DecimalProp", fqn); + } + + [Fact] + public void Multiple_Differences_All_Returned() + { + var left = new Simple { IntProp = 1, StringProp = "a" }; + var right = new Simple { IntProp = 2, StringProp = "b" }; + + var result = left.DiffWith(right); + + Assert.Equal(2, result.Count()); + } + } + + public class DiffWith_NullableProperties + { + [Fact] + public void Both_Nullable_Null_No_Difference() + { + var left = new WithNullable { NullableInt = null }; + var right = new WithNullable { NullableInt = null }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Left_Nullable_Null_Right_HasValue_Returns_Difference() + { + var left = new WithNullable { NullableInt = null }; + var right = new WithNullable { NullableInt = 5 }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("NullableInt", fqn); + Assert.Null(leftVal); + Assert.Equal(5, rightVal); + } + + [Fact] + public void Right_Nullable_Null_Left_HasValue_Returns_Difference() + { + var left = new WithNullable { NullableInt = 5 }; + var right = new WithNullable { NullableInt = null }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("NullableInt", fqn); + Assert.Equal(5, leftVal); + Assert.Null(rightVal); + } + + [Fact] + public void Both_Nullable_Same_Value_No_Difference() + { + var left = new WithNullable { NullableInt = 7 }; + var right = new WithNullable { NullableInt = 7 }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void String_Null_Both_Sides_No_Difference() + { + var left = new WithNullable { StringProp = null }; + var right = new WithNullable { StringProp = null }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void String_Null_Left_NonNull_Right_Returns_Difference() + { + var left = new WithNullable { StringProp = null }; + var right = new WithNullable { StringProp = "hello" }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("StringProp", fqn); + Assert.Null(leftVal); + Assert.Equal("hello", rightVal); + } + } + + public class DiffWith_EnumProperties + { + [Fact] + public void Same_Enum_No_Difference() + { + var left = new WithEnum { EnumProp = DayOfWeek.Monday }; + var right = new WithEnum { EnumProp = DayOfWeek.Monday }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Different_Enum_Returns_Difference() + { + var left = new WithEnum { EnumProp = DayOfWeek.Monday }; + var right = new WithEnum { EnumProp = DayOfWeek.Friday }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("EnumProp", fqn); + Assert.Equal(DayOfWeek.Monday, leftVal); + Assert.Equal(DayOfWeek.Friday, rightVal); + } + } + + public class DiffWith_ArrayProperties + { + [Fact] + public void Same_Array_No_Difference() + { + var left = new WithArray { ArrayProp = [1, 2, 3] }; + var right = new WithArray { ArrayProp = [1, 2, 3] }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Different_Array_Returns_Difference() + { + var left = new WithArray { ArrayProp = [1, 2, 3] }; + var right = new WithArray { ArrayProp = [1, 2, 4] }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("ArrayProp", fqn); + } + + [Fact] + public void Different_Array_Length_Returns_Difference() + { + var left = new WithArray { ArrayProp = [1, 2] }; + var right = new WithArray { ArrayProp = [1, 2, 3] }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("ArrayProp", fqn); + } + + [Fact] + public void Both_Arrays_Null_No_Difference() + { + var left = new WithArray { ArrayProp = null }; + var right = new WithArray { ArrayProp = null }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Left_Array_Null_Right_NonNull_Returns_Difference() + { + var left = new WithArray { ArrayProp = null }; + var right = new WithArray { ArrayProp = [1] }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("ArrayProp", fqn); + Assert.Null(leftVal); + Assert.NotNull(rightVal); + } + } + + public class DiffWith_DictionaryProperties + { + [Fact] + public void Same_Dictionary_No_Difference() + { + var left = new WithDictionary { DictProp = new Dictionary<string, int> { ["a"] = 1 } }; + var right = new WithDictionary { DictProp = new Dictionary<string, int> { ["a"] = 1 } }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Different_Dictionary_Returns_Difference() + { + var left = new WithDictionary { DictProp = new Dictionary<string, int> { ["a"] = 1 } }; + var right = new WithDictionary { DictProp = new Dictionary<string, int> { ["a"] = 2 } }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("DictProp", fqn); + } + + [Fact] + public void Both_Dictionaries_Null_No_Difference() + { + var left = new WithDictionary { DictProp = null }; + var right = new WithDictionary { DictProp = null }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Left_Dictionary_Null_Right_NonNull_Returns_Difference() + { + var left = new WithDictionary { DictProp = null }; + var right = new WithDictionary { DictProp = new Dictionary<string, int> { ["a"] = 1 } }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("DictProp", fqn); + } + } + + public class DiffWith_NestedObjects + { + [Fact] + public void Identical_Nested_Objects_Returns_Empty() + { + var left = new Nested { Name = "x", Inner = new Simple { IntProp = 1 } }; + var right = new Nested { Name = "x", Inner = new Simple { IntProp = 1 } }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Different_Nested_Property_FQN_Is_Dotted() + { + var left = new Nested { Inner = new Simple { IntProp = 1 } }; + var right = new Nested { Inner = new Simple { IntProp = 9 } }; + + var result = left.DiffWith(right); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("Inner.IntProp", fqn); + } + + [Fact] + public void Both_Nested_Null_No_Difference() + { + var left = new Nested { Inner = null }; + var right = new Nested { Inner = null }; + + var result = left.DiffWith(right); + + Assert.Empty(result); + } + + [Fact] + public void Left_Nested_Null_Right_NonNull_Returns_Difference() + { + var left = new Nested { Inner = null }; + var right = new Nested { Inner = new Simple() }; + + var result = left.DiffWith(right); + + var (_, fqn, leftVal, rightVal) = Assert.Single(result); + Assert.Equal("Inner", fqn); + Assert.Null(leftVal); + Assert.NotNull(rightVal); + } + + [Fact] + public void ParentFqn_Prepended_To_Nested_FQN() + { + var left = new Nested { Inner = new Simple { IntProp = 1 } }; + var right = new Nested { Inner = new Simple { IntProp = 2 } }; + + var result = left.DiffWith(right, "root"); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("root.Inner.IntProp", fqn); + } + + [Fact] + public void Top_Level_Property_FQN_Includes_ParentFqn() + { + var left = new Simple { IntProp = 1 }; + var right = new Simple { IntProp = 2 }; + + var result = left.DiffWith(right, "root"); + + var (_, fqn, _, _) = Assert.Single(result); + Assert.Equal("root.IntProp", fqn); + } + } +} 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; } } } |
