using System.Net; using System.Net.Http.Json; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge; namespace Admin.NET.DataPlatform.Edge; internal sealed class EdgeTransport(Uri origin) { internal HttpClient Connect(X509Certificate2? certificate) { if (origin.Scheme != "https" || origin.UserInfo.Length != 0 || origin.Query.Length != 0 || origin.Fragment.Length != 0 || origin.AbsolutePath != "/") throw new EdgeContractException("EDGE_PLATFORM_URL_INVALID"); var handler = new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false, UseCookies = false }; if (certificate is not null) handler.ClientCertificates.Add(certificate); return new HttpClient(handler) { BaseAddress = origin, Timeout = TimeSpan.FromSeconds(30) }; } internal async Task EnrollAsync(EdgeLocalState local, byte[] key, string activation, CancellationToken token) { if (File.Exists(Path.Combine(local.DirectoryPath, "certificate"))) throw new EdgeContractException("EDGE_ALREADY_REGISTERED"); using var client = Connect(null); using var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); var csr = new CertificateRequest("CN=AiDOP Edge", privateKey, HashAlgorithmName.SHA256); var result = await PostAsync(client, "/api/v1/edge/register", new(activation, csr.CreateSigningRequestPem()), token) ?? throw new EdgeContractException("EDGE_REGISTRATION_RESPONSE_INVALID"); using var leaf = X509Certificate2.CreateFromPem(result.CertificatePem); using var verified = leaf.CopyWithPrivateKey(privateKey); local.WriteCertificate(verified, key); } internal async Task RotateAsync(EdgeLocalState local, byte[] queueKey, X509Certificate2 current, CancellationToken token) { using var previouslyPending = local.ReadCertificate(queueKey, pending: true); if (previouslyPending is not null) { try { await ConfirmAsync(previouslyPending, token); local.PromoteCertificate(); return; } catch (EdgeContractException error) when (error.Code == "EDGE_DEVICE_FORBIDDEN") { } } using var client = Connect(current); using var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); var csr = new CertificateRequest("CN=AiDOP Edge", privateKey, HashAlgorithmName.SHA256); var issued = await PostAsync(client, "/api/v1/edge/certificate/renew", new(csr.CreateSigningRequestPem()), token) ?? throw new EdgeContractException("EDGE_RENEWAL_RESPONSE_INVALID"); using var leaf = X509Certificate2.CreateFromPem(issued.CertificatePem); using var pending = leaf.CopyWithPrivateKey(privateKey); local.WriteCertificate(pending, queueKey, pending: true); await ConfirmAsync(pending, token); local.PromoteCertificate(); } internal async Task SendAsync(HttpClient client, EdgeBatch batch, CancellationToken token) { using var status = await client.GetAsync("/api/v1/edge/batches/" + batch.BatchId.ToString("D"), token); if (status.StatusCode != HttpStatusCode.NotFound) return await ReadAsync(status, token) ?? throw new EdgeContractException("EDGE_RECEIPT_MISSING"); return await PostAsync(client, "/api/v1/edge/batches", batch, token) ?? throw new EdgeContractException("EDGE_RECEIPT_MISSING"); } private async Task ConfirmAsync(X509Certificate2 certificate, CancellationToken token) { using var client = Connect(certificate); using var response = await client.PostAsync("/api/v1/edge/certificate/confirm", null, token); if (!response.IsSuccessStatusCode) throw new EdgeContractException(response.StatusCode == HttpStatusCode.Forbidden ? "EDGE_DEVICE_FORBIDDEN" : "EDGE_CONFIRM_FAILED"); } internal static async Task PostAsync(HttpClient client, string route, TInput input, CancellationToken token) { using var response = await client.PostAsJsonAsync(route, input, EdgeProtocol.Json, token); return await ReadAsync(response, token); } private static async Task ReadAsync(HttpResponseMessage response, CancellationToken token) { if (response.StatusCode == HttpStatusCode.Forbidden) throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN"); if (!response.IsSuccessStatusCode) throw new EdgeContractException($"EDGE_PLATFORM_HTTP_{(int)response.StatusCode}"); if (response.StatusCode == HttpStatusCode.NoContent) return default; return await response.Content.ReadFromJsonAsync(EdgeProtocol.Json, token); } }