aboutsummaryrefslogtreecommitdiffstats
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
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
-rw-r--r--docs/config.md17
-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
6 files changed, 216 insertions, 69 deletions
diff --git a/docs/config.md b/docs/config.md
index 40f186f6..3efe2e8a 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -864,10 +864,16 @@ web:
Authentication for the web UI (and underlying API) is enabled by default, and the default username and password are both `slskd`. Changing both the username and password during the initial configuration is highly recommended.
+### JWT (Json Web Token)
+
+JWTs are used to authenticate the UI, and are generated by making an API call and supplying a username and password.
+
By default, a random JWT secret key is generated at each start. It is convenient and secure, but restarting the application will invalidate any issued JWTs, causing users to sign in again. To avoid this, supply a custom secret at least 16 characters in length. Note that the secret can be used to generate valid JWTs for the application, so keep this value secret.
The JWT TTL option determines how long issued JWTs are valid, defaulting to 7 days.
+### API Keys
+
API keys can be configured to allow for secure communication without requiring the caller to obtain a JWT by signing in with a username and password. Each key must be given a name and a key with a length between 16 and 255 characters (inclusive). Callers may then supply one of the configured keys in the `X-API-Key` header when making web requests. Remember that API keys are secrets, so keep them safe.
You can generate a random, 32 bit API key by starting the application with `--generate-secret` at the command line.
@@ -876,6 +882,16 @@ An optional comma separated list of [CIDRs](https://en.wikipedia.org/wiki/Classl
A common use case for CIDR filtering might be to restrict API access to clients within your home network. Assuming your network uses the common `192.168.1.x` addressing, you could specify a `cidr` of `192.168.1.0/24`, which would apply to any IP between `192.168.1.1` and `192.168.1.254`, inclusive.
+An optional 'primary' API key can be configured by passiing it via `-k` or `--api-key` on the command line, or by setting the `SLSKD_API_KEY` environment variable. As with other API keys, a role and list of CIDRs can be supplied, but because the command line and environment variables are limited to a simple string, the role and CIDRs must be passed via tuples separated by semicolons:
+
+```
+role=ReadOnly;cidr=0.0.0.0/0,::/0;<16 to 255 character string>
+```
+
+By default, the role associated with the 'primary' API key is `Administrator` (other API keys default to `ReadOnly`) and list of CIDRs is `0.0.0.0/0,::0` (same as other API keys).
+
+#### Cautions
+
Note that CIDR filtering may not work as expected behind a reverse proxy, ingress controller, or load balancer, because the remote IP address will be that of the device that's handling ingress. This application doesn't support the `X-Forwarded-For` header (or anything like it) because a bad actor can easily fake it. If you wish to use CIDR filtering in this scenario, you'll need to do it at the point of ingress to your network.
Please also note that using API key authentication without HTTPS is **NOT RECOMMENDED**. API keys are sent in HTTP headers (and in the case of SignalR, in query parameters) and will be easily accessible to anyone eavesdropping on the network. This is a risk with JWTs as well, but JWTs expire and API keys don't. If you choose to use API keys over plain HTTP, seriously consider using CIDR filtering.
@@ -885,6 +901,7 @@ Please also note that using API key authentication without HTTPS is **NOT RECOMM
| `-X\|--no-auth` | `SLSKD_NO_AUTH` | Determines whether authentication is to be disabled |
| `-u\|--username` | `SLSKD_USERNAME` | The username for the web UI |
| `-p\|--password` | `SLSKD_PASSWORD` | The password for the web UI |
+| `-k\|--api-key` | `SLSKD_API_KEY` | The primary API key |
| `--jwt-key` | `SLSKD_JWT_KEY` | The secret key used to sign JWTs |
| `--jwt-ttl` | `SLSKD_JWT_TTL` | The TTL (duration) of JWTs, in milliseconds |
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