using System.Runtime.ExceptionServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; /// Management callers construct this scope only after checking the operator's credential-management permission. public sealed record MdpIngestCredentialOwner(long TenantId, long UserId); public sealed record MdpIngestCredentialStatus( string ReferenceId, string MaskedAccessKey, bool Enabled, DateTime? RotatedAtUtc); public interface ISecretStore { Task ResolveAsync(string accessKey, CancellationToken cancellationToken); Task RegisterReferenceAsync( MdpIngestCredentialOwner owner, string accessKey, string secretReference, CancellationToken cancellationToken); Task RotateAsync( MdpIngestCredentialOwner owner, string previousKey, string newKey, string newReference, CancellationToken cancellationToken); Task InspectAsync( MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken); Task 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 provided = stackalloc byte[32]; if (!Convert.TryFromBase64String(signature, provided, out var decoded) || decoded != provided.Length) return false; Span 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; } } /// The deployment injects a Base64-encoded 256-bit key. The database contains only its reference. 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 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 ResolveAsync(string accessKey, CancellationToken cancellationToken) { if (!IsValidKey(accessKey)) return null; using var db = Open(cancellationToken); var record = await db.Ado.SqlQuerySingleAsync( """ 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 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 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(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 InspectAsync( MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken) { if (!IsValidKey(accessKey)) return null; using var db = Open(cancellationToken); var record = await db.Ado.SqlQuerySingleAsync(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 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 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 InTransactionAsync(SqlSugarClient db, Func> 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; } }