using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; internal sealed class CallerRegistry { private const string Header = "X-Plant-Finder-Key"; private static readonly Regex SubjectPattern = new(@"\A[a-zA-Z0-9_-]{1,64}\z", RegexOptions.CultureInvariant); private readonly Caller[] callers; private CallerRegistry(Caller[] callers) { this.callers = callers; } public static CallerRegistry Load(IConfiguration configuration) { var entries = configuration.GetSection("PlantFinder:Callers").GetChildren().ToArray(); if (entries.Length > 64) { throw new InvalidOperationException("Configure at most 64 fixture key entries."); } var knownHashes = new HashSet(StringComparer.OrdinalIgnoreCase); var callers = new List(); foreach (var entry in entries) { var subject = entry["Subject"]; var digest = entry["KeySha256"]; if (subject is null || !SubjectPattern.IsMatch(subject) || digest is null || digest.Length != 64 || !digest.All(Uri.IsHexDigit) || !knownHashes.Add(digest)) { throw new InvalidOperationException("Each fixture key entry needs a subject and a unique SHA-256 digest."); } callers.Add(new Caller(subject, Convert.FromHexString(digest))); } return new CallerRegistry(callers.ToArray()); } public string? Authenticate(IHeaderDictionary headers) { var values = headers[Header]; var key = values.Count == 1 ? values[0] : null; if (key is null || key.Length != 64 || !key.All(IsLowercaseHex)) { return null; } var digest = SHA256.HashData(Encoding.ASCII.GetBytes(key)); string? subject = null; foreach (var caller in callers) { if (CryptographicOperations.FixedTimeEquals(digest, caller.Digest)) { subject = caller.Subject; } } return subject; } private static bool IsLowercaseHex(char character) => character is >= '0' and <= '9' or >= 'a' and <= 'f'; private sealed record Caller(string Subject, byte[] Digest); }