EdgeTransport.cs 4.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System.Net;
  2. using System.Net.Http.Json;
  3. using System.Security.Cryptography;
  4. using System.Security.Cryptography.X509Certificates;
  5. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  6. namespace Admin.NET.DataPlatform.Edge;
  7. internal sealed class EdgeTransport(Uri origin)
  8. {
  9. internal HttpClient Connect(X509Certificate2? certificate)
  10. {
  11. if (origin.Scheme != "https" || origin.UserInfo.Length != 0 || origin.Query.Length != 0 || origin.Fragment.Length != 0
  12. || origin.AbsolutePath != "/")
  13. throw new EdgeContractException("EDGE_PLATFORM_URL_INVALID");
  14. var handler = new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false, UseCookies = false };
  15. if (certificate is not null) handler.ClientCertificates.Add(certificate);
  16. return new HttpClient(handler) { BaseAddress = origin, Timeout = TimeSpan.FromSeconds(30) };
  17. }
  18. internal async Task EnrollAsync(EdgeLocalState local, byte[] key, string activation, CancellationToken token)
  19. {
  20. if (File.Exists(Path.Combine(local.DirectoryPath, "certificate")))
  21. throw new EdgeContractException("EDGE_ALREADY_REGISTERED");
  22. using var client = Connect(null);
  23. using var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
  24. var csr = new CertificateRequest("CN=AiDOP Edge", privateKey, HashAlgorithmName.SHA256);
  25. var result = await PostAsync<EdgeRegistration, EdgeCertificate>(client, "/api/v1/edge/register",
  26. new(activation, csr.CreateSigningRequestPem()), token) ?? throw new EdgeContractException("EDGE_REGISTRATION_RESPONSE_INVALID");
  27. using var leaf = X509Certificate2.CreateFromPem(result.CertificatePem);
  28. using var verified = leaf.CopyWithPrivateKey(privateKey);
  29. local.WriteCertificate(verified, key);
  30. }
  31. internal async Task RotateAsync(EdgeLocalState local, byte[] queueKey, X509Certificate2 current, CancellationToken token)
  32. {
  33. using var previouslyPending = local.ReadCertificate(queueKey, pending: true);
  34. if (previouslyPending is not null)
  35. {
  36. try
  37. {
  38. await ConfirmAsync(previouslyPending, token);
  39. local.PromoteCertificate();
  40. return;
  41. }
  42. catch (EdgeContractException error) when (error.Code == "EDGE_DEVICE_FORBIDDEN") { }
  43. }
  44. using var client = Connect(current);
  45. using var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
  46. var csr = new CertificateRequest("CN=AiDOP Edge", privateKey, HashAlgorithmName.SHA256);
  47. var issued = await PostAsync<EdgeRenewal, EdgeCertificate>(client, "/api/v1/edge/certificate/renew",
  48. new(csr.CreateSigningRequestPem()), token) ?? throw new EdgeContractException("EDGE_RENEWAL_RESPONSE_INVALID");
  49. using var leaf = X509Certificate2.CreateFromPem(issued.CertificatePem);
  50. using var pending = leaf.CopyWithPrivateKey(privateKey);
  51. local.WriteCertificate(pending, queueKey, pending: true);
  52. await ConfirmAsync(pending, token);
  53. local.PromoteCertificate();
  54. }
  55. internal async Task<EdgeReceipt> SendAsync(HttpClient client, EdgeBatch batch, CancellationToken token)
  56. {
  57. using var status = await client.GetAsync("/api/v1/edge/batches/" + batch.BatchId.ToString("D"), token);
  58. if (status.StatusCode != HttpStatusCode.NotFound)
  59. return await ReadAsync<EdgeReceipt>(status, token) ?? throw new EdgeContractException("EDGE_RECEIPT_MISSING");
  60. return await PostAsync<EdgeBatch, EdgeReceipt>(client, "/api/v1/edge/batches", batch, token)
  61. ?? throw new EdgeContractException("EDGE_RECEIPT_MISSING");
  62. }
  63. private async Task ConfirmAsync(X509Certificate2 certificate, CancellationToken token)
  64. {
  65. using var client = Connect(certificate);
  66. using var response = await client.PostAsync("/api/v1/edge/certificate/confirm", null, token);
  67. if (!response.IsSuccessStatusCode)
  68. throw new EdgeContractException(response.StatusCode == HttpStatusCode.Forbidden ? "EDGE_DEVICE_FORBIDDEN" : "EDGE_CONFIRM_FAILED");
  69. }
  70. internal static async Task<TResponse?> PostAsync<TInput, TResponse>(HttpClient client, string route, TInput input, CancellationToken token)
  71. {
  72. using var response = await client.PostAsJsonAsync(route, input, EdgeProtocol.Json, token);
  73. return await ReadAsync<TResponse>(response, token);
  74. }
  75. private static async Task<T?> ReadAsync<T>(HttpResponseMessage response, CancellationToken token)
  76. {
  77. if (response.StatusCode == HttpStatusCode.Forbidden) throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN");
  78. if (!response.IsSuccessStatusCode) throw new EdgeContractException($"EDGE_PLATFORM_HTTP_{(int)response.StatusCode}");
  79. if (response.StatusCode == HttpStatusCode.NoContent) return default;
  80. return await response.Content.ReadFromJsonAsync<T>(EdgeProtocol.Json, token);
  81. }
  82. }