diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-01-11 16:37:02 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-01-11 16:37:02 -0600 |
| commit | 358a6b1912681d656ff3ff569ddc5bf1bb6a6ef7 (patch) | |
| tree | ae86b9040faf8771c13b50406392dafbe50c506a /src/slskd/Core | |
| parent | 8849d78cbe7057dacad9c00c471691af8e367cd9 (diff) | |
| parent | 0f2df52cbfe2b8afd517a598cbaf9fc55c36083c (diff) | |
| download | slskd-358a6b1912681d656ff3ff569ddc5bf1bb6a6ef7.tar.gz | |
Merge branch 'master' into paths
Diffstat (limited to 'src/slskd/Core')
| -rw-r--r-- | src/slskd/Core/API/Controllers/SessionController.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs | 93 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrator.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 112 | ||||
| -rw-r--r-- | src/slskd/Core/Security/SecurityService.cs | 171 |
5 files changed, 314 insertions, 67 deletions
diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index 861fd468..cfcb3f23 100644 --- a/src/slskd/Core/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -36,7 +36,7 @@ namespace slskd.Core.API public class SessionController : ControllerBase { public SessionController( - ISecurityService securityService, + SecurityService securityService, IOptionsSnapshot<Options> optionsSnapshot, OptionsAtStartup optionsAtStartup) { @@ -47,7 +47,7 @@ namespace slskd.Core.API private IOptionsSnapshot<Options> OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } - private ISecurityService Security { get; } + private SecurityService Security { get; } private ILogger Log { get; } = Serilog.Log.ForContext<SessionController>(); /// <summary> diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs new file mode 100644 index 00000000..2deffeb3 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -0,0 +1,93 @@ +// <copyright file="Z12282025_AdditionalTransferIndexesMigration.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// </copyright> + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// <summary> +/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. +/// </summary> +public class Z12282025_AdditionalTransferIndexesMigration : IMigration +{ + public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext<Z12282025_AdditionalTransferIndexesMigration>(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + var txfers = idxes["Transfers"]; + + var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); + var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); + var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); + + if (removedExists && usernameFilenameExists && statsExist) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z12282025_AdditionalTransferIndexesMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Adding missing index(es) on the Transfers table..."); + + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index b8a7ce10..5561de4b 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -43,6 +43,7 @@ public class Migrator { nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration(connectionStrings: Databases) }, { nameof(Z07062025_TransferIndexesMigration), new Z07062025_TransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z07262025_PrivateMessageWasReplayedMigration), new Z07262025_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, + { nameof(Z12282025_AdditionalTransferIndexesMigration), new Z12282025_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, }; } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 76dcd45c..a1d9953c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -115,7 +115,7 @@ namespace slskd /// <summary> /// Gets a value indicating whether to display a list of configuration environment variables. /// </summary> - [Argument('e', "envars")] + [Argument(default, "envars")] [Description("display environment variables")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -125,7 +125,7 @@ namespace slskd /// <summary> /// Gets a value indicating whether to generate an X509 certificate and password. /// </summary> - [Argument('g', "generate-cert")] + [Argument(default, "generate-cert")] [Description("generate X509 certificate and password for HTTPS")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -135,7 +135,7 @@ namespace slskd /// <summary> /// Gets a value indicating whether to generate a random secret. /// </summary> - [Argument('k', "generate-secret")] + [Argument(default, "generate-secret")] [Description("generate random secret of the specified length")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -1423,6 +1423,12 @@ namespace slskd /// </summary> [Range(5, maximum: int.MaxValue)] public int? Cancelled { get; init; } = null; + + /// <summary> + /// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes. + /// </summary> + [Range(5, maximum: int.MaxValue)] + public int? Failed { get; init; } = null; } } @@ -1839,6 +1845,16 @@ namespace slskd public int Port { get; init; } = 5030; /// <summary> + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests. + /// </summary> + [Argument(default, "http-ip-address")] + [EnvironmentVariable("HTTP_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTP requests")] + [IPAddress(allowCommaSeparatedValues: true)] + [RequiresRestart] + public string IpAddress { get; init; } + + /// <summary> /// Gets the HTTP listen unix domain socket (UDS) path. /// </summary> [Argument(default, "http-socket")] @@ -1893,7 +1909,7 @@ namespace slskd /// <summary> /// Authentication options. /// </summary> - public class WebAuthenticationOptions + public class WebAuthenticationOptions : IValidatableObject { /// <summary> /// Gets a value indicating whether authentication should be disabled. @@ -1931,11 +1947,89 @@ namespace slskd public JwtOptions Jwt { get; init; } = new JwtOptions(); /// <summary> + /// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'. + /// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'. + /// </summary> + [Argument('k', "api-key")] + [EnvironmentVariable("API_KEY")] + [Description("primary API key value")] + [Secret] + [RequiresRestart] + public string ApiKey { get; init; } + + /// <summary> /// Gets API keys. /// </summary> [Validate] public Dictionary<string, ApiKeyOptions> ApiKeys { get; init; } = new Dictionary<string, ApiKeyOptions>(); + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (string.IsNullOrWhiteSpace(ApiKey)) + { + return results; + } + + var tuples = ApiKey.Split(';'); + + // if only one tuple is supplied, it's just the key, no role or list of CIDRs + if (tuples.Length == 1) + { + var key = tuples.FirstOrDefault(); + + if (key?.Length < 16 || key?.Length > 255) + { + results.Add(new ValidationResult("API key must be between 16 and 255 characters")); + } + + return results; + } + + /* + if multiple tuples are supplied, verify that: + + * if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values + * if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid + * if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters + */ + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + var role = tuple.Split('=').LastOrDefault(); + + if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _)) + { + results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}")); + } + } + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) + { + var cidrs = tuple.Split('=').LastOrDefault(); + + foreach (var cidr in cidrs.Split(',')) + { + try + { + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}")); + } + } + } + else if (tuple?.Length < 16 || tuple?.Length > 255) + { + results.Add(new ValidationResult("API key must be between 16 and 255 characters")); + } + } + + return results; + } + /// <summary> /// JWT options. /// </summary> @@ -2040,6 +2134,16 @@ namespace slskd public int Port { get; init; } = 5031; /// <summary> + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests. + /// </summary> + [Argument(default, "https-ip-address")] + [EnvironmentVariable("HTTPS_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTPS requests")] + [IPAddress(allowCommaSeparatedValues: true)] + [RequiresRestart] + public string IpAddress { get; init; } + + /// <summary> /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// </summary> [Argument('f', "force-https")] diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 6da88571..254b3081 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -17,84 +17,133 @@ using Microsoft.Extensions.Options; -namespace slskd +namespace slskd; + +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Net; +using System.Security.Claims; +using Microsoft.IdentityModel.Tokens; +using NetTools; +using slskd.Authentication; + +public class SecurityService { - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Linq; - using System.Net; - using System.Security.Claims; - using Microsoft.IdentityModel.Tokens; - using NetTools; - using slskd.Authentication; - - public interface ISecurityService + public SecurityService( + SymmetricSecurityKey jwtSigningKey, + OptionsAtStartup optionsAtStartup, + IOptionsMonitor<Options> optionsMonitor) { - JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null); - (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress); - } + JwtSigningKey = jwtSigningKey; + OptionsAtStartup = optionsAtStartup; + OptionsMonitor = optionsMonitor; - public class SecurityService : ISecurityService - { - public SecurityService( - SymmetricSecurityKey jwtSigningKey, - OptionsAtStartup optionsAtStartup, - IOptionsMonitor<Options> optionsMonitor) + // parse the configured string into an instance of ApiKeyOptions and assign it to + // PrimaryApiKey, if a string is provided. + // this is kind of expensive in terms of allocations, so do it once at instantiation + // and mark the option with [RequiresRestart] + var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; + + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) { - JwtSigningKey = jwtSigningKey; - OptionsAtStartup = optionsAtStartup; - OptionsMonitor = optionsMonitor; - } + if (!adminApiKeyString.Contains(';')) + { + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = adminApiKeyString, + }; + } - private SymmetricSecurityKey JwtSigningKey { get; } - private OptionsAtStartup OptionsAtStartup { get; } - private IOptionsMonitor<Options> OptionsMonitor { get; } + var tuples = adminApiKeyString.Split(';'); - public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) - { - var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys - .FirstOrDefault(k => k.Value.Key == key); + string key = null; + string role = null; + string cidr = null; - if (record.Key == null) + foreach (var tuple in tuples) { - throw new NotFoundException($"The provided API key does not match an existing key"); + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + role = tuple.Split('=').LastOrDefault(); + } + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) + { + cidr = tuple.Split('=').LastOrDefault(); + } + else + { + key = tuple; + } } - if (!record.Value.Cidr.Split(',') - .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(callerIpAddress))) + if (!string.IsNullOrEmpty(key)) { - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role, + Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr, + }; } + } + } + + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions PrimaryApiKey { get; } = null; + + public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) + { + var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - return (record.Key, record.Value.Role.ToEnum<Role>()); + if (PrimaryApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey)); } - public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null) + var record = keys.FirstOrDefault(k => k.Value.Key == key); + + if (record.Key == null) { - var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl); + throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}"); + } - var claims = new List<Claim>() - { - new Claim(ClaimTypes.Name, username), - new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, role.ToString()), - new Claim("name", username), - new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), - }; - - var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); - - var token = new JwtSecurityToken( - issuer: Program.AppName, - claims: claims, - notBefore: issuedUtc, - expires: expiresUtc, - signingCredentials: credentials); - - return token; + if (!record.Value.Cidr.Split(',') + .Select(cidr => IPAddressRange.Parse(cidr)) + .Any(range => range.Contains(callerIpAddress))) + { + throw new OutOfRangeException($"IP address {callerIpAddress} not included in CIDR range(s) for API key {record.Key}; allowed: {record.Value.Cidr}"); } + + return (record.Key, record.Value.Role.ToEnum<Role>()); + } + + public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null) + { + var issuedUtc = DateTime.UtcNow; + var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl); + + var claims = new List<Claim>() + { + new Claim(ClaimTypes.Name, username), + new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), + new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), + }; + + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); + + var token = new JwtSecurityToken( + issuer: Program.AppName, + claims: claims, + notBefore: issuedUtc, + expires: expiresUtc, + signingCredentials: credentials); + + return token; } } |
