MdpApiPullClient.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using System.Collections.Concurrent;
  2. using System.Net;
  3. using System.Net.Http.Headers;
  4. using System.Text;
  5. using System.Text.Json;
  6. using System.Text.RegularExpressions;
  7. using Microsoft.Extensions.Configuration;
  8. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  9. public sealed class MdpApiPullClient(MdpApiPullEgress egress, IConfiguration configuration)
  10. {
  11. private static readonly Regex HeaderName = new(@"\A[A-Za-z][A-Za-z0-9-]{0,63}\z");
  12. private static readonly Regex LinkValue = new(@"<([^<>]+)>\s*((?:\s*;[^<,]+)*)", RegexOptions.CultureInvariant);
  13. private static readonly Regex NextRelation = new("(?:^|;)\\s*rel\\s*=\\s*(?:\"next\"|next)(?:\\s*;|\\s*$)",
  14. RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
  15. private readonly ConcurrentDictionary<TokenScope, TokenCache> tokens = new();
  16. internal async Task<MdpApiPullResponse> FetchAsync(long tenant, long source, MdpApiPullPlan plan,
  17. MdpApiPullPosition position, CancellationToken cancellationToken, Func<CancellationToken, Task> reserve)
  18. {
  19. var endpoint = plan.RequestUri(position);
  20. if (!MdpApiPullEgress.SameOrigin(plan.Endpoint, endpoint))
  21. throw new MdpApiPullException("PULL_LINK_FORBIDDEN");
  22. if (plan.Auth == "oauth2") egress.Target(tenant, source, new Uri(plan.TokenUrl!));
  23. egress.Target(tenant, source, endpoint);
  24. if (plan.CredentialRef is { } reference
  25. && !(configuration.GetSection($"MdpApiPull:Credentials:{tenant}:{source}").Get<string[]>() ?? []).Contains(reference, StringComparer.Ordinal))
  26. throw new MdpApiPullException("PULL_CREDENTIAL_FORBIDDEN");
  27. using var secret = ReadCredential(plan.CredentialRef);
  28. var access = plan.Auth == "oauth2" ? await TokenAsync(tenant, source, plan, secret, null, cancellationToken, reserve) : null;
  29. var response = await ReadAsync(tenant, source, endpoint, plan.Method, CreateRequest, MdpIngestProtocol.Limits.MaxBodyBytes, cancellationToken, reserve);
  30. if (response.Status == HttpStatusCode.Unauthorized && access is not null)
  31. {
  32. access = await TokenAsync(tenant, source, plan, secret, access, cancellationToken, reserve);
  33. response = await ReadAsync(tenant, source, endpoint, plan.Method, CreateRequest, MdpIngestProtocol.Limits.MaxBodyBytes, cancellationToken, reserve);
  34. }
  35. RequireSuccess(response);
  36. return response;
  37. HttpRequestMessage CreateRequest(Uri uri)
  38. {
  39. var request = new HttpRequestMessage(new HttpMethod(plan.Method), uri);
  40. if (plan.Method == "POST") request.Content = new StringContent(plan.PostJson!, Encoding.UTF8, "application/json");
  41. if (access is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", access);
  42. else if (plan.Auth == "basic") SetBasic(request, Secret(secret, "user"), Secret(secret, "password"));
  43. else if (plan.Auth == "apiKey")
  44. {
  45. var header = Secret(secret, "header");
  46. if (!HeaderName.IsMatch(header) || header.ToUpperInvariant() is "HOST" or "AUTHORIZATION" or "COOKIE"
  47. or "CONTENT-LENGTH" or "CONNECTION" or "TRANSFER-ENCODING" or "PROXY-AUTHORIZATION"
  48. || header.StartsWith("X-Forwarded-", StringComparison.OrdinalIgnoreCase))
  49. throw new MdpApiPullException("PULL_CREDENTIAL_INVALID");
  50. if (!request.Headers.TryAddWithoutValidation(header, Secret(secret, "value")))
  51. throw new MdpApiPullException("PULL_CREDENTIAL_INVALID");
  52. }
  53. return request;
  54. }
  55. }
  56. private async Task<string> TokenAsync(long tenant, long source, MdpApiPullPlan plan, JsonDocument? secret,
  57. string? rejectedToken, CancellationToken cancellationToken, Func<CancellationToken, Task> reserve)
  58. {
  59. var key = new TokenScope(tenant, source, plan.CredentialRef!, plan.TokenUrl!, plan.TokenScope);
  60. var item = tokens.GetOrAdd(key, _ => new TokenCache());
  61. await item.Gate.WaitAsync(cancellationToken);
  62. try
  63. {
  64. if (item.Value is not null && item.ValidUntil > DateTimeOffset.UtcNow && item.Value != rejectedToken)
  65. return item.Value;
  66. var form = new Dictionary<string, string> { ["grant_type"] = "client_credentials" };
  67. if (!string.IsNullOrEmpty(plan.TokenScope)) form.Add("scope", plan.TokenScope);
  68. var result = await ReadAsync(tenant, source, new Uri(plan.TokenUrl!), "POST", uri =>
  69. {
  70. var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = new FormUrlEncodedContent(form) };
  71. SetBasic(request, WebUtility.UrlEncode(Secret(secret, "clientId")), WebUtility.UrlEncode(Secret(secret, "clientSecret")));
  72. return request;
  73. }, 16384, cancellationToken, reserve);
  74. RequireSuccess(result);
  75. if (result.LinkDiagnostic is { } diagnostic) throw new MdpApiPullException(diagnostic);
  76. using var doc = JsonDocument.Parse(result.Body);
  77. var token = MdpApiPullPlan.Value(doc.RootElement, "access_token");
  78. var type = MdpApiPullPlan.Value(doc.RootElement, "token_type");
  79. var duration = MdpApiPullPlan.Value(doc.RootElement, "expires_in");
  80. if (token.ValueKind != JsonValueKind.String || token.GetString() is not { Length: > 0 and <= 8192 } text
  81. || text.Any(ch => ch is < '!' or > '~') || type.ValueKind != JsonValueKind.String
  82. || !string.Equals(type.GetString(), "Bearer", StringComparison.OrdinalIgnoreCase)
  83. || duration.ValueKind != JsonValueKind.Number || !duration.TryGetInt32(out var seconds)
  84. || seconds is <= 0 or > 86400)
  85. throw new MdpApiPullException("PULL_TOKEN_INVALID");
  86. item.Value = text;
  87. item.ValidUntil = DateTimeOffset.UtcNow.AddSeconds(seconds - Math.Min(30, seconds / 2));
  88. return text;
  89. }
  90. finally { item.Gate.Release(); }
  91. }
  92. private async Task<MdpApiPullResponse> ReadAsync(long tenant, long source, Uri initial, string method,
  93. Func<Uri, HttpRequestMessage> create, int limit, CancellationToken cancellationToken, Func<CancellationToken, Task> reserve)
  94. {
  95. using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  96. deadline.CancelAfter(TimeSpan.FromSeconds(25));
  97. var current = initial;
  98. var redirects = new HashSet<Uri>();
  99. try
  100. {
  101. for (var hop = 0; hop <= 3; hop++)
  102. {
  103. if (!redirects.Add(current))
  104. throw new MdpApiPullException("PULL_REDIRECT_FORBIDDEN");
  105. using var client = egress.Open(tenant, source, current);
  106. using var request = create(current);
  107. request.Headers.Accept.ParseAdd("application/json");
  108. request.Headers.AcceptEncoding.ParseAdd("identity");
  109. await reserve(deadline.Token);
  110. using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token);
  111. var status = (int)response.StatusCode;
  112. if (status is 301 or 302 or 303 or 307 or 308)
  113. {
  114. if (method == "POST" && status is not (307 or 308) || response.Headers.Location is null
  115. || !Uri.TryCreate(current, response.Headers.Location, out var next)
  116. || !MdpApiPullEgress.SameOrigin(initial, next))
  117. throw new MdpApiPullException("PULL_REDIRECT_FORBIDDEN");
  118. current = next;
  119. continue;
  120. }
  121. var retryAfter = response.Headers.RetryAfter;
  122. var delay = retryAfter?.Delta ?? retryAfter?.Date - DateTimeOffset.UtcNow;
  123. if (!response.IsSuccessStatusCode)
  124. return new MdpApiPullResponse(response.StatusCode, current, [], null, delay);
  125. if (response.Content.Headers.ContentEncoding.Any(value => value != "identity"))
  126. throw new MdpApiPullException("PULL_CONTENT_ENCODING_UNSUPPORTED");
  127. var links = response.Headers.TryGetValues("Link", out var all) ? all : [];
  128. string? nextLink = null;
  129. string? linkDiagnostic = null;
  130. try { nextLink = ParseNext(links); }
  131. catch (MdpApiPullException error) { linkDiagnostic = error.Code; }
  132. if (nextLink is { Length: > 2048 } || current.AbsoluteUri.Length > 2048)
  133. {
  134. nextLink = null;
  135. linkDiagnostic = "PULL_LINK_INVALID";
  136. }
  137. using var stream = await response.Content.ReadAsStreamAsync(deadline.Token);
  138. using var buffer = new MemoryStream();
  139. var block = new byte[8192];
  140. while (true)
  141. {
  142. var count = await stream.ReadAsync(block, deadline.Token);
  143. if (count == 0) break;
  144. if (buffer.Length + count > limit)
  145. throw new MdpApiPullException("PULL_BODY_TOO_LARGE");
  146. buffer.Write(block, 0, count);
  147. }
  148. return new MdpApiPullResponse(response.StatusCode, current, buffer.ToArray(), nextLink, null, linkDiagnostic);
  149. }
  150. }
  151. catch (HttpRequestException ex) when (ex.InnerException is MdpApiPullException policy)
  152. {
  153. throw policy;
  154. }
  155. catch (HttpRequestException)
  156. {
  157. throw new MdpApiPullException("PULL_TEMPORARY", TimeSpan.FromSeconds(1));
  158. }
  159. catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
  160. {
  161. throw new MdpApiPullException("PULL_TIMEOUT", TimeSpan.FromSeconds(1));
  162. }
  163. throw new MdpApiPullException("PULL_REDIRECT_FORBIDDEN");
  164. }
  165. internal static string? ParseNext(IEnumerable<string> values)
  166. {
  167. var joined = string.Join(",", values);
  168. if (joined.Length > 8192) throw new MdpApiPullException("PULL_LINK_INVALID");
  169. var next = LinkValue.Matches(joined).Where(value => NextRelation.IsMatch(value.Groups[2].Value))
  170. .Select(value => value.Groups[1].Value).Take(2).ToArray();
  171. return next.Length switch { 0 => null, 1 => next[0], _ => throw new MdpApiPullException("PULL_LINK_INVALID") };
  172. }
  173. private static void RequireSuccess(MdpApiPullResponse response)
  174. {
  175. var status = (int)response.Status;
  176. if (status is >= 200 and < 300) return;
  177. if (status == 429)
  178. throw new MdpApiPullException("PULL_SOURCE_RATE_LIMITED", response.RetryAfter ?? TimeSpan.FromSeconds(1));
  179. if (status >= 500 || status == 408)
  180. throw new MdpApiPullException("PULL_TEMPORARY", response.RetryAfter ?? TimeSpan.FromSeconds(1));
  181. throw new MdpApiPullException(status is 401 or 403 ? "PULL_SOURCE_AUTH_DENIED" : "PULL_SOURCE_REQUEST_REJECTED");
  182. }
  183. private static JsonDocument? ReadCredential(string? reference)
  184. {
  185. if (reference is null) return null;
  186. var value = Environment.GetEnvironmentVariable(reference);
  187. if (string.IsNullOrEmpty(value) || value.Length > 8192) throw new MdpApiPullException("PULL_CREDENTIAL_UNAVAILABLE");
  188. try { return JsonDocument.Parse(value); }
  189. catch (JsonException) { throw new MdpApiPullException("PULL_CREDENTIAL_INVALID"); }
  190. }
  191. private static string Secret(JsonDocument? doc, string name) =>
  192. (doc is null ? default : MdpApiPullPlan.Value(doc.RootElement, name)) is { ValueKind: JsonValueKind.String } value
  193. && value.GetString() is { Length: > 0 and <= 4096 } text && !text.Any(char.IsControl)
  194. ? text : throw new MdpApiPullException("PULL_CREDENTIAL_INVALID");
  195. private static void SetBasic(HttpRequestMessage request, string user, string password)
  196. {
  197. if (user.Contains(':')) throw new MdpApiPullException("PULL_CREDENTIAL_INVALID");
  198. request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password)));
  199. }
  200. private sealed record TokenScope(long Tenant, long Source, string Reference, string Endpoint, string? Scope);
  201. private sealed class TokenCache
  202. {
  203. public SemaphoreSlim Gate { get; } = new(1, 1);
  204. public string? Value { get; set; }
  205. public DateTimeOffset ValidUntil { get; set; }
  206. }
  207. }
  208. internal sealed record MdpApiPullResponse(HttpStatusCode Status, Uri Effective, byte[] Body, string? NextLink, TimeSpan? RetryAfter, string? LinkDiagnostic = null);