using System.Collections.Concurrent; using System.Net; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.Extensions.Configuration; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed class MdpApiPullClient(MdpApiPullEgress egress, IConfiguration configuration) { private static readonly Regex HeaderName = new(@"\A[A-Za-z][A-Za-z0-9-]{0,63}\z"); private static readonly Regex LinkValue = new(@"<([^<>]+)>\s*((?:\s*;[^<,]+)*)", RegexOptions.CultureInvariant); private static readonly Regex NextRelation = new("(?:^|;)\\s*rel\\s*=\\s*(?:\"next\"|next)(?:\\s*;|\\s*$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private readonly ConcurrentDictionary tokens = new(); internal async Task FetchAsync(long tenant, long source, MdpApiPullPlan plan, MdpApiPullPosition position, CancellationToken cancellationToken, Func reserve) { var endpoint = plan.RequestUri(position); if (!MdpApiPullEgress.SameOrigin(plan.Endpoint, endpoint)) throw new MdpApiPullException("PULL_LINK_FORBIDDEN"); if (plan.Auth == "oauth2") egress.Target(tenant, source, new Uri(plan.TokenUrl!)); egress.Target(tenant, source, endpoint); if (plan.CredentialRef is { } reference && !(configuration.GetSection($"MdpApiPull:Credentials:{tenant}:{source}").Get() ?? []).Contains(reference, StringComparer.Ordinal)) throw new MdpApiPullException("PULL_CREDENTIAL_FORBIDDEN"); using var secret = ReadCredential(plan.CredentialRef); var access = plan.Auth == "oauth2" ? await TokenAsync(tenant, source, plan, secret, null, cancellationToken, reserve) : null; var response = await ReadAsync(tenant, source, endpoint, plan.Method, CreateRequest, MdpIngestProtocol.Limits.MaxBodyBytes, cancellationToken, reserve); if (response.Status == HttpStatusCode.Unauthorized && access is not null) { access = await TokenAsync(tenant, source, plan, secret, access, cancellationToken, reserve); response = await ReadAsync(tenant, source, endpoint, plan.Method, CreateRequest, MdpIngestProtocol.Limits.MaxBodyBytes, cancellationToken, reserve); } RequireSuccess(response); return response; HttpRequestMessage CreateRequest(Uri uri) { var request = new HttpRequestMessage(new HttpMethod(plan.Method), uri); if (plan.Method == "POST") request.Content = new StringContent(plan.PostJson!, Encoding.UTF8, "application/json"); if (access is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", access); else if (plan.Auth == "basic") SetBasic(request, Secret(secret, "user"), Secret(secret, "password")); else if (plan.Auth == "apiKey") { var header = Secret(secret, "header"); if (!HeaderName.IsMatch(header) || header.ToUpperInvariant() is "HOST" or "AUTHORIZATION" or "COOKIE" or "CONTENT-LENGTH" or "CONNECTION" or "TRANSFER-ENCODING" or "PROXY-AUTHORIZATION" || header.StartsWith("X-Forwarded-", StringComparison.OrdinalIgnoreCase)) throw new MdpApiPullException("PULL_CREDENTIAL_INVALID"); if (!request.Headers.TryAddWithoutValidation(header, Secret(secret, "value"))) throw new MdpApiPullException("PULL_CREDENTIAL_INVALID"); } return request; } } private async Task TokenAsync(long tenant, long source, MdpApiPullPlan plan, JsonDocument? secret, string? rejectedToken, CancellationToken cancellationToken, Func reserve) { var key = new TokenScope(tenant, source, plan.CredentialRef!, plan.TokenUrl!, plan.TokenScope); var item = tokens.GetOrAdd(key, _ => new TokenCache()); await item.Gate.WaitAsync(cancellationToken); try { if (item.Value is not null && item.ValidUntil > DateTimeOffset.UtcNow && item.Value != rejectedToken) return item.Value; var form = new Dictionary { ["grant_type"] = "client_credentials" }; if (!string.IsNullOrEmpty(plan.TokenScope)) form.Add("scope", plan.TokenScope); var result = await ReadAsync(tenant, source, new Uri(plan.TokenUrl!), "POST", uri => { var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = new FormUrlEncodedContent(form) }; SetBasic(request, WebUtility.UrlEncode(Secret(secret, "clientId")), WebUtility.UrlEncode(Secret(secret, "clientSecret"))); return request; }, 16384, cancellationToken, reserve); RequireSuccess(result); if (result.LinkDiagnostic is { } diagnostic) throw new MdpApiPullException(diagnostic); using var doc = JsonDocument.Parse(result.Body); var token = MdpApiPullPlan.Value(doc.RootElement, "access_token"); var type = MdpApiPullPlan.Value(doc.RootElement, "token_type"); var duration = MdpApiPullPlan.Value(doc.RootElement, "expires_in"); if (token.ValueKind != JsonValueKind.String || token.GetString() is not { Length: > 0 and <= 8192 } text || text.Any(ch => ch is < '!' or > '~') || type.ValueKind != JsonValueKind.String || !string.Equals(type.GetString(), "Bearer", StringComparison.OrdinalIgnoreCase) || duration.ValueKind != JsonValueKind.Number || !duration.TryGetInt32(out var seconds) || seconds is <= 0 or > 86400) throw new MdpApiPullException("PULL_TOKEN_INVALID"); item.Value = text; item.ValidUntil = DateTimeOffset.UtcNow.AddSeconds(seconds - Math.Min(30, seconds / 2)); return text; } finally { item.Gate.Release(); } } private async Task ReadAsync(long tenant, long source, Uri initial, string method, Func create, int limit, CancellationToken cancellationToken, Func reserve) { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromSeconds(25)); var current = initial; var redirects = new HashSet(); try { for (var hop = 0; hop <= 3; hop++) { if (!redirects.Add(current)) throw new MdpApiPullException("PULL_REDIRECT_FORBIDDEN"); using var client = egress.Open(tenant, source, current); using var request = create(current); request.Headers.Accept.ParseAdd("application/json"); request.Headers.AcceptEncoding.ParseAdd("identity"); await reserve(deadline.Token); using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); var status = (int)response.StatusCode; if (status is 301 or 302 or 303 or 307 or 308) { if (method == "POST" && status is not (307 or 308) || response.Headers.Location is null || !Uri.TryCreate(current, response.Headers.Location, out var next) || !MdpApiPullEgress.SameOrigin(initial, next)) throw new MdpApiPullException("PULL_REDIRECT_FORBIDDEN"); current = next; continue; } var retryAfter = response.Headers.RetryAfter; var delay = retryAfter?.Delta ?? retryAfter?.Date - DateTimeOffset.UtcNow; if (!response.IsSuccessStatusCode) return new MdpApiPullResponse(response.StatusCode, current, [], null, delay); if (response.Content.Headers.ContentEncoding.Any(value => value != "identity")) throw new MdpApiPullException("PULL_CONTENT_ENCODING_UNSUPPORTED"); var links = response.Headers.TryGetValues("Link", out var all) ? all : []; string? nextLink = null; string? linkDiagnostic = null; try { nextLink = ParseNext(links); } catch (MdpApiPullException error) { linkDiagnostic = error.Code; } if (nextLink is { Length: > 2048 } || current.AbsoluteUri.Length > 2048) { nextLink = null; linkDiagnostic = "PULL_LINK_INVALID"; } using var stream = await response.Content.ReadAsStreamAsync(deadline.Token); using var buffer = new MemoryStream(); var block = new byte[8192]; while (true) { var count = await stream.ReadAsync(block, deadline.Token); if (count == 0) break; if (buffer.Length + count > limit) throw new MdpApiPullException("PULL_BODY_TOO_LARGE"); buffer.Write(block, 0, count); } return new MdpApiPullResponse(response.StatusCode, current, buffer.ToArray(), nextLink, null, linkDiagnostic); } } catch (HttpRequestException ex) when (ex.InnerException is MdpApiPullException policy) { throw policy; } catch (HttpRequestException) { throw new MdpApiPullException("PULL_TEMPORARY", TimeSpan.FromSeconds(1)); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { throw new MdpApiPullException("PULL_TIMEOUT", TimeSpan.FromSeconds(1)); } throw new MdpApiPullException("PULL_REDIRECT_FORBIDDEN"); } internal static string? ParseNext(IEnumerable values) { var joined = string.Join(",", values); if (joined.Length > 8192) throw new MdpApiPullException("PULL_LINK_INVALID"); var next = LinkValue.Matches(joined).Where(value => NextRelation.IsMatch(value.Groups[2].Value)) .Select(value => value.Groups[1].Value).Take(2).ToArray(); return next.Length switch { 0 => null, 1 => next[0], _ => throw new MdpApiPullException("PULL_LINK_INVALID") }; } private static void RequireSuccess(MdpApiPullResponse response) { var status = (int)response.Status; if (status is >= 200 and < 300) return; if (status == 429) throw new MdpApiPullException("PULL_SOURCE_RATE_LIMITED", response.RetryAfter ?? TimeSpan.FromSeconds(1)); if (status >= 500 || status == 408) throw new MdpApiPullException("PULL_TEMPORARY", response.RetryAfter ?? TimeSpan.FromSeconds(1)); throw new MdpApiPullException(status is 401 or 403 ? "PULL_SOURCE_AUTH_DENIED" : "PULL_SOURCE_REQUEST_REJECTED"); } private static JsonDocument? ReadCredential(string? reference) { if (reference is null) return null; var value = Environment.GetEnvironmentVariable(reference); if (string.IsNullOrEmpty(value) || value.Length > 8192) throw new MdpApiPullException("PULL_CREDENTIAL_UNAVAILABLE"); try { return JsonDocument.Parse(value); } catch (JsonException) { throw new MdpApiPullException("PULL_CREDENTIAL_INVALID"); } } private static string Secret(JsonDocument? doc, string name) => (doc is null ? default : MdpApiPullPlan.Value(doc.RootElement, name)) is { ValueKind: JsonValueKind.String } value && value.GetString() is { Length: > 0 and <= 4096 } text && !text.Any(char.IsControl) ? text : throw new MdpApiPullException("PULL_CREDENTIAL_INVALID"); private static void SetBasic(HttpRequestMessage request, string user, string password) { if (user.Contains(':')) throw new MdpApiPullException("PULL_CREDENTIAL_INVALID"); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password))); } private sealed record TokenScope(long Tenant, long Source, string Reference, string Endpoint, string? Scope); private sealed class TokenCache { public SemaphoreSlim Gate { get; } = new(1, 1); public string? Value { get; set; } public DateTimeOffset ValidUntil { get; set; } } } internal sealed record MdpApiPullResponse(HttpStatusCode Status, Uri Effective, byte[] Body, string? NextLink, TimeSpan? RetryAfter, string? LinkDiagnostic = null);