aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-12-13 16:46:28 -0600
committerGitHub <noreply@github.com>2025-12-13 16:46:28 -0600
commit54584b8edd08f704427355d59323163086102207 (patch)
treefc3e4fb320af056b25bd8d2d9c3fbd48cdd454f8 /src
parent999b903244233747e1a190fb88af372ea2c5f2ab (diff)
parent1e0eb94a16fd6b8a3204bc14e11c0c5d47617d0c (diff)
downloadslskd-54584b8edd08f704427355d59323163086102207.tar.gz
Merge pull request #1587 from slskd/api-key
Add the ability to configure an API key via environment variables and command line
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Authentication/ApiKeyAuthentication.cs9
-rw-r--r--src/slskd/Core/API/Controllers/SessionController.cs4
-rw-r--r--src/slskd/Core/Options.cs80
-rw-r--r--src/slskd/Core/Security/SecurityService.cs171
-rw-r--r--src/slskd/Program.cs4
5 files changed, 199 insertions, 69 deletions
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
index 1aaa4a4f..e2733442 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/.
// </copyright>
+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;
/// <summary>
/// API key authentication.
@@ -51,7 +52,7 @@ namespace slskd.Authentication
/// <param name="urlEncoder">A url encoder.</param>
public ApiKeyAuthenticationHandler(
IOptionsMonitor<ApiKeyAuthenticationOptions> 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<ApiKeyAuthenticationHandler>();
+ private SecurityService Security { get; }
/// <summary>
/// Authenticates via API key.
@@ -86,6 +88,7 @@ namespace slskd.Authentication
}
catch (Exception ex)
{
+ 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/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/Options.cs b/src/slskd/Core/Options.cs
index cca7e01d..20b53f6c 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -1903,7 +1903,7 @@ namespace slskd
/// <summary>
/// Authentication options.
/// </summary>
- public class WebAuthenticationOptions
+ public class WebAuthenticationOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether authentication should be disabled.
@@ -1941,11 +1941,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>
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;
}
}
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<ISecurityService, SecurityService>();
+ services.AddSingleton<SecurityService>();
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<ISecurityService>();
+ var service = services.BuildServiceProvider().GetRequiredService<SecurityService>();
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