From 30b2b42ccc9a51be4aee4c74b9184f5da1509932 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Oct 2022 15:24:50 -0500 Subject: add options for api keys --- src/slskd/Core/Options.cs | 61 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 44cc4c71..4c146d32 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -28,6 +28,7 @@ namespace slskd using System.Text.Json.Serialization; using System.Text.RegularExpressions; using FluentFTP; + using NetTools; using slskd.Configuration; using slskd.Validation; using Soulseek.Diagnostics; @@ -126,6 +127,16 @@ namespace slskd [YamlIgnore] public bool GenerateCertificate { get; init; } = false; + /// + /// Gets a value indicating whether to generate a random API key. + /// + [Argument('k', "generate-api-key")] + [Description("generate random API key for HTTP/S")] + [Obsolete("USed only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool GenerateApiKey { get; init; } = false; + /// /// Gets a value indicating whether the application should run in debug mode. /// @@ -1214,6 +1225,12 @@ namespace slskd [RequiresRestart] public JwtOptions Jwt { get; init; } = new JwtOptions(); + /// + /// Gets API keys. + /// + [Validate] + public Dictionary ApiKeys { get; init; } = new Dictionary(); + /// /// JWT options. /// @@ -1240,6 +1257,50 @@ namespace slskd [RequiresRestart] public int Ttl { get; init; } = 604800000; } + + /// + /// API key options. + /// + public class ApiKeyOptions : IValidatableObject + { + /// + /// Gets the API key value. + /// + [Description("API key value")] + [StringLength(255, MinimumLength = 16)] + [Secret] + public string Key { get; init; } + + /// + /// Gets the comma separated list of CIDRs that are authorized to use the key. + /// + [Description("An optional comma separated list of CIDRs that are authorized to use the key")] + public string Cidr { get; init; } = "0.0.0.0/0,::/0"; + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + foreach (var cidr in Cidr.Split(',')) + { + try + { + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}")); + } + } + + return results; + } + } } /// -- cgit v1.2.3