MdpIngestAuthenticationHandler.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. using System.Globalization;
  2. using System.Security.Claims;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using System.Text.Encodings.Web;
  6. using System.Text.RegularExpressions;
  7. using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
  8. using Microsoft.AspNetCore.Authentication;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.Extensions.Options;
  12. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  13. public sealed class MdpIngestAuthenticationHandler(
  14. IOptionsMonitor<AuthenticationSchemeOptions> options,
  15. ILoggerFactory logger,
  16. UrlEncoder encoder,
  17. MdpIngestAdmissionStore store,
  18. ISecretStore secrets) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
  19. {
  20. private const long AllowedClockSkewSeconds = 300;
  21. private static readonly Regex DatasetKeyPattern = new(@"\A[a-z0-9][a-z0-9._-]{0,79}\z");
  22. protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
  23. {
  24. if (Request.RouteValues["datasetKey"] is not string datasetKey || !DatasetKeyPattern.IsMatch(datasetKey))
  25. return Fail(StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE");
  26. if (Request.ContentLength > MdpIngestProtocol.Limits.MaxBodyBytes)
  27. return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
  28. var accessKey = ReadHeader(InboundSignatureDefaults.AccessKeyHeader, 128);
  29. var timestamp = ReadHeader(InboundSignatureDefaults.TimestampHeader, 20);
  30. var nonce = ReadHeader(InboundSignatureDefaults.NonceHeader, 128);
  31. var signature = ReadHeader(InboundSignatureDefaults.SignatureHeader, 44);
  32. var digest = ReadHeader(InboundSignatureDefaults.ContentSha256Header, 64);
  33. if (accessKey is null || timestamp is null || nonce is null || signature?.Length != 44 || digest?.Length != 64)
  34. return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
  35. var idempotencyKey = ReadHeader(InboundSignatureDefaults.IdempotencyKeyHeader, 128);
  36. if (idempotencyKey is null)
  37. return Fail(StatusCodes.Status400BadRequest, "INVALID_IDEMPOTENCY_KEY");
  38. if (!long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var unixSeconds)
  39. || !IsWithinClockSkew(unixSeconds))
  40. return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
  41. try
  42. {
  43. var payload = await ReadPayloadAsync();
  44. if (payload is null)
  45. return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
  46. var payloadSha256 = Sha256(payload);
  47. if (!string.Equals(payloadSha256, digest, StringComparison.OrdinalIgnoreCase))
  48. return Fail(StatusCodes.Status400BadRequest, "CONTENT_DIGEST_MISMATCH");
  49. using var credential = await secrets.ResolveAsync(accessKey, Context.RequestAborted);
  50. if (credential is null)
  51. return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
  52. var signed = $"{Request.Method.ToUpperInvariant()}&{Request.Path.Value}&{accessKey}&{timestamp}&{nonce}&{payloadSha256}&{idempotencyKey}";
  53. if (!credential.Verify(signed, signature))
  54. return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
  55. // 报文读取可能耗时,准入前再核对签名时效。
  56. if (!IsWithinClockSkew(unixSeconds))
  57. return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
  58. var accessKeyHash = Sha256(Encoding.UTF8.GetBytes(accessKey));
  59. var admission = await store.AdmitAsync(credential.TenantId, accessKeyHash, datasetKey,
  60. Sha256(Encoding.UTF8.GetBytes(nonce)), Context.RequestAborted);
  61. if (admission.Status == MdpIngestAdmissionStatus.Replayed)
  62. return Fail(StatusCodes.Status401Unauthorized, "NONCE_REPLAYED");
  63. if (admission.Status == MdpIngestAdmissionStatus.Limited)
  64. return Fail(StatusCodes.Status429TooManyRequests, "SOURCE_RATE_LIMITED", admission.RetryAfterSeconds);
  65. if (admission.Grant is not { } grant)
  66. return Fail(StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE");
  67. if (!MdpBatchFactory.TryRead(payload, credential.TenantId, grant.FactoryId, grant.UseBatchFactory, out var targetFactory))
  68. return Fail(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
  69. Context.Items[typeof(MdpIngestSubmission)] = new MdpIngestSubmission(grant.Id, credential.TenantId,
  70. targetFactory, grant.SourceId, datasetKey, idempotencyKey, payload, accessKeyHash,
  71. grant.UseBatchFactory ? grant.FactoryId : null);
  72. var identity = new ClaimsIdentity(
  73. [
  74. new Claim(ClaimConst.TenantId, credential.TenantId.ToString(CultureInfo.InvariantCulture)),
  75. new Claim(ClaimConst.UserId, credential.UserId.ToString(CultureInfo.InvariantCulture))
  76. ], Scheme.Name);
  77. return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
  78. }
  79. catch (BadHttpRequestException exception)
  80. {
  81. return exception.StatusCode == StatusCodes.Status413PayloadTooLarge
  82. ? Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE")
  83. : Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST");
  84. }
  85. catch (Exception exception) when (!Context.RequestAborted.IsCancellationRequested)
  86. {
  87. Logger.LogWarning("接收准入失败,请求 {TraceIdentifier},异常类型 {ExceptionType}",
  88. Context.TraceIdentifier, exception.GetType().Name);
  89. return Fail(StatusCodes.Status503ServiceUnavailable, "ADMISSION_UNAVAILABLE");
  90. }
  91. }
  92. protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
  93. {
  94. await HandleAuthenticateOnceSafeAsync();
  95. if (Response.HasStarted)
  96. return;
  97. var failure = Context.Items[typeof(AdmissionFailure)] as AdmissionFailure
  98. ?? new AdmissionFailure(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION", 0);
  99. Response.StatusCode = failure.StatusCode;
  100. if (failure.RetryAfterSeconds > 0)
  101. Response.Headers.RetryAfter = failure.RetryAfterSeconds.ToString(CultureInfo.InvariantCulture);
  102. await Response.WriteAsJsonAsync(new { code = failure.Code, traceId = Context.TraceIdentifier }, Context.RequestAborted);
  103. }
  104. private AuthenticateResult Fail(int statusCode, string code, int retryAfterSeconds = 0)
  105. {
  106. Context.Items[typeof(AdmissionFailure)] = new AdmissionFailure(statusCode, code, retryAfterSeconds);
  107. return AuthenticateResult.Fail(code);
  108. }
  109. private string? ReadHeader(string name, int maxLength)
  110. {
  111. if (!Request.Headers.TryGetValue(name, out var values) || values.Count != 1
  112. || values[0] is not { Length: > 0 } value || value.Length > maxLength
  113. || value.Any(character => character is < '!' or > '~' or '&' or ','))
  114. return null;
  115. return value;
  116. }
  117. private async Task<byte[]?> ReadPayloadAsync()
  118. {
  119. var limit = MdpIngestProtocol.Limits.MaxBodyBytes;
  120. using var body = new MemoryStream();
  121. var buffer = new byte[8192];
  122. while (true)
  123. {
  124. var readSize = Math.Min(buffer.Length, limit - (int)body.Length + 1);
  125. var count = await Request.Body.ReadAsync(buffer.AsMemory(0, readSize), Context.RequestAborted);
  126. if (count == 0)
  127. return body.ToArray();
  128. if (body.Length + count > limit)
  129. return null;
  130. body.Write(buffer.AsSpan(0, count));
  131. }
  132. }
  133. private static bool IsWithinClockSkew(long timestamp)
  134. {
  135. var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  136. return timestamp >= now - AllowedClockSkewSeconds && timestamp <= now + AllowedClockSkewSeconds;
  137. }
  138. private static string Sha256(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
  139. private sealed record AdmissionFailure(int StatusCode, string Code, int RetryAfterSeconds);
  140. }