From 46ec9c72ff1904e917eb695bbb88241b001e681e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 Aug 2025 19:05:21 -0500 Subject: namespace tweaking --- src/slskd/Core/Data/Databases.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Databases.cs b/src/slskd/Core/Data/Databases.cs index f118ad2a..a5d51ea6 100644 --- a/src/slskd/Core/Data/Databases.cs +++ b/src/slskd/Core/Data/Databases.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +namespace slskd; + /// /// A primitive type for Database names and a static value for each of them. And a list. /// -- cgit v1.2.3 From 865fcbc4fed85e9eac58125092838f08dbd55430 Mon Sep 17 00:00:00 2001 From: xovi Date: Wed, 26 Nov 2025 15:23:43 +0100 Subject: Added configurable ip address for the Web GUI (useful for ipv6 only users) --- config/slskd.example.yml | 2 ++ src/slskd/Core/Options.cs | 22 +++++++++++++++++++++- src/slskd/Program.cs | 10 ++++++---- 3 files changed, 29 insertions(+), 5 deletions(-) (limited to 'src/slskd/Core') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index a0ca4f3f..f923afbf 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -137,10 +137,12 @@ # - ^.{1,2}$ # web: # port: 5030 +# listen_ip_address: 0.0.0.0 # socket: ~ # https: # disabled: false # port: 5031 +# listen_ip_address: 0.0.0.0 # force: false # certificate: # pfx: ~ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 254adcab..ab08be04 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1832,6 +1832,16 @@ namespace slskd [RequiresRestart] public int Port { get; init; } = 5030; + /// + /// Gets the IP address on which to listen for HTTP requests. + /// + [Argument(default, "http-listen-ip-address")] + [EnvironmentVariable("HTTP_LISTEN_IP_ADDRESS")] + [Description("IP address on which to listen for HTTP requests")] + [IPAddress] + [RequiresRestart] + public string ListenIpAddress { get; init; } = "0.0.0.0"; + /// /// Gets the HTTP listen unix domain socket (UDS) path. /// @@ -2032,7 +2042,17 @@ namespace slskd [Range(1, 65535)] [RequiresRestart] public int Port { get; init; } = 5031; - + + /// + /// Gets the IP address on which to listen for HTTPS requests. + /// + [Argument(default, "https-listen-ip-address")] + [EnvironmentVariable("HTTPS_LISTEN_IP_ADDRESS")] + [Description("IP address on which to listen for HTTPS requests")] + [IPAddress] + [RequiresRestart] + public string ListenIpAddress { get; init; } = "0.0.0.0"; + /// /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6b50aedb..e693db63 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -474,8 +474,9 @@ namespace slskd .UseUrls() .UseKestrel(options => { - Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); - options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); + var httpIpAddress = IPAddress.Parse(OptionsAtStartup.Web.ListenIpAddress); + Log.Information($"Listening for HTTP requests at http://{httpIpAddress}:{OptionsAtStartup.Web.Port}/"); + options.Listen(httpIpAddress, OptionsAtStartup.Web.Port); if (OptionsAtStartup.Web.Socket != null) { @@ -485,8 +486,9 @@ namespace slskd if (!OptionsAtStartup.Web.Https.Disabled) { - Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); - options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => + var httpsIpAddress = IPAddress.Parse(OptionsAtStartup.Web.Https.ListenIpAddress); + Log.Information($"Listening for HTTPS requests at https://{httpsIpAddress}:{OptionsAtStartup.Web.Https.Port}/"); + options.Listen(httpsIpAddress, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; -- cgit v1.2.3 From ea0d7e74ada936d4212129a58bd3a29e09ba8c3e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:08:34 +0000 Subject: Add validation check for blacklist file when enabled Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Core/Options.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 254adcab..b93ac5e2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1252,6 +1252,12 @@ namespace slskd return results; } + if (string.IsNullOrWhiteSpace(File)) + { + results.Add(new ValidationResult("The Enabled field is true, but no File has been specified")); + return results; + } + // loading/validating the entire list will be costly on low spec systems // just make sure that we can detect a valid format and leave it at that // if there's a problem with any of the entries, the load will fail and -- cgit v1.2.3 From 88b42219f4bd707713a90656d9177458a447005b Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:09:59 +0000 Subject: Add period to validation message for consistency Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index b93ac5e2..76dcd45c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1254,7 +1254,7 @@ namespace slskd if (string.IsNullOrWhiteSpace(File)) { - results.Add(new ValidationResult("The Enabled field is true, but no File has been specified")); + results.Add(new ValidationResult("The Enabled field is true, but no File has been specified.")); return results; } -- cgit v1.2.3 From 35a8023360d444021167022970bff1a85ed4e9b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Dec 2025 19:28:21 -0600 Subject: update options to allow comma separated lists --- src/slskd/Core/Options.cs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d3e302a5..afeb1797 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1839,14 +1839,14 @@ namespace slskd public int Port { get; init; } = 5030; /// - /// Gets the IP address on which to listen for HTTP requests. + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests. /// - [Argument(default, "http-listen-ip-address")] - [EnvironmentVariable("HTTP_LISTEN_IP_ADDRESS")] - [Description("IP address on which to listen for HTTP requests")] + [Argument(default, "http-ip-address")] + [EnvironmentVariable("HTTP_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTP requests")] [IPAddress] [RequiresRestart] - public string ListenIpAddress { get; init; } = "0.0.0.0"; + public string IpAddress { get; init; } /// /// Gets the HTTP listen unix domain socket (UDS) path. @@ -2048,17 +2048,17 @@ namespace slskd [Range(1, 65535)] [RequiresRestart] public int Port { get; init; } = 5031; - + /// - /// Gets the IP address on which to listen for HTTPS requests. + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests. /// - [Argument(default, "https-listen-ip-address")] - [EnvironmentVariable("HTTPS_LISTEN_IP_ADDRESS")] - [Description("IP address on which to listen for HTTPS requests")] - [IPAddress] + [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 ListenIpAddress { get; init; } = "0.0.0.0"; - + public string IpAddress { get; init; } + /// /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// -- cgit v1.2.3 From c026b58c435372b7042d5a1ddf911dd4429ba993 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Dec 2025 19:28:43 -0600 Subject: allow lists --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index afeb1797..1739f5fb 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1844,7 +1844,7 @@ namespace slskd [Argument(default, "http-ip-address")] [EnvironmentVariable("HTTP_IP_ADDRESS")] [Description("IP addresses on which to listen for HTTP requests")] - [IPAddress] + [IPAddress(allowCommaSeparatedValues: true)] [RequiresRestart] public string IpAddress { get; init; } -- cgit v1.2.3 From 08b20cd73d1fed6100649d3d0f4886a1c4362823 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 09:34:01 -0600 Subject: remove single character cli args for envars and cert/secret gen --- src/slskd/Core/Options.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1739f5fb..cca7e01d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -115,7 +115,7 @@ namespace slskd /// /// Gets a value indicating whether to display a list of configuration environment variables. /// - [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 /// /// Gets a value indicating whether to generate an X509 certificate and password. /// - [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 /// /// Gets a value indicating whether to generate a random secret. /// - [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] -- cgit v1.2.3 From eaab0b09e0e23ca661163fe7da6ccbab64a24cc8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:10:36 -0600 Subject: add validation of admin api key --- src/slskd/Core/Options.cs | 69 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cca7e01d..fc367578 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1903,7 +1903,7 @@ namespace slskd /// /// Authentication options. /// - public class WebAuthenticationOptions + public class WebAuthenticationOptions : IValidatableObject { /// /// Gets a value indicating whether authentication should be disabled. @@ -1940,12 +1940,79 @@ namespace slskd [RequiresRestart] public JwtOptions Jwt { get; init; } = new JwtOptions(); + /// + /// 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]'. + /// + [Description("Administrative API key value")] + [Secret] + [RequiresRestart] + public string ApiKey { get; init; } + /// /// Gets API keys. /// [Validate] public Dictionary ApiKeys { get; init; } = new Dictionary(); + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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")); + } + } + + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + var role = tuple.Split('=').LastOrDefault(); + + if (!Enum.TryParse(typeof(Role), role, 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; + } + /// /// JWT options. /// -- cgit v1.2.3 From 8892dfa4eaffcc1cbc3b1f74127911fe056188d9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:11:01 -0600 Subject: auth with admin api key --- src/slskd/Core/Security/SecurityService.cs | 56 ++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 6da88571..871e6e95 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -45,16 +45,68 @@ namespace slskd JwtSigningKey = jwtSigningKey; OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + + var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; + + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + { + if (!adminApiKeyString.Contains(';')) + { + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = adminApiKeyString, + }; + } + + var tuples = adminApiKeyString.Split(';'); + + string key = null; + string role = null; + string cidr = null; + + foreach (var tuple in tuples) + { + 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 (!string.IsNullOrEmpty(key)) + { + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = role, + Cidr = cidr, + }; + } + } } private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) { - var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys - .FirstOrDefault(k => k.Value.Key == key); + var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); + + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + } + + var record = keys.FirstOrDefault(k => k.Value.Key == key); if (record.Key == null) { -- cgit v1.2.3 From c6f912f4df7cba8abc947f4ed57a23ed0e58d995 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:13:15 -0600 Subject: todos --- src/slskd/Core/Options.cs | 1 + src/slskd/Core/Security/SecurityService.cs | 5 +++++ 2 files changed, 6 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index fc367578..ced7c96f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1957,6 +1957,7 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { + // TODO: test me! var results = new List(); if (string.IsNullOrWhiteSpace(ApiKey)) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 871e6e95..c5531a35 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -46,6 +46,10 @@ namespace slskd OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + // parse the configured string into an instance of ApiKeyOptions and assign it to + // AdministrativeApiKey, 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)) @@ -101,6 +105,7 @@ namespace slskd { var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); + // TODO: test me! if (AdministrativeApiKey is not null) { keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); -- cgit v1.2.3 From 8fadf7bdd6b253895a273fe6ffc8bd4943f07ee9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 11:48:45 -0600 Subject: tweak validation --- src/slskd/Core/Options.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index ced7c96f..43363654 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1944,6 +1944,8 @@ namespace slskd /// 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]'. /// + [Argument('k', "api-key")] + [EnvironmentVariable("API_KEY")] [Description("Administrative API key value")] [Secret] [RequiresRestart] @@ -1957,7 +1959,6 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { - // TODO: test me! var results = new List(); if (string.IsNullOrWhiteSpace(ApiKey)) @@ -1976,15 +1977,24 @@ namespace slskd { 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), role, out _)) + 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)))}")); } -- cgit v1.2.3 From 1c2983723e4c683f101bb9988844a2812aab749d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 13:02:35 -0600 Subject: add logger, use file scoped namespace --- src/slskd/Core/Security/SecurityService.cs | 218 ++++++++++++++--------------- 1 file changed, 107 insertions(+), 111 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index c5531a35..9a87449e 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -17,141 +17,137 @@ 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 Serilog; +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 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 optionsMonitor) - { - JwtSigningKey = jwtSigningKey; - OptionsAtStartup = optionsAtStartup; - OptionsMonitor = optionsMonitor; + // parse the configured string into an instance of ApiKeyOptions and assign it to + // AdministrativeApiKey, 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; - // parse the configured string into an instance of ApiKeyOptions and assign it to - // AdministrativeApiKey, 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)) + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + { + if (!adminApiKeyString.Contains(';')) { - if (!adminApiKeyString.Contains(';')) + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions - { - Key = adminApiKeyString, - }; - } + Key = adminApiKeyString, + }; + } - var tuples = adminApiKeyString.Split(';'); + var tuples = adminApiKeyString.Split(';'); - string key = null; - string role = null; - string cidr = null; + string key = null; + string role = null; + string cidr = null; - foreach (var tuple in tuples) + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) { - if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) - { - role = tuple.Split('=').LastOrDefault(); - } - else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) - { - cidr = tuple.Split('=').LastOrDefault(); - } - else - { - key = tuple; - } + role = tuple.Split('=').LastOrDefault(); } - - if (!string.IsNullOrEmpty(key)) + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions - { - Key = key, - Role = role, - Cidr = cidr, - }; + cidr = tuple.Split('=').LastOrDefault(); + } + else + { + key = tuple; } } - } - private SymmetricSecurityKey JwtSigningKey { get; } - private OptionsAtStartup OptionsAtStartup { get; } - private IOptionsMonitor OptionsMonitor { get; } - private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; - - public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) - { - var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - - // TODO: test me! - if (AdministrativeApiKey is not null) + if (!string.IsNullOrEmpty(key)) { - keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = role, + Cidr = cidr, + }; } + } + } - var record = keys.FirstOrDefault(k => k.Value.Key == key); - - if (record.Key == null) - { - throw new NotFoundException($"The provided API key does not match an existing key"); - } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; - if (!record.Value.Cidr.Split(',') - .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(callerIpAddress))) - { - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); - } + 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()); + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); } - 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); + Log.Warning("Unauthorized access attempt: unknown API key beginning with {FirstFourCharacters}", key.Substring(0, 4)); + throw new NotFoundException($"The provided API key does not match an existing key"); + } - var claims = new List() - { - 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))) + { + Log.Warning("Unauthorized access attempt: IP Address {IP} not included in CIDR(s) for API key {Name}: {CIDR}", callerIpAddress, record.Key, record.Value.Cidr); + throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); } + + return (record.Key, record.Value.Role.ToEnum()); + } + + 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() + { + 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; } } -- cgit v1.2.3 From 942eeb1eeb535dbaa99e3701ffea39cadcabc4db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:19:13 -0600 Subject: remove serilog --- src/slskd/Core/Security/SecurityService.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 9a87449e..8b3afa44 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -27,7 +27,6 @@ using System.Net; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using NetTools; -using Serilog; using slskd.Authentication; public class SecurityService @@ -91,7 +90,6 @@ public class SecurityService } } - private ILogger Log { get; } = Serilog.Log.ForContext(); private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } @@ -110,16 +108,14 @@ public class SecurityService if (record.Key == null) { - Log.Warning("Unauthorized access attempt: unknown API key beginning with {FirstFourCharacters}", key.Substring(0, 4)); - throw new NotFoundException($"The provided API key does not match an existing key"); + throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}"); } if (!record.Value.Cidr.Split(',') .Select(cidr => IPAddressRange.Parse(cidr)) .Any(range => range.Contains(callerIpAddress))) { - Log.Warning("Unauthorized access attempt: IP Address {IP} not included in CIDR(s) for API key {Name}: {CIDR}", callerIpAddress, record.Key, record.Value.Cidr); - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); + throw new OutOfRangeException($"IP Address {callerIpAddress} not included in CIDR(s) for API key {record.Key}: {record.Value.Cidr}"); } return (record.Key, record.Value.Role.ToEnum()); -- cgit v1.2.3 From 848262831fe6281d448afd3bdcf802bbc643fbd1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:19:52 -0600 Subject: remove ISecurityService interface, add logging to api key handler --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 9 ++++++--- src/slskd/Core/API/Controllers/SessionController.cs | 4 ++-- src/slskd/Program.cs | 4 ++-- 3 files changed, 10 insertions(+), 7 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 1aaa4a4f..fb209478 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -15,6 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace slskd.Authentication @@ -24,7 +25,7 @@ namespace slskd.Authentication using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; - using Microsoft.Extensions.Logging; + using Serilog; /// /// API key authentication. @@ -51,7 +52,7 @@ namespace slskd.Authentication /// A url encoder. public ApiKeyAuthenticationHandler( IOptionsMonitor apiKeyOptionsMonitor, - ISecurityService securityService, + SecurityService securityService, ILoggerFactory logger, UrlEncoder urlEncoder) : base(apiKeyOptionsMonitor, logger, urlEncoder) @@ -59,7 +60,8 @@ namespace slskd.Authentication Security = securityService; } - private ISecurityService Security { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private SecurityService Security { get; } /// /// Authenticates via API key. @@ -86,6 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { + Log.Warning(ex, "Unauthorized: {Message}", ex.Message); return AuthenticateResult.Fail(ex); } } 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 optionsSnapshot, OptionsAtStartup optionsAtStartup) { @@ -47,7 +47,7 @@ namespace slskd.Core.API private IOptionsSnapshot OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } - private ISecurityService Security { get; } + private SecurityService Security { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 288fa0e3..cb1961a2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -768,7 +768,7 @@ namespace slskd var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); services.AddSingleton(jwtSigningKey); - services.AddSingleton(); + services.AddSingleton(); if (!OptionsAtStartup.Web.Authentication.Disabled) { @@ -835,7 +835,7 @@ namespace slskd try { // check to see if the provided value is a valid API key - var service = services.BuildServiceProvider().GetRequiredService(); + var service = services.BuildServiceProvider().GetRequiredService(); var (name, role) = service.AuthenticateWithApiKey(token, callerIpAddress: context.HttpContext.Connection.RemoteIpAddress); // the API key is valid. create a new, short lived jwt for the key name and role -- cgit v1.2.3 From fc1aecbe54b0077d0fde20f9f8e6350312344692 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:36:09 -0600 Subject: tweak logging --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 2 +- src/slskd/Core/Security/SecurityService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index fb209478..e2733442 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -88,7 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { - Log.Warning(ex, "Unauthorized: {Message}", ex.Message); + Log.Warning("Unauthorized request from IP address {IP}: {Message}", Request.HttpContext.Connection.RemoteIpAddress, ex.Message); return AuthenticateResult.Fail(ex); } } diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 8b3afa44..e98dd5eb 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -115,7 +115,7 @@ public class SecurityService .Select(cidr => IPAddressRange.Parse(cidr)) .Any(range => range.Contains(callerIpAddress))) { - throw new OutOfRangeException($"IP Address {callerIpAddress} not included in CIDR(s) for API key {record.Key}: {record.Value.Cidr}"); + 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()); -- cgit v1.2.3 From 0b06e03e7091b486b99c74d71609fe1caa9e1093 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:00:33 -0600 Subject: default to administrator and all CIDRs --- src/slskd/Core/Security/SecurityService.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index e98dd5eb..254b3081 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -41,7 +41,7 @@ public class SecurityService OptionsMonitor = optionsMonitor; // parse the configured string into an instance of ApiKeyOptions and assign it to - // AdministrativeApiKey, if a string is provided. + // 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; @@ -50,7 +50,7 @@ public class SecurityService { if (!adminApiKeyString.Contains(';')) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { Key = adminApiKeyString, }; @@ -80,11 +80,11 @@ public class SecurityService if (!string.IsNullOrEmpty(key)) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { Key = key, - Role = role, - Cidr = cidr, + Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role, + Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr, }; } } @@ -93,15 +93,15 @@ public class SecurityService private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } - private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; + 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(); - if (AdministrativeApiKey is not null) + if (PrimaryApiKey is not null) { - keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + keys = keys.Prepend(new KeyValuePair(nameof(PrimaryApiKey), PrimaryApiKey)); } var record = keys.FirstOrDefault(k => k.Value.Key == key); -- cgit v1.2.3 From 9296ec4295a7d6a2371e19d38d6a32ef285eb373 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:00:53 -0600 Subject: administrative -> primary --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 43363654..20b53f6c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1946,7 +1946,7 @@ namespace slskd /// [Argument('k', "api-key")] [EnvironmentVariable("API_KEY")] - [Description("Administrative API key value")] + [Description("primary API key value")] [Secret] [RequiresRestart] public string ApiKey { get; init; } -- cgit v1.2.3