| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- using System.Runtime.ExceptionServices;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- /// <summary>Management callers construct this scope only after checking the operator's credential-management permission.</summary>
- public sealed record MdpIngestCredentialOwner(long TenantId, long UserId);
- public sealed record MdpIngestCredentialStatus(
- string ReferenceId, string MaskedAccessKey, bool Enabled, DateTime? RotatedAtUtc);
- public interface ISecretStore
- {
- Task<MdpIngestSigningCredential?> ResolveAsync(string accessKey, CancellationToken cancellationToken);
- Task<MdpIngestCredentialStatus> RegisterReferenceAsync(
- MdpIngestCredentialOwner owner, string accessKey, string secretReference, CancellationToken cancellationToken);
- Task<MdpIngestCredentialStatus> RotateAsync(
- MdpIngestCredentialOwner owner, string previousKey, string newKey, string newReference, CancellationToken cancellationToken);
- Task<MdpIngestCredentialStatus?> InspectAsync(
- MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken);
- Task<bool> RevokeAsync(MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken);
- }
- public sealed class MdpIngestSigningCredential : IDisposable
- {
- private readonly byte[] _key;
- private bool _disposed;
- internal MdpIngestSigningCredential(long tenantId, long userId, byte[] key)
- {
- TenantId = tenantId;
- UserId = userId;
- _key = key;
- }
- public long TenantId { get; }
- public long UserId { get; }
- public bool Verify(string canonical, string signature)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- Span<byte> provided = stackalloc byte[32];
- if (!Convert.TryFromBase64String(signature, provided, out var decoded) || decoded != provided.Length)
- return false;
- Span<byte> expected = stackalloc byte[32];
- HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(canonical), expected);
- return CryptographicOperations.FixedTimeEquals(expected, provided);
- }
- public void Dispose()
- {
- CryptographicOperations.ZeroMemory(_key);
- _disposed = true;
- }
- }
- /// <summary>The deployment injects a Base64-encoded 256-bit key. The database contains only its reference.</summary>
- internal interface IMdpIngestSecretProvider
- {
- byte[]? Read(string reference);
- }
- internal sealed class EnvironmentMdpIngestSecretProvider : IMdpIngestSecretProvider
- {
- private static readonly Regex ReferenceName = new(@"\AMDP_INGRESS_SECRET_[A-Z0-9_]{1,64}\z");
- public byte[]? Read(string reference)
- {
- if (reference is null || !ReferenceName.IsMatch(reference))
- return null;
- var encoded = Environment.GetEnvironmentVariable(reference);
- Span<byte> decoded = stackalloc byte[32];
- try
- {
- return encoded is { Length: 44 }
- && Convert.TryFromBase64String(encoded, decoded, out var length)
- && length == decoded.Length ? decoded.ToArray() : null;
- }
- finally
- {
- CryptographicOperations.ZeroMemory(decoded);
- }
- }
- }
- internal sealed class MdpIngestSecretStore(ISqlSugarClient host, IMdpIngestSecretProvider provider) : ISecretStore
- {
- private const string OwnerFields = """
- SELECT tenant_id AS TenantId, user_id AS UserId, secret_ref AS SecretRef,
- rotated_at AS RotatedAt, revoked_at AS RevokedAt
- FROM mdp_ingest_credential_ref
- WHERE access_key_hash = @KeyHash AND tenant_id = @TenantId AND user_id = @UserId
- """;
- public async Task<MdpIngestSigningCredential?> ResolveAsync(string accessKey, CancellationToken cancellationToken)
- {
- if (!IsValidKey(accessKey))
- return null;
- using var db = Open(cancellationToken);
- var record = await db.Ado.SqlQuerySingleAsync<MdpIngestCredentialRecord>(
- """
- SELECT tenant_id AS TenantId, user_id AS UserId, secret_ref AS SecretRef
- FROM mdp_ingest_credential_ref WHERE access_key_hash = @KeyHash AND revoked_at IS NULL
- """, new { KeyHash = HashKey(accessKey) });
- if (record is not { TenantId: > 0, UserId: > 0 })
- return null;
- var secret = record.SecretRef == MdpUploadSigningKeys.Reference
- ? MdpUploadSigningKeys.Derive(accessKey) : provider.Read(record.SecretRef);
- return secret is null ? null : new MdpIngestSigningCredential(record.TenantId, record.UserId, secret);
- }
- public async Task<MdpIngestCredentialStatus> RegisterReferenceAsync(
- MdpIngestCredentialOwner owner, string accessKey, string secretReference, CancellationToken cancellationToken)
- {
- ValidateRegistration(owner, accessKey, secretReference);
- using var db = Open(cancellationToken);
- await InsertReferenceAsync(db, owner, accessKey, secretReference, null);
- return Status(accessKey, true, null);
- }
- public async Task<MdpIngestCredentialStatus> RotateAsync(
- MdpIngestCredentialOwner owner, string previousKey, string newKey, string newReference, CancellationToken cancellationToken)
- {
- ValidateRegistration(owner, newKey, newReference);
- if (!IsValidKey(previousKey) || string.Equals(previousKey, newKey, StringComparison.Ordinal))
- throw new InvalidOperationException("INGRESS_CREDENTIAL_ROTATION_INVALID");
- using var db = Open(cancellationToken);
- return await InTransactionAsync(db, async () =>
- {
- var previous = await db.Ado.SqlQuerySingleAsync<MdpIngestCredentialRecord>(OwnerFields + " FOR UPDATE",
- new { KeyHash = HashKey(previousKey), owner.TenantId, owner.UserId });
- if (previous is null || previous.RevokedAt.HasValue || previous.SecretRef == newReference)
- throw new InvalidOperationException("INGRESS_CREDENTIAL_ROTATION_INVALID");
- var rotatedAt = DateTime.UtcNow;
- await InsertReferenceAsync(db, owner, newKey, newReference, rotatedAt);
- await db.Ado.ExecuteCommandAsync(
- """
- INSERT INTO mdp_ingest_access_grant
- (tenant_id, factory_id, source_id, dataset_key, access_key_hash, enabled, rate_limit_per_min, use_batch_factory)
- SELECT tenant_id, factory_id, source_id, dataset_key, @NewKeyHash, enabled, rate_limit_per_min, use_batch_factory
- FROM mdp_ingest_access_grant
- WHERE tenant_id = @TenantId AND access_key_hash = @PreviousKeyHash AND enabled = 1
- """, new { owner.TenantId, NewKeyHash = HashKey(newKey), PreviousKeyHash = HashKey(previousKey) });
- cancellationToken.ThrowIfCancellationRequested();
- return Status(newKey, true, rotatedAt);
- });
- }
- public async Task<MdpIngestCredentialStatus?> InspectAsync(
- MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken)
- {
- if (!IsValidKey(accessKey))
- return null;
- using var db = Open(cancellationToken);
- var record = await db.Ado.SqlQuerySingleAsync<MdpIngestCredentialRecord>(OwnerFields,
- new { KeyHash = HashKey(accessKey), owner.TenantId, owner.UserId });
- return record is null
- ? null
- : Status(accessKey, !record.RevokedAt.HasValue,
- record.RotatedAt is DateTime time ? DateTime.SpecifyKind(time, DateTimeKind.Utc) : null);
- }
- public async Task<bool> RevokeAsync(
- MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken)
- {
- if (!IsValidKey(accessKey))
- return false;
- using var db = Open(cancellationToken);
- return await InTransactionAsync(db, async () =>
- {
- var parameters = new { KeyHash = HashKey(accessKey), owner.TenantId, owner.UserId };
- var count = await db.Ado.ExecuteCommandAsync(
- """
- UPDATE mdp_ingest_credential_ref SET revoked_at = UTC_TIMESTAMP(6)
- WHERE access_key_hash = @KeyHash AND tenant_id = @TenantId AND user_id = @UserId AND revoked_at IS NULL
- """, parameters);
- if (count == 0)
- return false;
- // Prevent a request that already resolved the old key from committing after revocation.
- await db.Ado.ExecuteCommandAsync(
- """
- UPDATE mdp_ingest_access_grant SET enabled = 0
- WHERE access_key_hash = @KeyHash AND tenant_id = @TenantId AND enabled = 1
- """, parameters);
- cancellationToken.ThrowIfCancellationRequested();
- return true;
- });
- }
- private void ValidateRegistration(MdpIngestCredentialOwner owner, string accessKey, string reference)
- {
- if (owner.TenantId <= 0 || owner.UserId <= 0 || !IsValidKey(accessKey))
- throw new InvalidOperationException("INGRESS_CREDENTIAL_SCOPE_INVALID");
- var key = provider.Read(reference) ?? throw new InvalidOperationException("INGRESS_SECRET_REFERENCE_UNAVAILABLE");
- CryptographicOperations.ZeroMemory(key);
- }
- private SqlSugarClient Open(CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
- var db = MdpIngestDatabase.Open(host);
- db.Ado.CancellationToken = cancellationToken;
- return db;
- }
- private static Task<int> InsertReferenceAsync(SqlSugarClient db, MdpIngestCredentialOwner owner, string key, string reference, DateTime? rotatedAt) =>
- db.Ado.ExecuteCommandAsync(
- """
- INSERT INTO mdp_ingest_credential_ref (access_key_hash, tenant_id, user_id, secret_ref, created_at, rotated_at)
- VALUES (@KeyHash, @TenantId, @UserId, @Reference, UTC_TIMESTAMP(6), @RotatedAt)
- """, new { KeyHash = HashKey(key), owner.TenantId, owner.UserId, Reference = reference, RotatedAt = rotatedAt });
- private static async Task<T> InTransactionAsync<T>(SqlSugarClient db, Func<Task<T>> work)
- {
- var transaction = await db.Ado.UseTranAsync(work);
- if (transaction.IsSuccess)
- return transaction.Data;
- if (transaction.ErrorException is not null)
- ExceptionDispatchInfo.Throw(transaction.ErrorException);
- throw new InvalidOperationException("INGRESS_CREDENTIAL_UPDATE_UNAVAILABLE");
- }
- private static bool IsValidKey(string value) =>
- value is { Length: > 0 and <= 128 } && !value.Any(character => character is < '!' or > '~' or '&' or ',');
- private static string HashKey(string key) =>
- Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant();
- private static MdpIngestCredentialStatus Status(string key, bool enabled, DateTime? rotatedAt) =>
- new(HashKey(key), key.Length > 4 ? $"****{key[^4..]}" : "****", enabled, rotatedAt);
- }
- internal sealed class MdpIngestCredentialRecord
- {
- public long TenantId { get; set; }
- public long UserId { get; set; }
- public string SecretRef { get; set; } = string.Empty;
- public DateTime? RotatedAt { get; set; }
- public DateTime? RevokedAt { get; set; }
- }
|