using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge; using Microsoft.Extensions.Configuration; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed partial class MdpEdgeDeviceService(ISqlSugarClient host, IConfiguration settings) { private const string Devices = """ SELECT device_id AS DeviceId,tenant_id AS TenantId,factory_id AS FactoryId,dataset_id AS DatasetId, source_id AS SourceId,device_name AS DeviceName,state AS State,activation_expires AS ActivationExpires, certificate_expires AS CertificateExpires,config_json AS ConfigJson,config_generation AS Generation, position_text AS Position,task_phase AS Phase,seen_at AS SeenAt,report_json AS ReportJson, page_count AS PageCount,row_count AS RowCount, (SELECT p.batch_id FROM mdp_edge_api_rejected_page p WHERE p.device_id=mdp_edge_device.device_id AND p.generation=mdp_edge_device.config_generation AND p.settled_at IS NULL AND mdp_edge_device.task_phase='BLOCKED' ORDER BY p.batch_id LIMIT 1) AS RejectedRawId, (SELECT r.digest FROM mdp_edge_api_rejected_page p JOIN mdp_edge_receipt r ON r.batch_id=p.batch_id WHERE p.device_id=mdp_edge_device.device_id AND p.generation=mdp_edge_device.config_generation AND p.settled_at IS NULL AND mdp_edge_device.task_phase='BLOCKED' ORDER BY p.batch_id LIMIT 1) AS RejectedDigest FROM mdp_edge_device """; public async Task ListAsync(long tenant, long factory, long dataset) { RequireEnabled(); using var db = MdpIngestDatabase.Open(host); var devices = await db.Ado.SqlQueryAsync(Devices + """ WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset ORDER BY created_at DESC LIMIT 100 """, new { tenant, factory, dataset }); return devices.Select(x => new { x.DeviceId, x.DeviceName, SourceId = x.SourceId.ToString(System.Globalization.CultureInfo.InvariantCulture), x.State, x.CertificateExpires, x.Generation, x.Phase, x.SeenAt, x.PageCount, x.RowCount, x.RejectedRawId, x.RejectedDigest, Online = x.State == "ACTIVE" && x.SeenAt >= DateTime.UtcNow.AddSeconds(-60), Watermark = long.TryParse(x.Position, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var value) ? value.ToString(System.Globalization.CultureInfo.InvariantCulture) : null, Report = x.ReportJson is null ? null : JsonSerializer.Deserialize(x.ReportJson, EdgeProtocol.Json) }).ToArray(); } public async Task ApproveAsync(long tenant, long factory, long dataset, long source, string name, long actor) { RequireEnabled(); Require(name is { Length: > 0 and <= 120 } && !name.Any(char.IsControl), "EDGE_DEVICE_NAME_INVALID"); var deviceId = Guid.NewGuid().ToString("D"); var activation = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); using var db = MdpIngestDatabase.Open(host); return await Tx(db, async () => { _ = await BoundAsync(db, tenant, factory, dataset, source, true); Require(await db.Ado.GetIntAsync(""" SELECT COUNT(*) FROM mdp_edge_device WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND source_id=@source AND active_slot=1 """, new { tenant, factory, dataset, source }) == 0, "EDGE_BINDING_ACTIVE"); await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_edge_device(device_id,tenant_id,factory_id,dataset_id,source_id,device_name,state, active_slot,activation_hash,activation_expires) VALUES (@deviceId,@tenant,@factory,@dataset,@source,@name,'APPROVED',1,@hash,TIMESTAMPADD(MINUTE,15,UTC_TIMESTAMP(6))) """, new { deviceId, tenant, factory, dataset, source, name, hash = HashText(activation) }); await AuditAsync(db, dataset, actor, "EDGE_APPROVED", deviceId); return new { deviceId, activation, validForSeconds = 900 }; }); } public async Task RegisterAsync(EdgeRegistration input, CancellationToken token) { RequireEnabled(); Require(input.Activation is { Length: 64 } && input.Activation.All(Uri.IsHexDigit), "EDGE_ACTIVATION_INVALID"); var hash = HashText(input.Activation); using var db = MdpIngestDatabase.Open(host); return await Tx(db, async () => { var device = await db.Ado.SqlQuerySingleAsync(Devices + """ WHERE activation_hash=@hash AND activation_expires>UTC_TIMESTAMP(6) AND state='APPROVED' FOR UPDATE """, new { hash }) ?? throw new EdgeContractException("EDGE_ACTIVATION_INVALID"); using var certificate = Sign(device.DeviceId, input.RequestPem); await UpdateCertificateAsync(db, device, certificate); await AuditAsync(db, device.DatasetId, 0, "EDGE_REGISTERED", device.DeviceId); token.ThrowIfCancellationRequested(); return new EdgeCertificate(Guid.Parse(device.DeviceId), certificate.ExportCertificatePem()); }); } public async Task RenewAsync(X509Certificate2 issued, EdgeRenewal input, CancellationToken token) { RequireEnabled(); using var db = MdpIngestDatabase.Open(host); return await Tx(db, async () => { var device = await AuthenticateAsync(db, issued, true); using var certificate = Sign(device.DeviceId, input.RequestPem); // The currently verified certificate remains current until explicit confirmation using the pending certificate. await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET next_certificate_hash=@hash,next_certificate_expires=@expiry WHERE device_id=@DeviceId """, new { device.DeviceId, hash = EdgeProtocol.Digest(certificate.RawData), expiry = certificate.NotAfter.ToUniversalTime() }); await AuditAsync(db, device.DatasetId, 0, "EDGE_RENEWAL_ISSUED", device.DeviceId); token.ThrowIfCancellationRequested(); return new EdgeCertificate(Guid.Parse(device.DeviceId), certificate.ExportCertificatePem()); }); } public async Task ConfirmCertificateAsync(X509Certificate2 certificate, CancellationToken token) { RequireEnabled(); using var db = MdpIngestDatabase.Open(host); var hash = CertificateHash(certificate); await Tx(db, async () => { var device = await db.Ado.SqlQuerySingleAsync(Devices + """ WHERE next_certificate_hash=@hash AND next_certificate_expires>UTC_TIMESTAMP(6) AND state='ACTIVE' FOR UPDATE """, new { hash }); if (device is null) { _ = await AuthenticateAsync(db, certificate, true); return true; } await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET certificate_hash=next_certificate_hash,certificate_expires=next_certificate_expires, next_certificate_hash=NULL,next_certificate_expires=NULL WHERE device_id=@DeviceId """, new { device.DeviceId }); await AuditAsync(db, device.DatasetId, 0, "EDGE_CERT_ROTATED", device.DeviceId); token.ThrowIfCancellationRequested(); return true; }); } public async Task RevokeAsync(long tenant, long factory, long dataset, Guid id, long actor) { RequireEnabled(); var deviceId = id.ToString("D"); using var db = MdpIngestDatabase.Open(host); await Tx(db, async () => { var changed = await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET state='REVOKED',active_slot=NULL,activation_hash=NULL, certificate_hash=NULL,next_certificate_hash=NULL,task_phase='PAUSED' WHERE tenant_id=@tenant AND factory_id=@factory AND dataset_id=@dataset AND device_id=@deviceId AND state<>'REVOKED' """, new { tenant, factory, dataset, deviceId }); Require(changed == 1, "EDGE_DEVICE_NOT_FOUND"); await AuditAsync(db, dataset, actor, "EDGE_REVOKED", deviceId); return true; }); } public async Task PollAsync(X509Certificate2 certificate, EdgeReport report) { RequireEnabled(); Require(report.Version is { Length: > 0 and <= 32 } && report.Pending >= 0 && report.BufferedBytes >= 0 && report.FreeBytes >= 0 && (report.LastError?.Length ?? 0) <= 100, "EDGE_REPORT_INVALID"); using var db = MdpIngestDatabase.Open(host); return await Tx(db, async () => { var device = await AuthenticateAsync(db, certificate, true); await db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET seen_at=UTC_TIMESTAMP(6),report_json=@json WHERE device_id=@DeviceId """, new { device.DeviceId, json = JsonSerializer.Serialize(report, EdgeProtocol.Json) }); if (device.ConfigJson is null) return null; var task = await RecoveryTaskAsync(db, device, includeSettled: true); return task with { LeaseUntil = DateTimeOffset.UtcNow.AddSeconds(60) }; }); } private static string CertificateHash(X509Certificate2 certificate) { var now = DateTime.UtcNow; Require(now >= certificate.NotBefore.ToUniversalTime() && now < certificate.NotAfter.ToUniversalTime(), "EDGE_DEVICE_FORBIDDEN"); return EdgeProtocol.Digest(certificate.RawData); } private static async Task AuthenticateAsync(ISqlSugarClient db, X509Certificate2 certificate, bool locked) => await db.Ado.SqlQuerySingleAsync(Devices + """ WHERE certificate_hash=@hash AND certificate_expires>UTC_TIMESTAMP(6) AND state='ACTIVE' """ + (locked ? " FOR UPDATE" : ""), new { hash = CertificateHash(certificate) }) ?? throw new EdgeContractException("EDGE_DEVICE_FORBIDDEN"); private X509Certificate2 Sign(string deviceId, string pem) { Require(pem is { Length: > 0 and <= 8192 }, "EDGE_CERT_REQUEST_INVALID"); var path = settings["MdpEdge:CaPfxPath"]; Require(!string.IsNullOrWhiteSpace(path), "EDGE_CA_UNAVAILABLE"); try { using var ca = new X509Certificate2(path!, settings["MdpEdge:CaPfxPassword"], X509KeyStorageFlags.EphemeralKeySet); var loaded = CertificateRequest.LoadSigningRequestPem(pem, HashAlgorithmName.SHA256); using var publicKey = loaded.PublicKey.GetECDsaPublicKey(); Require(publicKey?.KeySize == 256, "EDGE_CERT_REQUEST_INVALID"); var request = new CertificateRequest(new X500DistinguishedName("CN=" + deviceId), loaded.PublicKey, HashAlgorithmName.SHA256); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.2") }, true)); var end = DateTimeOffset.UtcNow.AddDays(Math.Clamp(settings.GetValue("MdpEdge:CertificateDays", 30), 1, 90)); if (end.UtcDateTime > ca.NotAfter.ToUniversalTime()) end = ca.NotAfter.ToUniversalTime(); using var rsa = ca.GetRSAPrivateKey(); using var ec = ca.GetECDsaPrivateKey(); var signature = rsa is not null ? X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1) : ec is not null ? X509SignatureGenerator.CreateForECDsa(ec) : throw new EdgeContractException("EDGE_CA_UNAVAILABLE"); var start = DateTimeOffset.UtcNow.AddSeconds(-10); if (start.UtcDateTime < ca.NotBefore.ToUniversalTime()) start = ca.NotBefore.ToUniversalTime(); return request.Create(ca.SubjectName, signature, start, end, RandomNumberGenerator.GetBytes(20)); } catch (Exception error) when (error is ArgumentException or CryptographicException) { throw new EdgeContractException("EDGE_CERT_REQUEST_INVALID"); } } private static Task UpdateCertificateAsync(ISqlSugarClient db, Device device, X509Certificate2 certificate) => db.Ado.ExecuteCommandAsync(""" UPDATE mdp_edge_device SET state='ACTIVE',activation_hash=NULL,activation_expires=NULL, certificate_hash=@hash,certificate_expires=@expiry WHERE device_id=@DeviceId """, new { device.DeviceId, hash = EdgeProtocol.Digest(certificate.RawData), expiry = certificate.NotAfter.ToUniversalTime() }); private static Task AuditAsync(ISqlSugarClient db, long dataset, long actor, string action, string detail) => db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_release_log(dataset_id,action,actor,detail,created_at) VALUES (@dataset,@action,@actor,@detail,UTC_TIMESTAMP(6)) """, new { dataset, action, actor, detail }); private void RequireEnabled() => Require(settings.GetValue("MdpEdge:Enabled"), "EDGE_DISABLED"); private static string HashText(string value) => EdgeProtocol.Digest(Encoding.UTF8.GetBytes(value)); private static void Require(bool condition, string code) { if (!condition) throw new EdgeContractException(code); } private static async Task Tx(ISqlSugarClient db, Func> run) { var result = await db.Ado.UseTranAsync(run); if (result.IsSuccess) return result.Data; if (result.ErrorException is { } failure) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure); throw new EdgeContractException("EDGE_STORE_UNAVAILABLE"); } private sealed class Device { public string DeviceId { get; set; } = ""; public long TenantId { get; set; } public long FactoryId { get; set; } public long DatasetId { get; set; } public long SourceId { get; set; } public string DeviceName { get; set; } = ""; public string State { get; set; } = ""; public DateTime? ActivationExpires { get; set; } public DateTime? CertificateExpires { get; set; } public string? ConfigJson { get; set; } public long Generation { get; set; } public string? Position { get; set; } public string? Phase { get; set; } public DateTime? SeenAt { get; set; } public string? ReportJson { get; set; } public int PageCount { get; set; } public long RowCount { get; set; } public string? RejectedRawId { get; set; } public string? RejectedDigest { get; set; } } }