| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163 |
- using System.Globalization;
- using System.Security.Claims;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Encodings.Web;
- using System.Text.RegularExpressions;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed class MdpIngestAuthenticationHandler(
- IOptionsMonitor<AuthenticationSchemeOptions> options,
- ILoggerFactory logger,
- UrlEncoder encoder,
- MdpIngestAdmissionStore store,
- ISecretStore secrets) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
- {
- private const long AllowedClockSkewSeconds = 300;
- private static readonly Regex DatasetKeyPattern = new(@"\A[a-z0-9][a-z0-9._-]{0,79}\z");
- protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
- {
- if (Request.RouteValues["datasetKey"] is not string datasetKey || !DatasetKeyPattern.IsMatch(datasetKey))
- return Fail(StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE");
- if (Request.ContentLength > MdpIngestProtocol.Limits.MaxBodyBytes)
- return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
- var accessKey = ReadHeader(InboundSignatureDefaults.AccessKeyHeader, 128);
- var timestamp = ReadHeader(InboundSignatureDefaults.TimestampHeader, 20);
- var nonce = ReadHeader(InboundSignatureDefaults.NonceHeader, 128);
- var signature = ReadHeader(InboundSignatureDefaults.SignatureHeader, 44);
- var digest = ReadHeader(InboundSignatureDefaults.ContentSha256Header, 64);
- if (accessKey is null || timestamp is null || nonce is null || signature?.Length != 44 || digest?.Length != 64)
- return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
- var idempotencyKey = ReadHeader(InboundSignatureDefaults.IdempotencyKeyHeader, 128);
- if (idempotencyKey is null)
- return Fail(StatusCodes.Status400BadRequest, "INVALID_IDEMPOTENCY_KEY");
- if (!long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var unixSeconds)
- || !IsWithinClockSkew(unixSeconds))
- return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
- try
- {
- var payload = await ReadPayloadAsync();
- if (payload is null)
- return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
- var payloadSha256 = Sha256(payload);
- if (!string.Equals(payloadSha256, digest, StringComparison.OrdinalIgnoreCase))
- return Fail(StatusCodes.Status400BadRequest, "CONTENT_DIGEST_MISMATCH");
- using var credential = await secrets.ResolveAsync(accessKey, Context.RequestAborted);
- if (credential is null)
- return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
- var signed = $"{Request.Method.ToUpperInvariant()}&{Request.Path.Value}&{accessKey}&{timestamp}&{nonce}&{payloadSha256}&{idempotencyKey}";
- if (!credential.Verify(signed, signature))
- return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
- // 报文读取可能耗时,准入前再核对签名时效。
- if (!IsWithinClockSkew(unixSeconds))
- return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
- var accessKeyHash = Sha256(Encoding.UTF8.GetBytes(accessKey));
- var admission = await store.AdmitAsync(credential.TenantId, accessKeyHash, datasetKey,
- Sha256(Encoding.UTF8.GetBytes(nonce)), Context.RequestAborted);
- if (admission.Status == MdpIngestAdmissionStatus.Replayed)
- return Fail(StatusCodes.Status401Unauthorized, "NONCE_REPLAYED");
- if (admission.Status == MdpIngestAdmissionStatus.Limited)
- return Fail(StatusCodes.Status429TooManyRequests, "SOURCE_RATE_LIMITED", admission.RetryAfterSeconds);
- if (admission.Grant is not { } grant)
- return Fail(StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE");
- if (!MdpBatchFactory.TryRead(payload, credential.TenantId, grant.FactoryId, grant.UseBatchFactory, out var targetFactory))
- return Fail(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
- Context.Items[typeof(MdpIngestSubmission)] = new MdpIngestSubmission(grant.Id, credential.TenantId,
- targetFactory, grant.SourceId, datasetKey, idempotencyKey, payload, accessKeyHash,
- grant.UseBatchFactory ? grant.FactoryId : null);
- var identity = new ClaimsIdentity(
- [
- new Claim(ClaimConst.TenantId, credential.TenantId.ToString(CultureInfo.InvariantCulture)),
- new Claim(ClaimConst.UserId, credential.UserId.ToString(CultureInfo.InvariantCulture))
- ], Scheme.Name);
- return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
- }
- catch (BadHttpRequestException exception)
- {
- return exception.StatusCode == StatusCodes.Status413PayloadTooLarge
- ? Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE")
- : Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST");
- }
- catch (Exception exception) when (!Context.RequestAborted.IsCancellationRequested)
- {
- Logger.LogWarning("接收准入失败,请求 {TraceIdentifier},异常类型 {ExceptionType}",
- Context.TraceIdentifier, exception.GetType().Name);
- return Fail(StatusCodes.Status503ServiceUnavailable, "ADMISSION_UNAVAILABLE");
- }
- }
- protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
- {
- await HandleAuthenticateOnceSafeAsync();
- if (Response.HasStarted)
- return;
- var failure = Context.Items[typeof(AdmissionFailure)] as AdmissionFailure
- ?? new AdmissionFailure(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION", 0);
- Response.StatusCode = failure.StatusCode;
- if (failure.RetryAfterSeconds > 0)
- Response.Headers.RetryAfter = failure.RetryAfterSeconds.ToString(CultureInfo.InvariantCulture);
- await Response.WriteAsJsonAsync(new { code = failure.Code, traceId = Context.TraceIdentifier }, Context.RequestAborted);
- }
- private AuthenticateResult Fail(int statusCode, string code, int retryAfterSeconds = 0)
- {
- Context.Items[typeof(AdmissionFailure)] = new AdmissionFailure(statusCode, code, retryAfterSeconds);
- return AuthenticateResult.Fail(code);
- }
- private string? ReadHeader(string name, int maxLength)
- {
- if (!Request.Headers.TryGetValue(name, out var values) || values.Count != 1
- || values[0] is not { Length: > 0 } value || value.Length > maxLength
- || value.Any(character => character is < '!' or > '~' or '&' or ','))
- return null;
- return value;
- }
- private async Task<byte[]?> ReadPayloadAsync()
- {
- var limit = MdpIngestProtocol.Limits.MaxBodyBytes;
- using var body = new MemoryStream();
- var buffer = new byte[8192];
- while (true)
- {
- var readSize = Math.Min(buffer.Length, limit - (int)body.Length + 1);
- var count = await Request.Body.ReadAsync(buffer.AsMemory(0, readSize), Context.RequestAborted);
- if (count == 0)
- return body.ToArray();
- if (body.Length + count > limit)
- return null;
- body.Write(buffer.AsSpan(0, count));
- }
- }
- private static bool IsWithinClockSkew(long timestamp)
- {
- var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
- return timestamp >= now - AllowedClockSkewSeconds && timestamp <= now + AllowedClockSkewSeconds;
- }
- private static string Sha256(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
- private sealed record AdmissionFailure(int StatusCode, string Code, int RetryAfterSeconds);
- }
|