MdpUploadGrantController.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using Furion.Logging;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. [ApiController, Authorize, NonUnify, RequirePcMenuPath("/aidop/data-platform/sources")]
  6. [Route("api/DataPlatform/upload-grants")]
  7. public sealed class MdpUploadGrantController(ISqlSugarClient host, UserManager user) : ControllerBase
  8. {
  9. [HttpGet]
  10. public async Task<IActionResult> Choices([FromQuery] string sourceCode)
  11. {
  12. if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
  13. var tenant = AidopTenantScope.ResolveOrThrow(user);
  14. using var db = MdpIngestDatabase.Open(host);
  15. var rows = await db.Ado.SqlQueryAsync<Choice>("""
  16. SELECT CAST(d.id AS CHAR) AS Id,d.dataset_key AS DatasetKey,d.name AS Name,o.Name AS ConfigurationOrg,
  17. (SELECT CAST(MAX(g.id) AS CHAR) FROM mdp_ingest_access_grant g
  18. WHERE g.tenant_id=s.tenant_id AND g.source_id=s.id AND g.dataset_key=d.dataset_key
  19. AND g.use_batch_factory=1 AND g.enabled=1) AS GrantId
  20. FROM mdp_source s JOIN mdp_ingest_dataset_source b ON b.tenant_id=s.tenant_id AND b.source_id=s.id AND b.enabled=1
  21. JOIN mdp_ingest_dataset d ON d.tenant_id=b.tenant_id AND d.id=b.dataset_id AND d.factory_id=b.factory_id
  22. JOIN SysOrg o ON o.TenantId=d.tenant_id AND o.Id=d.factory_id
  23. WHERE s.tenant_id=@tenant AND s.source_code=@sourceCode AND s.status=1 AND s.source_type='API_INBOUND'
  24. ORDER BY d.dataset_key,d.id
  25. """, new { tenant, sourceCode });
  26. return Ok(rows);
  27. }
  28. public sealed class Choice
  29. {
  30. public string Id { get; set; } = "";
  31. public string DatasetKey { get; set; } = "";
  32. public string Name { get; set; } = "";
  33. public string ConfigurationOrg { get; set; } = "";
  34. public string? GrantId { get; set; }
  35. }
  36. public sealed record IssueInput([Required] string SourceCode, [Range(1,long.MaxValue)] long DatasetId,
  37. [Range(1,10000)] int RateLimitPerMinute, long? PreviousGrantId);
  38. [HttpPost, SuppressMonitor]
  39. [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
  40. public async Task<IActionResult> Issue(IssueInput input)
  41. {
  42. if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
  43. var tenant = AidopTenantScope.ResolveOrThrow(user);
  44. using var db = MdpIngestDatabase.Open(host);
  45. var tx = await db.Ado.UseTranAsync<IActionResult>(async () =>
  46. {
  47. var sourceId = await db.Ado.SqlQuerySingleAsync<long?>("""
  48. SELECT id FROM mdp_source WHERE tenant_id=@tenant AND source_code=@SourceCode
  49. AND status=1 AND source_type='API_INBOUND' FOR UPDATE
  50. """, new { tenant, input.SourceCode });
  51. if (!sourceId.HasValue) return NotFound();
  52. var dataset = await db.Ado.SqlQuerySingleAsync<GrantDataset>("""
  53. SELECT d.factory_id AS Factory,d.dataset_key AS DatasetKey FROM mdp_ingest_dataset d
  54. JOIN mdp_ingest_dataset_source b ON b.tenant_id=d.tenant_id AND b.factory_id=d.factory_id AND b.dataset_id=d.id
  55. WHERE d.id=@DatasetId AND d.tenant_id=@tenant AND b.source_id=@sourceId AND b.enabled=1 FOR SHARE
  56. """, new { tenant, sourceId, input.DatasetId });
  57. if (dataset == null) return NotFound();
  58. var current = await db.Ado.SqlQuerySingleAsync<long?>("""
  59. SELECT MAX(id) FROM mdp_ingest_access_grant WHERE tenant_id=@tenant AND source_id=@sourceId
  60. AND dataset_key=@DatasetKey AND enabled=1 AND use_batch_factory=1
  61. """, new { tenant, sourceId, dataset.DatasetKey });
  62. if (current != input.PreviousGrantId) return Conflict(new { message = "凭据已变化,请重新打开向导" });
  63. var accessKey = "mdp_" + Convert.ToHexString(RandomNumberGenerator.GetBytes(20)).ToLowerInvariant();
  64. byte[] signingKey;
  65. try { signingKey = MdpUploadSigningKeys.Derive(accessKey); }
  66. catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException)
  67. {
  68. return StatusCode(503,new { message = "请由部署人员配置统一上传签发密钥" });
  69. }
  70. try
  71. {
  72. if (current.HasValue)
  73. await db.Ado.ExecuteCommandAsync("""
  74. UPDATE mdp_ingest_access_grant g JOIN mdp_ingest_credential_ref c
  75. ON c.tenant_id=g.tenant_id AND c.access_key_hash=g.access_key_hash
  76. SET g.enabled=0,c.revoked_at=UTC_TIMESTAMP(6)
  77. WHERE g.id=@current AND g.tenant_id=@tenant AND g.use_batch_factory=1
  78. """, new { current, tenant });
  79. var hash = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(accessKey))).ToLowerInvariant();
  80. await db.Ado.ExecuteCommandAsync("""
  81. INSERT INTO mdp_ingest_credential_ref(access_key_hash,tenant_id,user_id,secret_ref,created_at)
  82. VALUES (@hash,@tenant,@actor,@reference,UTC_TIMESTAMP(6))
  83. """, new { hash, tenant, actor=user.UserId, reference=MdpUploadSigningKeys.Reference });
  84. await db.Ado.ExecuteCommandAsync("""
  85. INSERT INTO mdp_ingest_access_grant(tenant_id,factory_id,source_id,dataset_key,access_key_hash,
  86. enabled,rate_limit_per_min,use_batch_factory) VALUES (@tenant,@Factory,@sourceId,@DatasetKey,@hash,1,@rate,1)
  87. """, new { tenant, dataset.Factory, sourceId, dataset.DatasetKey, hash, rate=input.RateLimitPerMinute });
  88. return Ok(new { accessKey, signingKeyBase64=Convert.ToBase64String(signingKey) });
  89. }
  90. finally { CryptographicOperations.ZeroMemory(signingKey); }
  91. });
  92. if (!tx.IsSuccess) throw tx.ErrorException ?? new InvalidOperationException("上传凭据签发失败");
  93. return tx.Data;
  94. }
  95. private sealed class GrantDataset
  96. {
  97. public long Factory { get; set; }
  98. public string DatasetKey { get; set; } = "";
  99. }
  100. }