MdpIngestSecretStore.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System.Runtime.ExceptionServices;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. /// <summary>Management callers construct this scope only after checking the operator's credential-management permission.</summary>
  7. public sealed record MdpIngestCredentialOwner(long TenantId, long UserId);
  8. public sealed record MdpIngestCredentialStatus(
  9. string ReferenceId, string MaskedAccessKey, bool Enabled, DateTime? RotatedAtUtc);
  10. public interface ISecretStore
  11. {
  12. Task<MdpIngestSigningCredential?> ResolveAsync(string accessKey, CancellationToken cancellationToken);
  13. Task<MdpIngestCredentialStatus> RegisterReferenceAsync(
  14. MdpIngestCredentialOwner owner, string accessKey, string secretReference, CancellationToken cancellationToken);
  15. Task<MdpIngestCredentialStatus> RotateAsync(
  16. MdpIngestCredentialOwner owner, string previousKey, string newKey, string newReference, CancellationToken cancellationToken);
  17. Task<MdpIngestCredentialStatus?> InspectAsync(
  18. MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken);
  19. Task<bool> RevokeAsync(MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken);
  20. }
  21. public sealed class MdpIngestSigningCredential : IDisposable
  22. {
  23. private readonly byte[] _key;
  24. private bool _disposed;
  25. internal MdpIngestSigningCredential(long tenantId, long userId, byte[] key)
  26. {
  27. TenantId = tenantId;
  28. UserId = userId;
  29. _key = key;
  30. }
  31. public long TenantId { get; }
  32. public long UserId { get; }
  33. public bool Verify(string canonical, string signature)
  34. {
  35. ObjectDisposedException.ThrowIf(_disposed, this);
  36. Span<byte> provided = stackalloc byte[32];
  37. if (!Convert.TryFromBase64String(signature, provided, out var decoded) || decoded != provided.Length)
  38. return false;
  39. Span<byte> expected = stackalloc byte[32];
  40. HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(canonical), expected);
  41. return CryptographicOperations.FixedTimeEquals(expected, provided);
  42. }
  43. public void Dispose()
  44. {
  45. CryptographicOperations.ZeroMemory(_key);
  46. _disposed = true;
  47. }
  48. }
  49. /// <summary>The deployment injects a Base64-encoded 256-bit key. The database contains only its reference.</summary>
  50. internal interface IMdpIngestSecretProvider
  51. {
  52. byte[]? Read(string reference);
  53. }
  54. internal sealed class EnvironmentMdpIngestSecretProvider : IMdpIngestSecretProvider
  55. {
  56. private static readonly Regex ReferenceName = new(@"\AMDP_INGRESS_SECRET_[A-Z0-9_]{1,64}\z");
  57. public byte[]? Read(string reference)
  58. {
  59. if (reference is null || !ReferenceName.IsMatch(reference))
  60. return null;
  61. var encoded = Environment.GetEnvironmentVariable(reference);
  62. Span<byte> decoded = stackalloc byte[32];
  63. try
  64. {
  65. return encoded is { Length: 44 }
  66. && Convert.TryFromBase64String(encoded, decoded, out var length)
  67. && length == decoded.Length ? decoded.ToArray() : null;
  68. }
  69. finally
  70. {
  71. CryptographicOperations.ZeroMemory(decoded);
  72. }
  73. }
  74. }
  75. internal sealed class MdpIngestSecretStore(ISqlSugarClient host, IMdpIngestSecretProvider provider) : ISecretStore
  76. {
  77. private const string OwnerFields = """
  78. SELECT tenant_id AS TenantId, user_id AS UserId, secret_ref AS SecretRef,
  79. rotated_at AS RotatedAt, revoked_at AS RevokedAt
  80. FROM mdp_ingest_credential_ref
  81. WHERE access_key_hash = @KeyHash AND tenant_id = @TenantId AND user_id = @UserId
  82. """;
  83. public async Task<MdpIngestSigningCredential?> ResolveAsync(string accessKey, CancellationToken cancellationToken)
  84. {
  85. if (!IsValidKey(accessKey))
  86. return null;
  87. using var db = Open(cancellationToken);
  88. var record = await db.Ado.SqlQuerySingleAsync<MdpIngestCredentialRecord>(
  89. """
  90. SELECT tenant_id AS TenantId, user_id AS UserId, secret_ref AS SecretRef
  91. FROM mdp_ingest_credential_ref WHERE access_key_hash = @KeyHash AND revoked_at IS NULL
  92. """, new { KeyHash = HashKey(accessKey) });
  93. if (record is not { TenantId: > 0, UserId: > 0 })
  94. return null;
  95. var secret = record.SecretRef == MdpUploadSigningKeys.Reference
  96. ? MdpUploadSigningKeys.Derive(accessKey) : provider.Read(record.SecretRef);
  97. return secret is null ? null : new MdpIngestSigningCredential(record.TenantId, record.UserId, secret);
  98. }
  99. public async Task<MdpIngestCredentialStatus> RegisterReferenceAsync(
  100. MdpIngestCredentialOwner owner, string accessKey, string secretReference, CancellationToken cancellationToken)
  101. {
  102. ValidateRegistration(owner, accessKey, secretReference);
  103. using var db = Open(cancellationToken);
  104. await InsertReferenceAsync(db, owner, accessKey, secretReference, null);
  105. return Status(accessKey, true, null);
  106. }
  107. public async Task<MdpIngestCredentialStatus> RotateAsync(
  108. MdpIngestCredentialOwner owner, string previousKey, string newKey, string newReference, CancellationToken cancellationToken)
  109. {
  110. ValidateRegistration(owner, newKey, newReference);
  111. if (!IsValidKey(previousKey) || string.Equals(previousKey, newKey, StringComparison.Ordinal))
  112. throw new InvalidOperationException("INGRESS_CREDENTIAL_ROTATION_INVALID");
  113. using var db = Open(cancellationToken);
  114. return await InTransactionAsync(db, async () =>
  115. {
  116. var previous = await db.Ado.SqlQuerySingleAsync<MdpIngestCredentialRecord>(OwnerFields + " FOR UPDATE",
  117. new { KeyHash = HashKey(previousKey), owner.TenantId, owner.UserId });
  118. if (previous is null || previous.RevokedAt.HasValue || previous.SecretRef == newReference)
  119. throw new InvalidOperationException("INGRESS_CREDENTIAL_ROTATION_INVALID");
  120. var rotatedAt = DateTime.UtcNow;
  121. await InsertReferenceAsync(db, owner, newKey, newReference, rotatedAt);
  122. await db.Ado.ExecuteCommandAsync(
  123. """
  124. INSERT INTO mdp_ingest_access_grant
  125. (tenant_id, factory_id, source_id, dataset_key, access_key_hash, enabled, rate_limit_per_min, use_batch_factory)
  126. SELECT tenant_id, factory_id, source_id, dataset_key, @NewKeyHash, enabled, rate_limit_per_min, use_batch_factory
  127. FROM mdp_ingest_access_grant
  128. WHERE tenant_id = @TenantId AND access_key_hash = @PreviousKeyHash AND enabled = 1
  129. """, new { owner.TenantId, NewKeyHash = HashKey(newKey), PreviousKeyHash = HashKey(previousKey) });
  130. cancellationToken.ThrowIfCancellationRequested();
  131. return Status(newKey, true, rotatedAt);
  132. });
  133. }
  134. public async Task<MdpIngestCredentialStatus?> InspectAsync(
  135. MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken)
  136. {
  137. if (!IsValidKey(accessKey))
  138. return null;
  139. using var db = Open(cancellationToken);
  140. var record = await db.Ado.SqlQuerySingleAsync<MdpIngestCredentialRecord>(OwnerFields,
  141. new { KeyHash = HashKey(accessKey), owner.TenantId, owner.UserId });
  142. return record is null
  143. ? null
  144. : Status(accessKey, !record.RevokedAt.HasValue,
  145. record.RotatedAt is DateTime time ? DateTime.SpecifyKind(time, DateTimeKind.Utc) : null);
  146. }
  147. public async Task<bool> RevokeAsync(
  148. MdpIngestCredentialOwner owner, string accessKey, CancellationToken cancellationToken)
  149. {
  150. if (!IsValidKey(accessKey))
  151. return false;
  152. using var db = Open(cancellationToken);
  153. return await InTransactionAsync(db, async () =>
  154. {
  155. var parameters = new { KeyHash = HashKey(accessKey), owner.TenantId, owner.UserId };
  156. var count = await db.Ado.ExecuteCommandAsync(
  157. """
  158. UPDATE mdp_ingest_credential_ref SET revoked_at = UTC_TIMESTAMP(6)
  159. WHERE access_key_hash = @KeyHash AND tenant_id = @TenantId AND user_id = @UserId AND revoked_at IS NULL
  160. """, parameters);
  161. if (count == 0)
  162. return false;
  163. // Prevent a request that already resolved the old key from committing after revocation.
  164. await db.Ado.ExecuteCommandAsync(
  165. """
  166. UPDATE mdp_ingest_access_grant SET enabled = 0
  167. WHERE access_key_hash = @KeyHash AND tenant_id = @TenantId AND enabled = 1
  168. """, parameters);
  169. cancellationToken.ThrowIfCancellationRequested();
  170. return true;
  171. });
  172. }
  173. private void ValidateRegistration(MdpIngestCredentialOwner owner, string accessKey, string reference)
  174. {
  175. if (owner.TenantId <= 0 || owner.UserId <= 0 || !IsValidKey(accessKey))
  176. throw new InvalidOperationException("INGRESS_CREDENTIAL_SCOPE_INVALID");
  177. var key = provider.Read(reference) ?? throw new InvalidOperationException("INGRESS_SECRET_REFERENCE_UNAVAILABLE");
  178. CryptographicOperations.ZeroMemory(key);
  179. }
  180. private SqlSugarClient Open(CancellationToken cancellationToken)
  181. {
  182. cancellationToken.ThrowIfCancellationRequested();
  183. var db = MdpIngestDatabase.Open(host);
  184. db.Ado.CancellationToken = cancellationToken;
  185. return db;
  186. }
  187. private static Task<int> InsertReferenceAsync(SqlSugarClient db, MdpIngestCredentialOwner owner, string key, string reference, DateTime? rotatedAt) =>
  188. db.Ado.ExecuteCommandAsync(
  189. """
  190. INSERT INTO mdp_ingest_credential_ref (access_key_hash, tenant_id, user_id, secret_ref, created_at, rotated_at)
  191. VALUES (@KeyHash, @TenantId, @UserId, @Reference, UTC_TIMESTAMP(6), @RotatedAt)
  192. """, new { KeyHash = HashKey(key), owner.TenantId, owner.UserId, Reference = reference, RotatedAt = rotatedAt });
  193. private static async Task<T> InTransactionAsync<T>(SqlSugarClient db, Func<Task<T>> work)
  194. {
  195. var transaction = await db.Ado.UseTranAsync(work);
  196. if (transaction.IsSuccess)
  197. return transaction.Data;
  198. if (transaction.ErrorException is not null)
  199. ExceptionDispatchInfo.Throw(transaction.ErrorException);
  200. throw new InvalidOperationException("INGRESS_CREDENTIAL_UPDATE_UNAVAILABLE");
  201. }
  202. private static bool IsValidKey(string value) =>
  203. value is { Length: > 0 and <= 128 } && !value.Any(character => character is < '!' or > '~' or '&' or ',');
  204. private static string HashKey(string key) =>
  205. Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant();
  206. private static MdpIngestCredentialStatus Status(string key, bool enabled, DateTime? rotatedAt) =>
  207. new(HashKey(key), key.Length > 4 ? $"****{key[^4..]}" : "****", enabled, rotatedAt);
  208. }
  209. internal sealed class MdpIngestCredentialRecord
  210. {
  211. public long TenantId { get; set; }
  212. public long UserId { get; set; }
  213. public string SecretRef { get; set; } = string.Empty;
  214. public DateTime? RotatedAt { get; set; }
  215. public DateTime? RevokedAt { get; set; }
  216. }