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') 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