MdpEdgeDeviceService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System.Security.Cryptography;
  2. using System.Security.Cryptography.X509Certificates;
  3. using System.Text;
  4. using System.Text.Json;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  6. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  7. using Microsoft.Extensions.Configuration;
  8. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  9. public sealed partial class MdpEdgeDeviceService(ISqlSugarClient host, IConfiguration settings)
  10. {
  11. private const string Devices = """
  12. SELECT device_id AS DeviceId,tenant_id AS TenantId,factory_id AS FactoryId,dataset_id AS DatasetId,
  13. source_id AS SourceId,device_name AS DeviceName,state AS State,activation_expires AS ActivationExpires,
  14. certificate_expires AS CertificateExpires,config_json AS ConfigJson,config_generation AS Generation,
  15. position_text AS Position,task_phase AS Phase,seen_at AS SeenAt,report_json AS ReportJson,
  16. page_count AS PageCount,row_count AS RowCount,
  17. (SELECT p.batch_id FROM mdp_edge_api_rejected_page p WHERE p.device_id=mdp_edge_device.device_id
  18. AND p.generation=mdp_edge_device.config_generation AND p.settled_at IS NULL AND mdp_edge_device.task_phase='BLOCKED'
  19. ORDER BY p.batch_id LIMIT 1) AS RejectedRawId,
  20. (SELECT r.digest FROM mdp_edge_api_rejected_page p JOIN mdp_edge_receipt r ON r.batch_id=p.batch_id
  21. WHERE p.device_id=mdp_edge_device.device_id AND p.generation=mdp_edge_device.config_generation
  22. AND p.settled_at IS NULL AND mdp_edge_device.task_phase='BLOCKED' ORDER BY p.batch_id LIMIT 1) AS RejectedDigest
  23. FROM mdp_edge_device
  24. """;
  25. public async Task<object> ListAsync(long tenant, long factory, long dataset)
  26. {
  27. RequireEnabled();
  28. using var db = MdpIngestDatabase.Open(host);
  29. var devices = await db.Ado.SqlQueryAsync<Device>(Devices + """
  30. WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset ORDER BY created_at DESC LIMIT 100
  31. """, new { tenant, factory, dataset });
  32. return devices.Select(x => new
  33. {
  34. x.DeviceId, x.DeviceName, SourceId = x.SourceId.ToString(System.Globalization.CultureInfo.InvariantCulture),
  35. x.State, x.CertificateExpires, x.Generation, x.Phase, x.SeenAt, x.PageCount, x.RowCount,
  36. x.RejectedRawId, x.RejectedDigest,
  37. HandoffPending = x.State == "REVOKED" && x.ConfigJson is not null && x.Phase != HandedOff,
  38. Online = x.State == "ACTIVE" && x.SeenAt >= DateTime.UtcNow.AddSeconds(-60),
  39. Watermark = long.TryParse(x.Position, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var value)
  40. ? value.ToString(System.Globalization.CultureInfo.InvariantCulture) : null,
  41. Report = x.ReportJson is null ? null : JsonSerializer.Deserialize<EdgeReport>(x.ReportJson, EdgeProtocol.Json)
  42. }).ToArray();
  43. }
  44. public async Task<object> ApproveAsync(long tenant, long factory, long dataset, long source, string name, long actor)
  45. {
  46. RequireEnabled();
  47. Require(name is { Length: > 0 and <= 120 } && !name.Any(char.IsControl), "EDGE_DEVICE_NAME_INVALID");
  48. var deviceId = Guid.NewGuid().ToString("D");
  49. var activation = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
  50. using var db = MdpIngestDatabase.Open(host);
  51. return await Tx(db, async () =>
  52. {
  53. _ = await BoundAsync(db, tenant, factory, dataset, source, true);
  54. Require(await db.Ado.GetIntAsync("""
  55. SELECT COUNT(*) FROM mdp_edge_device
  56. WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND source_id=@source AND active_slot=1
  57. """, new { tenant, factory, dataset, source }) == 0, "EDGE_BINDING_ACTIVE");
  58. await db.Ado.ExecuteCommandAsync("""
  59. INSERT INTO mdp_edge_device(device_id,tenant_id,factory_id,dataset_id,source_id,device_name,state,
  60. active_slot,activation_hash,activation_expires)
  61. VALUES (@deviceId,@tenant,@factory,@dataset,@source,@name,'APPROVED',1,@hash,TIMESTAMPADD(MINUTE,15,UTC_TIMESTAMP(6)))
  62. """, new { deviceId, tenant, factory, dataset, source, name, hash = HashText(activation) });
  63. await AuditAsync(db, dataset, actor, "EDGE_APPROVED", deviceId);
  64. return new { deviceId, activation, validForSeconds = 900 };
  65. });
  66. }
  67. public async Task<EdgeCertificate> RegisterAsync(EdgeRegistration input, CancellationToken token)
  68. {
  69. RequireEnabled();
  70. Require(input.Activation is { Length: 64 } && input.Activation.All(Uri.IsHexDigit), "EDGE_ACTIVATION_INVALID");
  71. var hash = HashText(input.Activation);
  72. using var db = MdpIngestDatabase.Open(host);
  73. return await Tx(db, async () =>
  74. {
  75. var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  76. WHERE activation_hash=@hash AND activation_expires>UTC_TIMESTAMP(6) AND state='APPROVED' FOR UPDATE
  77. """, new { hash }) ?? throw new EdgeContractException("EDGE_ACTIVATION_INVALID");
  78. using var certificate = Sign(device.DeviceId, input.RequestPem);
  79. await UpdateCertificateAsync(db, device, certificate);
  80. await AuditAsync(db, device.DatasetId, 0, "EDGE_REGISTERED", device.DeviceId);
  81. token.ThrowIfCancellationRequested();
  82. return new EdgeCertificate(Guid.Parse(device.DeviceId), certificate.ExportCertificatePem());
  83. });
  84. }
  85. public async Task<EdgeCertificate> RenewAsync(X509Certificate2 issued, EdgeRenewal input, CancellationToken token)
  86. {
  87. RequireEnabled();
  88. using var db = MdpIngestDatabase.Open(host);
  89. return await Tx(db, async () =>
  90. {
  91. var device = await AuthenticateAsync(db, issued, true);
  92. using var certificate = Sign(device.DeviceId, input.RequestPem);
  93. // The currently verified certificate remains current until explicit confirmation using the pending certificate.
  94. await db.Ado.ExecuteCommandAsync("""
  95. UPDATE mdp_edge_device SET next_certificate_hash=@hash,next_certificate_expires=@expiry WHERE device_id=@DeviceId
  96. """, new { device.DeviceId, hash = EdgeProtocol.Digest(certificate.RawData), expiry = certificate.NotAfter.ToUniversalTime() });
  97. await AuditAsync(db, device.DatasetId, 0, "EDGE_RENEWAL_ISSUED", device.DeviceId);
  98. token.ThrowIfCancellationRequested();
  99. return new EdgeCertificate(Guid.Parse(device.DeviceId), certificate.ExportCertificatePem());
  100. });
  101. }
  102. public async Task ConfirmCertificateAsync(X509Certificate2 certificate, CancellationToken token)
  103. {
  104. RequireEnabled();
  105. using var db = MdpIngestDatabase.Open(host);
  106. var hash = CertificateHash(certificate);
  107. await Tx(db, async () =>
  108. {
  109. var device = await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  110. WHERE next_certificate_hash=@hash AND next_certificate_expires>UTC_TIMESTAMP(6) AND state='ACTIVE' FOR UPDATE
  111. """, new { hash });
  112. if (device is null)
  113. {
  114. _ = await AuthenticateAsync(db, certificate, true);
  115. return true;
  116. }
  117. await db.Ado.ExecuteCommandAsync("""
  118. UPDATE mdp_edge_device SET certificate_hash=next_certificate_hash,certificate_expires=next_certificate_expires,
  119. next_certificate_hash=NULL,next_certificate_expires=NULL WHERE device_id=@DeviceId
  120. """, new { device.DeviceId });
  121. await AuditAsync(db, device.DatasetId, 0, "EDGE_CERT_ROTATED", device.DeviceId);
  122. token.ThrowIfCancellationRequested();
  123. return true;
  124. });
  125. }
  126. public async Task RevokeAsync(long tenant, long factory, long dataset, Guid id, long actor)
  127. {
  128. RequireEnabled();
  129. var deviceId = id.ToString("D");
  130. using var db = MdpIngestDatabase.Open(host);
  131. await Tx(db, async () =>
  132. {
  133. var changed = await db.Ado.ExecuteCommandAsync("""
  134. UPDATE mdp_edge_device SET state='REVOKED',active_slot=NULL,activation_hash=NULL,
  135. certificate_hash=NULL,next_certificate_hash=NULL,task_phase='PAUSED'
  136. WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND device_id=@deviceId
  137. AND state<>'REVOKED'
  138. """, new { tenant, factory, dataset, deviceId });
  139. Require(changed == 1, "EDGE_DEVICE_NOT_FOUND");
  140. await AuditAsync(db, dataset, actor, "EDGE_REVOKED", deviceId);
  141. return true;
  142. });
  143. }
  144. public async Task<EdgeTask?> PollAsync(X509Certificate2 certificate, EdgeReport report)
  145. {
  146. RequireEnabled();
  147. Require(report.Version is { Length: > 0 and <= 32 } && report.Pending >= 0 && report.BufferedBytes >= 0
  148. && report.FreeBytes >= 0 && (report.LastError?.Length ?? 0) <= 100, "EDGE_REPORT_INVALID");
  149. using var db = MdpIngestDatabase.Open(host);
  150. return await Tx(db, async () =>
  151. {
  152. var device = await AuthenticateAsync(db, certificate, true);
  153. await db.Ado.ExecuteCommandAsync("""
  154. UPDATE mdp_edge_device SET seen_at=UTC_TIMESTAMP(6),report_json=@json WHERE device_id=@DeviceId
  155. """, new { device.DeviceId, json = JsonSerializer.Serialize(report, EdgeProtocol.Json) });
  156. if (device.ConfigJson is null) return null;
  157. var task = await RecoveryTaskAsync(db, device, includeSettled: true);
  158. return task with { LeaseUntil = DateTimeOffset.UtcNow.AddSeconds(60) };
  159. });
  160. }
  161. private static string CertificateHash(X509Certificate2 certificate)
  162. {
  163. var now = DateTime.UtcNow;
  164. Require(now >= certificate.NotBefore.ToUniversalTime() && now < certificate.NotAfter.ToUniversalTime(), "EDGE_DEVICE_FORBIDDEN");
  165. return EdgeProtocol.Digest(certificate.RawData);
  166. }
  167. private static async Task<Device> AuthenticateAsync(ISqlSugarClient db, X509Certificate2 certificate, bool locked) =>
  168. await db.Ado.SqlQuerySingleAsync<Device>(Devices + """
  169. WHERE certificate_hash=@hash AND certificate_expires>UTC_TIMESTAMP(6) AND state='ACTIVE'
  170. """ + (locked ? " FOR UPDATE" : ""), new { hash = CertificateHash(certificate) })
  171. ?? throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN");
  172. private X509Certificate2 Sign(string deviceId, string pem)
  173. {
  174. Require(pem is { Length: > 0 and <= 8192 }, "EDGE_CERT_REQUEST_INVALID");
  175. var path = settings["MdpEdge:CaPfxPath"];
  176. Require(!string.IsNullOrWhiteSpace(path), "EDGE_CA_UNAVAILABLE");
  177. try
  178. {
  179. using var ca = new X509Certificate2(path!, settings["MdpEdge:CaPfxPassword"], X509KeyStorageFlags.EphemeralKeySet);
  180. var loaded = CertificateRequest.LoadSigningRequestPem(pem, HashAlgorithmName.SHA256);
  181. using var publicKey = loaded.PublicKey.GetECDsaPublicKey();
  182. Require(publicKey?.KeySize == 256, "EDGE_CERT_REQUEST_INVALID");
  183. var request = new CertificateRequest(new X500DistinguishedName("CN=" + deviceId), loaded.PublicKey, HashAlgorithmName.SHA256);
  184. request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
  185. request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
  186. request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.2") }, true));
  187. var end = DateTimeOffset.UtcNow.AddDays(Math.Clamp(settings.GetValue("MdpEdge:CertificateDays", 30), 1, 90));
  188. if (end.UtcDateTime > ca.NotAfter.ToUniversalTime()) end = ca.NotAfter.ToUniversalTime();
  189. using var rsa = ca.GetRSAPrivateKey();
  190. using var ec = ca.GetECDsaPrivateKey();
  191. var signature = rsa is not null
  192. ? X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1)
  193. : ec is not null ? X509SignatureGenerator.CreateForECDsa(ec) : throw new EdgeContractException("EDGE_CA_UNAVAILABLE");
  194. var start = DateTimeOffset.UtcNow.AddSeconds(-10);
  195. if (start.UtcDateTime < ca.NotBefore.ToUniversalTime()) start = ca.NotBefore.ToUniversalTime();
  196. return request.Create(ca.SubjectName, signature, start, end, RandomNumberGenerator.GetBytes(20));
  197. }
  198. catch (Exception error) when (error is ArgumentException or CryptographicException)
  199. {
  200. throw new EdgeContractException("EDGE_CERT_REQUEST_INVALID");
  201. }
  202. }
  203. private static Task<int> UpdateCertificateAsync(ISqlSugarClient db, Device device, X509Certificate2 certificate) =>
  204. db.Ado.ExecuteCommandAsync("""
  205. UPDATE mdp_edge_device SET state='ACTIVE',activation_hash=NULL,activation_expires=NULL,
  206. certificate_hash=@hash,certificate_expires=@expiry WHERE device_id=@DeviceId
  207. """, new { device.DeviceId, hash = EdgeProtocol.Digest(certificate.RawData), expiry = certificate.NotAfter.ToUniversalTime() });
  208. private static Task<int> AuditAsync(ISqlSugarClient db, long dataset, long actor, string action, string detail) =>
  209. db.Ado.ExecuteCommandAsync("""
  210. INSERT INTO mdp_ingest_release_log(dataset_id,action,actor,detail,created_at)
  211. VALUES (@dataset,@action,@actor,@detail,UTC_TIMESTAMP(6))
  212. """, new { dataset, action, actor, detail });
  213. private void RequireEnabled() => Require(settings.GetValue<bool>("MdpEdge:Enabled"), "EDGE_DISABLED");
  214. private static string HashText(string value) => EdgeProtocol.Digest(Encoding.UTF8.GetBytes(value));
  215. private static void Require(bool condition, string code)
  216. {
  217. if (!condition) throw new EdgeContractException(code);
  218. }
  219. private static async Task<T> Tx<T>(ISqlSugarClient db, Func<Task<T>> run)
  220. {
  221. var result = await db.Ado.UseTranAsync(run);
  222. if (result.IsSuccess) return result.Data;
  223. if (result.ErrorException is { } failure) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure);
  224. throw new EdgeContractException("EDGE_STORE_UNAVAILABLE");
  225. }
  226. private sealed class Device
  227. {
  228. public string DeviceId { get; set; } = "";
  229. public long TenantId { get; set; }
  230. public long FactoryId { get; set; }
  231. public long DatasetId { get; set; }
  232. public long SourceId { get; set; }
  233. public string DeviceName { get; set; } = "";
  234. public string State { get; set; } = "";
  235. public DateTime? ActivationExpires { get; set; }
  236. public DateTime? CertificateExpires { get; set; }
  237. public string? ConfigJson { get; set; }
  238. public long Generation { get; set; }
  239. public string? Position { get; set; }
  240. public string? Phase { get; set; }
  241. public DateTime? SeenAt { get; set; }
  242. public string? ReportJson { get; set; }
  243. public int PageCount { get; set; }
  244. public long RowCount { get; set; }
  245. public string? RejectedRawId { get; set; }
  246. public string? RejectedDigest { get; set; }
  247. }
  248. }