diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-12-13 16:59:51 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-12-13 16:59:51 -0600 |
| commit | 1d27718843b0d62afa8a52847eadcbdbcbf44b98 (patch) | |
| tree | bc6d2bd7fd959d0740a68b5b35a3baf8f1de31c0 /src/slskd/Core/Security | |
| parent | 6dbedb038a152a22dd9ee4b04a41a8b3ffde5d1f (diff) | |
| parent | 54584b8edd08f704427355d59323163086102207 (diff) | |
| download | slskd-1d27718843b0d62afa8a52847eadcbdbcbf44b98.tar.gz | |
Merge branch 'master' into copilot/add-sort-directories-files
Diffstat (limited to 'src/slskd/Core/Security')
| -rw-r--r-- | src/slskd/Core/Security/SecurityService.cs | 171 |
1 files changed, 110 insertions, 61 deletions
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; } } |
