|
|
@@ -1,10 +1,12 @@
|
|
|
using System.Globalization;
|
|
|
+using System.Net.Http.Headers;
|
|
|
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 Admin.NET.Plugin.AiDOP.DataPlatform.Core;
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
@@ -17,7 +19,8 @@ public sealed class MdpIngestAuthenticationHandler(
|
|
|
ILoggerFactory logger,
|
|
|
UrlEncoder encoder,
|
|
|
MdpIngestAdmissionStore store,
|
|
|
- ISecretStore secrets) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
|
|
+ ISecretStore secrets,
|
|
|
+ MdpIngestExternalIdentities external) : 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");
|
|
|
@@ -30,64 +33,130 @@ public sealed class MdpIngestAuthenticationHandler(
|
|
|
if (Request.ContentLength > MdpIngestProtocol.Limits.MaxBodyBytes)
|
|
|
return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
|
|
|
|
|
|
- var accessKey = ReadHeader(InboundSignatureDefaults.AccessKeyHeader, 128);
|
|
|
+ var query = HttpMethods.IsGet(Request.Method);
|
|
|
+ var signatureVersion = ReadHeader(MdpIngestProtocol.SignatureVersionHeader, 40);
|
|
|
+ var schemaVersion = ReadHeader(MdpIngestProtocol.SchemaHeader, 64);
|
|
|
+ var factoryHeader = ReadHeader(MdpIngestProtocol.FactoryHeader, 19);
|
|
|
+ if (signatureVersion is null && Request.Headers.ContainsKey(MdpIngestProtocol.SignatureVersionHeader)
|
|
|
+ || schemaVersion is null && Request.Headers.ContainsKey(MdpIngestProtocol.SchemaHeader)
|
|
|
+ || factoryHeader is null && Request.Headers.ContainsKey(MdpIngestProtocol.FactoryHeader))
|
|
|
+ return Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST_METADATA");
|
|
|
+
|
|
|
+ long? factoryId = null;
|
|
|
+ if (factoryHeader is not null)
|
|
|
+ {
|
|
|
+ if (!long.TryParse(factoryHeader, NumberStyles.None, CultureInfo.InvariantCulture, out var factory) || factory <= 0)
|
|
|
+ return Fail(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
|
|
|
+ factoryId = factory;
|
|
|
+ }
|
|
|
+
|
|
|
+ var mediaType = query ? "" : "application/json";
|
|
|
+ if (Request.ContentType is { } contentType)
|
|
|
+ {
|
|
|
+ if (query || !MediaTypeHeaderValue.TryParse(contentType, out var media)
|
|
|
+ || media.MediaType is null
|
|
|
+ || media.Parameters.Any(parameter => !parameter.Name.Equals("charset", StringComparison.OrdinalIgnoreCase))
|
|
|
+ || media.Parameters.Count > 1
|
|
|
+ || media.CharSet is { } charset && !charset.Trim('"').Equals("utf-8", StringComparison.OrdinalIgnoreCase))
|
|
|
+ return Fail(StatusCodes.Status415UnsupportedMediaType, "UNSUPPORTED_MEDIA_TYPE");
|
|
|
+ mediaType = media.MediaType.ToLowerInvariant();
|
|
|
+ }
|
|
|
+ if (mediaType is not ("" or "application/json" or "application/x-ndjson"))
|
|
|
+ return Fail(StatusCodes.Status415UnsupportedMediaType, "UNSUPPORTED_MEDIA_TYPE");
|
|
|
+ var format = mediaType == "application/x-ndjson" ? IngestPayloadFormat.Ndjson : IngestPayloadFormat.Json;
|
|
|
+ if (!query && format == IngestPayloadFormat.Json && factoryId.HasValue
|
|
|
+ || query && schemaVersion is not null)
|
|
|
+ return Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST_METADATA");
|
|
|
+
|
|
|
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)
|
|
|
+ if (timestamp is null || nonce is null
|
|
|
+ || !long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var unixSeconds)
|
|
|
+ || !IsWithinClockSkew(unixSeconds))
|
|
|
return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
|
|
|
|
|
|
- var idempotencyKey = ReadHeader(InboundSignatureDefaults.IdempotencyKeyHeader, 128);
|
|
|
+ var idempotencyKey = query ? "" : 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))
|
|
|
+ if (query && payload.Length != 0)
|
|
|
+ return Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST");
|
|
|
+
|
|
|
+ var certificate = await Context.Connection.GetClientCertificateAsync(Context.RequestAborted);
|
|
|
+ var hasBearer = Request.Headers.ContainsKey("Authorization");
|
|
|
+ var hasHmac = Request.Headers.ContainsKey(InboundSignatureDefaults.AccessKeyHeader)
|
|
|
+ || Request.Headers.ContainsKey(InboundSignatureDefaults.SignatureHeader) || signatureVersion is not null;
|
|
|
+ if ((hasBearer ? 1 : 0) + (hasHmac ? 1 : 0) + (certificate is null ? 0 : 1) != 1
|
|
|
+ || (hasBearer || certificate is not null) && !Request.IsHttps)
|
|
|
return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
|
|
|
|
|
|
- // 报文读取可能耗时,准入前再核对签名时效。
|
|
|
- if (!IsWithinClockSkew(unixSeconds))
|
|
|
+ MdpIngestIdentity? caller;
|
|
|
+ if (hasHmac)
|
|
|
+ {
|
|
|
+ var accessKey = ReadHeader(InboundSignatureDefaults.AccessKeyHeader, 128);
|
|
|
+ var signature = ReadHeader(InboundSignatureDefaults.SignatureHeader, 44);
|
|
|
+ var digest = ReadHeader(InboundSignatureDefaults.ContentSha256Header, 64);
|
|
|
+ var v2 = signatureVersion == MdpIngestProtocol.SignatureVersionV2;
|
|
|
+ if (accessKey is null || signature?.Length != 44 || digest?.Length != 64
|
|
|
+ || !v2 && (query || format == IngestPayloadFormat.Ndjson || schemaVersion is not null
|
|
|
+ || signatureVersion is not (null or MdpIngestProtocol.SignatureVersion)))
|
|
|
+ return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
|
|
|
+
|
|
|
+ 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);
|
|
|
+ var signed = MdpIngestProtocol.CanonicalSignature(Request.Method, Request.Path.Value!, accessKey,
|
|
|
+ timestamp, nonce, payloadSha256, idempotencyKey, v2, mediaType, factoryHeader, schemaVersion);
|
|
|
+ if (credential is null || !credential.Verify(signed, signature))
|
|
|
+ return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
|
|
|
+
|
|
|
+ caller = new MdpIngestIdentity(credential.TenantId, credential.UserId, Sha256(Encoding.UTF8.GetBytes(accessKey)));
|
|
|
+ }
|
|
|
+ else if (certificate is not null)
|
|
|
+ {
|
|
|
+ caller = external.ResolveCertificate(certificate);
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ caller = await external.ResolveBearerAsync(Request.Headers.Authorization, query, Context.RequestAborted);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 报文读取和证书/令牌验证可能耗时,准入前再核对时效。
|
|
|
+ if (caller is null || !IsWithinClockSkew(unixSeconds))
|
|
|
return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
|
|
|
|
|
|
- var accessKeyHash = Sha256(Encoding.UTF8.GetBytes(accessKey));
|
|
|
- var admission = await store.AdmitAsync(credential.TenantId, accessKeyHash, datasetKey,
|
|
|
+ var admission = await store.AdmitAsync(caller.TenantId, caller.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.Status == MdpIngestAdmissionStatus.TenantLimited)
|
|
|
+ return Fail(StatusCodes.Status429TooManyRequests, "TENANT_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))
|
|
|
+ long targetFactory;
|
|
|
+ var validFactory = query || format == IngestPayloadFormat.Ndjson
|
|
|
+ ? MdpBatchFactory.TryResolve(grant.FactoryId, grant.UseBatchFactory, factoryId, out targetFactory)
|
|
|
+ : MdpBatchFactory.TryRead(payload, caller.TenantId, grant.FactoryId, grant.UseBatchFactory, out targetFactory);
|
|
|
+ if (!validFactory)
|
|
|
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);
|
|
|
+ Context.Items[typeof(MdpIngestSubmission)] = new MdpIngestSubmission(grant.Id, caller.TenantId,
|
|
|
+ targetFactory, grant.SourceId, datasetKey, idempotencyKey, payload, caller.AccessKeyHash,
|
|
|
+ grant.UseBatchFactory ? grant.FactoryId : null, format, schemaVersion);
|
|
|
var identity = new ClaimsIdentity(
|
|
|
[
|
|
|
- new Claim(ClaimConst.TenantId, credential.TenantId.ToString(CultureInfo.InvariantCulture)),
|
|
|
- new Claim(ClaimConst.UserId, credential.UserId.ToString(CultureInfo.InvariantCulture))
|
|
|
+ new Claim(ClaimConst.TenantId, caller.TenantId.ToString(CultureInfo.InvariantCulture)),
|
|
|
+ new Claim(ClaimConst.UserId, caller.UserId.ToString(CultureInfo.InvariantCulture))
|
|
|
], Scheme.Name);
|
|
|
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
|
|
|
}
|