using System; using System.Collections.Concurrent; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace CarpaNet.OAuth; /// /// Discovers and caches OAuth authorization server metadata. /// public sealed class AuthorizationServerDiscovery : IDisposable { private readonly HttpClient _httpClient; private readonly bool _ownsHttpClient; private readonly TimeSpan _cacheTtl; private readonly ConcurrentDictionary _cache = new(); private readonly ILogger _logger; private bool _disposed; private sealed class CachedMetadata { public OAuthAuthorizationServerMetadata Metadata { get; set; } = null!; public DateTimeOffset ExpiresAt { get; set; } } /// /// Creates a new authorization server discovery client. /// /// Cache time-to-live (default: 60 seconds). /// Optional logger factory for diagnostic logging. public AuthorizationServerDiscovery(TimeSpan? cacheTtl = null, ILoggerFactory? loggerFactory = null) : this(new HttpClient(), ownsHttpClient: true, cacheTtl, loggerFactory) { } /// /// Creates a new authorization server discovery client with a custom HttpClient. /// /// The HttpClient to use. /// Cache time-to-live (default: 60 seconds). /// Optional logger factory for diagnostic logging. public AuthorizationServerDiscovery(HttpClient httpClient, TimeSpan? cacheTtl = null, ILoggerFactory? loggerFactory = null) : this(httpClient, ownsHttpClient: false, cacheTtl, loggerFactory) { } private AuthorizationServerDiscovery(HttpClient httpClient, bool ownsHttpClient, TimeSpan? cacheTtl, ILoggerFactory? loggerFactory) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _ownsHttpClient = ownsHttpClient; _cacheTtl = cacheTtl ?? TimeSpan.FromSeconds(60); _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger(); } /// /// Gets the well-known URL for OAuth authorization server metadata. /// /// The issuer URL. /// The well-known metadata URL. public static string GetWellKnownUrl(string issuer) { var uri = new Uri(issuer.TrimEnd('/')); return $"{uri.Scheme}://{uri.Authority}/.well-known/oauth-authorization-server"; } /// /// Gets the well-known URL for OAuth protected resource metadata (PDS). /// /// The resource server URL. /// The well-known metadata URL. public static string GetProtectedResourceWellKnownUrl(string resourceUrl) { var uri = new Uri(resourceUrl.TrimEnd('/')); return $"{uri.Scheme}://{uri.Authority}/.well-known/oauth-protected-resource"; } /// /// Fetches authorization server metadata from the issuer. /// /// The authorization server issuer URL. /// Cancellation token. /// The authorization server metadata. public async Task GetMetadataAsync( string issuer, CancellationToken cancellationToken = default) { ThrowIfDisposed(); // Check cache if (_cache.TryGetValue(issuer, out var cached) && cached.ExpiresAt > DateTimeOffset.UtcNow) { _logger.LogTrace("Authorization server metadata cache hit for {Issuer}", issuer); return cached.Metadata; } // Fetch metadata var wellKnownUrl = GetWellKnownUrl(issuer); _logger.LogDebug("Fetching authorization server metadata from {Url}", wellKnownUrl); var response = await _httpClient.GetAsync(wellKnownUrl, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { _logger.LogWarning("Failed to fetch server metadata from {Url}: HTTP {StatusCode}", wellKnownUrl, (int)response.StatusCode); throw new OAuthException( "metadata_fetch_failed", $"Failed to fetch authorization server metadata from {wellKnownUrl}: {response.StatusCode}"); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var metadata = JsonSerializer.Deserialize(content, OAuthJsonContext.Default.OAuthAuthorizationServerMetadata); if (metadata == null) { throw new OAuthException( "metadata_parse_failed", "Failed to parse authorization server metadata."); } // Validate issuer matches (mix-up attack prevention) if (!string.Equals(metadata.Issuer, issuer, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Issuer mismatch: expected {Expected}, got {Actual}", issuer, metadata.Issuer); throw new OAuthException( "issuer_mismatch", $"Authorization server metadata issuer '{metadata.Issuer}' does not match expected '{issuer}'."); } // Cache the result _cache[issuer] = new CachedMetadata { Metadata = metadata, ExpiresAt = DateTimeOffset.UtcNow + _cacheTtl }; return metadata; } /// /// Fetches protected resource metadata from a PDS to discover its authorization server. /// /// The PDS URL. /// Cancellation token. /// The authorization server issuer URL. public async Task DiscoverAuthorizationServerAsync( string resourceUrl, CancellationToken cancellationToken = default) { ThrowIfDisposed(); _logger.LogDebug("Discovering authorization server for {ResourceUrl}", resourceUrl); var wellKnownUrl = GetProtectedResourceWellKnownUrl(resourceUrl); var response = await _httpClient.GetAsync(wellKnownUrl, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { throw new OAuthException( "resource_metadata_fetch_failed", $"Failed to fetch protected resource metadata from {wellKnownUrl}: {response.StatusCode}"); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); using var doc = JsonDocument.Parse(content); if (!doc.RootElement.TryGetProperty("authorization_servers", out var servers) || servers.GetArrayLength() == 0) { throw new OAuthException( "no_authorization_server", "Protected resource does not specify any authorization servers."); } // Use the first authorization server return servers[0].GetString() ?? throw new OAuthException("invalid_authorization_server", "Authorization server URL is null."); } /// /// Clears the metadata cache. /// public void ClearCache() { _cache.Clear(); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(AuthorizationServerDiscovery)); } } /// public void Dispose() { if (_disposed) { return; } _disposed = true; if (_ownsHttpClient) { _httpClient.Dispose(); } } }