diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-12-13 13:02:35 -0600 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-12-13 13:02:35 -0600 |
| commit | 1c2983723e4c683f101bb9988844a2812aab749d (patch) | |
| tree | c7bed5aecf7ca90e9be0fa6050e230a3de6abc88 /src | |
| parent | 8fadf7bdd6b253895a273fe6ffc8bd4943f07ee9 (diff) | |
| download | slskd-1c2983723e4c683f101bb9988844a2812aab749d.tar.gz | |
add logger, use file scoped namespace
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Core/Security/SecurityService.cs | 218 |
1 files changed, 107 insertions, 111 deletions
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<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) - { - 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<Options> 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<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(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<SecurityService>(); + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor<Options> 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<Role>()); + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(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<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))) + { + 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<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; } } |
