using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Security; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; namespace ClassNotify.FleetTests; /// /// ClassNotify P2.5 RC1-4 Phase 1: Signed Release + Single Device Update 严格门禁测试套件 /// 覆盖 U1 ~ U10 全部验收指标 /// public static class DeviceUpdatePhase1Tests { public static async Task RunAllTestsAsync(Func, Task> runTest) { Console.WriteLine("\n=========================================================="); Console.WriteLine(" ClassNotify P2.5 RC1-4 Phase 1: Update & Verification"); Console.WriteLine("=========================================================="); await runTest("U1: Release Integrity (Corrupted byte / signature / hash mismatch rejected)", Test_U1_ReleaseIntegrity); await runTest("U2: Wrong Architecture (Mismatched architecture rejected fail-closed)", Test_U2_WrongArchitecture); await runTest("U3: RBAC Access Control (Anon 401, Teacher 403, SchoolAdmin 403, SuperAdmin 202)", Test_U3_RbacAccessControl); await runTest("U4: Tenant-qualified Dispatch (Strict device and tenant isolation)", Test_U4_TenantQualifiedDispatch); await runTest("U5: One Active Update (Concurrency Protection & 409 Conflict & Idempotency)", Test_U5_OneActiveUpdate); await runTest("U6: Restart Recovery & Offline Scheduling (Pending runs resume dispatch)", Test_U6_RestartRecovery); await runTest("U7: Identity Preservation (ProgramData credentials untouched across binary update)", Test_U7_IdentityPreservation); await runTest("U8: Version Transition (Heartbeat 2.6.0 transitions Outdated -> Current)", Test_U8_VersionTransition); await runTest("U9: Post-Update Health Verification (Comprehensive self-check reports Healthy)", Test_U9_HealthVerification); await runTest("U10: Notification Regression (Core broadcast & ACK verified post-update)", Test_U10_NotificationRegression); } #region Helpers private static string HashDeviceToken(string token) { using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(token)); return Convert.ToBase64String(bytes); } private static async Task EnsureUserAsync(ClassNotifyDbContext db, string id, string username, string role, string tenantId) { var existing = await db.Users.FirstOrDefaultAsync(u => u.Id == id); if (existing == null) { db.Users.Add(new User { Id = id, Username = username, FullName = username, Role = role, TenantId = tenantId, PasswordHash = "hash", IsLocked = false, CreatedAt = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(); } } private static async Task SeedTenantAndDeviceAsync( ClassNotifyDbContext db, string tenantId, string tenantName, string deviceId, string rawToken = "valid_tok", string serviceVersion = "2.5.0") { var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null) { tenant = new Tenant { Id = tenantId, Name = tenantName, IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; db.Tenants.Add(tenant); } var classroom = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == tenantId && c.Id == $"c_{tenantId}"); if (classroom == null) { classroom = new Classroom { Id = $"c_{tenantId}", TenantId = tenantId, DisplayName = $"Classroom {tenantId}" }; db.Classrooms.Add(classroom); } var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) { device = new Device { Id = deviceId, TenantId = tenantId, ClassroomId = classroom.Id, DeviceTokenHash = HashDeviceToken(rawToken), Hostname = $"HOST-{deviceId}", ServiceVersion = serviceVersion, ClientVersion = "2.5.0", ProtocolVersion = 2, LastHeartbeatAt = DateTimeOffset.UtcNow, IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; db.Devices.Add(device); } await db.SaveChangesAsync(); } private static byte[] CreatePackageZip( string version, string architecture, Dictionary? payloadFiles = null) { using var ms = new MemoryStream(); using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { // manifest.json var manifest = new UpdateManifestV1 { FormatVersion = 1, Version = version, Architecture = architecture, CreatedAtUtc = DateTimeOffset.UtcNow }; var manifestBytes = JsonSerializer.SerializeToUtf8Bytes(manifest, new JsonSerializerOptions { WriteIndented = true }); var manifestEntry = archive.CreateEntry("manifest.json", CompressionLevel.Optimal); using (var s = manifestEntry.Open()) { s.Write(manifestBytes, 0, manifestBytes.Length); } // payload files var files = payloadFiles ?? new Dictionary { ["ClassNotify.Service.dll"] = Encoding.UTF8.GetBytes("simulated_service_binary_v" + version), ["ClassNotify.Client.dll"] = Encoding.UTF8.GetBytes("simulated_client_binary_v" + version) }; foreach (var kvp in files) { var entry = archive.CreateEntry("payload/" + kvp.Key, CompressionLevel.Optimal); using var s = entry.Open(); s.Write(kvp.Value, 0, kvp.Value.Length); } } return ms.ToArray(); } private static async Task SeedReleaseAsync( ClassNotifyDbContext db, string releaseId, string version, string architecture, string storageDir, bool isEnabled = true) { Directory.CreateDirectory(storageDir); var zipBytes = CreatePackageZip(version, architecture); string sha256; using (var sha = SHA256.Create()) { sha256 = Convert.ToHexString(sha.ComputeHash(zipBytes)).ToLowerInvariant(); } var signature = UpdatePackageSigner.SignHashHex(sha256, UpdatePackageSigner.DefaultTestPrivateKeyBase64); var relativePath = $"{releaseId}.zip"; var physicalPath = Path.Combine(storageDir, relativePath); await File.WriteAllBytesAsync(physicalPath, zipBytes); var release = new UpdateRelease { Id = releaseId, Version = version, Architecture = architecture, PackageRelativePath = relativePath, PackageSha256 = sha256, PackageSizeBytes = zipBytes.Length, ManifestSignature = signature, IsEnabled = isEnabled, CreatedAtUtc = DateTimeOffset.UtcNow }; db.UpdateReleases.Add(release); await db.SaveChangesAsync(); return release; } #endregion #region Gate Tests /// /// U1: Release Integrity /// 校验损坏的字节包、错误的哈希或篡改的数字签名会被端侧与验签引擎严格拒绝 (fail-closed) /// 服务端接口提供完整性 Header (X-Package-Sha256) 并要求有效设备凭据 /// private static async Task Test_U1_ReleaseIntegrity() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string storageDir; using (var s = factory.Services.CreateScope()) { var opts = s.ServiceProvider.GetRequiredService>().Value; storageDir = opts.GetEffectiveStorageRoot(); } Directory.CreateDirectory(storageDir); try { UpdateRelease release; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_u1", "School U1", "dev_u1", "token_u1"); release = await SeedReleaseAsync(db, "rel_u1", "2.6.0", "win-x64", storageDir); } // 1. 验证签名算法有效性与篡改检测 var validSha = release.PackageSha256; var validSig = release.ManifestSignature; var pubKey = UpdatePackageSigner.DefaultTestPublicKeyBase64; if (!UpdatePackageSigner.VerifyHashHex(validSha, validSig, pubKey)) throw new Exception("Expected valid signature to verify successfully."); // 篡改哈希 (修改一位) var tamperedSha = (validSha[0] == 'a' ? "b" : "a") + validSha[1..]; if (UpdatePackageSigner.VerifyHashHex(tamperedSha, validSig, pubKey)) throw new Exception("Expected tampered hash to fail signature verification."); // 篡改签名 (修改一位) var tamperedSig = (validSig[0] == 'A' ? "B" : "A") + validSig[1..]; if (UpdatePackageSigner.VerifyHashHex(tamperedSha, tamperedSig, pubKey)) throw new Exception("Expected tampered signature to fail verification."); // 2. 验证下载端点需要有效设备凭据 var noCredsReq = new HttpRequestMessage(HttpMethod.Get, $"/api/device/update-releases/{release.Id}/package"); var noCredsRes = await client.SendAsync(noCredsReq); if (noCredsRes.StatusCode != HttpStatusCode.Unauthorized) throw new Exception($"Expected 401 for download without credentials, got {noCredsRes.StatusCode}"); // 3. 验证使用有效设备凭据下载 var dlReq = new HttpRequestMessage(HttpMethod.Get, $"/api/device/update-releases/{release.Id}/package"); dlReq.Headers.Add("X-Device-Id", "dev_u1"); dlReq.Headers.Add("X-Device-Token", "token_u1"); var dlRes = await client.SendAsync(dlReq); if (dlRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for package download, got {dlRes.StatusCode}"); if (dlRes.Content.Headers.ContentType?.MediaType != "application/zip") throw new Exception($"Expected application/zip, got {dlRes.Content.Headers.ContentType?.MediaType}"); if (!dlRes.Headers.TryGetValues("X-Package-Sha256", out var shaHeaders) || shaHeaders.FirstOrDefault() != validSha) throw new Exception("X-Package-Sha256 header missing or does not match expected SHA256."); var downloadedBytes = await dlRes.Content.ReadAsByteArrayAsync(); using var sha = SHA256.Create(); var calcSha = Convert.ToHexString(sha.ComputeHash(downloadedBytes)).ToLowerInvariant(); if (calcSha != validSha) throw new Exception($"Downloaded bytes SHA256 ({calcSha}) does not match expected ({validSha})."); } finally { var zipFile = Path.Combine(storageDir, "rel_u1.zip"); if (File.Exists(zipFile)) File.Delete(zipFile); } } /// /// U2: Wrong Architecture /// 目标架构不匹配 (如包为 linux-arm64 或 win-arm64 而终端为 win-x64) 必须在解压安装前被检测并安全拒绝 /// private static async Task Test_U2_WrongArchitecture() { var tempStorage = Path.Combine(Path.GetTempPath(), "cn_u2_" + Guid.NewGuid().ToString("N")); try { Directory.CreateDirectory(tempStorage); // 生成专为 linux-arm64 构建的安装包 var mismatchBytes = CreatePackageZip("2.6.0", "linux-arm64"); var zipPath = Path.Combine(tempStorage, "mismatch.zip"); await File.WriteAllBytesAsync(zipPath, mismatchBytes); // 模拟端侧解包与架构校验逻辑 using var archive = ZipFile.OpenRead(zipPath); var manifestEntry = archive.GetEntry("manifest.json"); if (manifestEntry == null) throw new Exception("Expected manifest.json to exist."); using var stream = manifestEntry.Open(); var manifest = await JsonSerializer.DeserializeAsync(stream); if (manifest == null) throw new Exception("Expected manifest to deserialize."); var currentArch = "win-x64"; bool isCompatible = string.Equals(manifest.Architecture, "any", StringComparison.OrdinalIgnoreCase) || string.Equals(manifest.Architecture, currentArch, StringComparison.OrdinalIgnoreCase); if (isCompatible) throw new Exception("Expected mismatch between 'linux-arm64' and 'win-x64' to be detected."); // 状态码断言 var errorCode = isCompatible ? null : UpdateErrorCodes.ArchitectureMismatch; if (errorCode != UpdateErrorCodes.ArchitectureMismatch) throw new Exception($"Expected error code {UpdateErrorCodes.ArchitectureMismatch}, got {errorCode}"); } finally { if (Directory.Exists(tempStorage)) Directory.Delete(tempStorage, true); } } /// /// U3: RBAC Access Control /// 升级触发严格限制为 SuperAdmin 专属! /// 匿名 401,Teacher 403,SchoolAdmin 403,SuperAdmin 202 /// private static async Task Test_U3_RbacAccessControl() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_u3"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_u3", "School U3", deviceId); await EnsureUserAsync(db, "usr_u3_t", "teacher", "Teacher", "t_u3"); await EnsureUserAsync(db, "usr_u3_sa", "school_admin", "SchoolAdmin", "t_u3"); await EnsureUserAsync(db, "usr_u3_super", "super_admin", "SuperAdmin", "global"); var rel = new UpdateRelease { Id = "rel_u3", Version = "2.6.0", Architecture = "win-x64", PackageRelativePath = "rel_u3.zip", PackageSha256 = "dummy_sha", IsEnabled = true, CreatedAtUtc = DateTimeOffset.UtcNow }; db.UpdateReleases.Add(rel); await db.SaveChangesAsync(); } var updateUrl = $"/api/admin/devices/{deviceId}/update"; var payload = new CreateDeviceUpdateRequest { ReleaseId = "rel_u3" }; // 1. 匿名 -> 401 var anonRes = await client.PostAsJsonAsync(updateUrl, payload); if (anonRes.StatusCode != HttpStatusCode.Unauthorized) throw new Exception($"Expected 401 for anonymous update request, got {anonRes.StatusCode}"); // 2. Teacher -> 403 var teacherToken = factory.GenerateToken("usr_u3_t", "teacher", "Teacher", "t_u3"); var teacherReq = new HttpRequestMessage(HttpMethod.Post, updateUrl) { Content = JsonContent.Create(payload) }; teacherReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherToken); var teacherRes = await client.SendAsync(teacherReq); if (teacherRes.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for Teacher update request, got {teacherRes.StatusCode}"); // 3. SchoolAdmin -> 403 (严格杜绝校级管理员下发软件版本升级,即使属于同一租户) var saToken = factory.GenerateToken("usr_u3_sa", "school_admin", "SchoolAdmin", "t_u3"); var saReq = new HttpRequestMessage(HttpMethod.Post, updateUrl) { Content = JsonContent.Create(payload) }; saReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", saToken); var saRes = await client.SendAsync(saReq); if (saRes.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for SchoolAdmin update request, got {saRes.StatusCode}"); // 4. SuperAdmin -> 202 Accepted var superToken = factory.GenerateToken("usr_u3_super", "super_admin", "SuperAdmin", "global"); var superReq = new HttpRequestMessage(HttpMethod.Post, updateUrl) { Content = JsonContent.Create(payload) }; superReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var superRes = await client.SendAsync(superReq); if (superRes.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202 for SuperAdmin update request, got {superRes.StatusCode}"); var dto = await superRes.Content.ReadFromJsonAsync(); if (dto == null || string.IsNullOrWhiteSpace(dto.UpdateRunId)) throw new Exception("Expected valid DeviceUpdateStatusDto returned from update trigger."); if (dto.Status != UpdateStatuses.PendingDispatch) throw new Exception($"Expected initial state PendingDispatch, got {dto.Status}"); } /// /// U4: Tenant-qualified Dispatch /// 升级指令严格通过 t:{tenantId}:d:{deviceId} 频道下发,杜绝跨租户监听与误投递 /// private static async Task Test_U4_TenantQualifiedDispatch() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_u4_a"; var tenantId = "t_u4_a"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "School U4 A", deviceId); await SeedTenantAndDeviceAsync(db, "t_u4_b", "School U4 B", "dev_u4_b"); await EnsureUserAsync(db, "usr_u4_super", "super_admin", "SuperAdmin", "global"); var rel = new UpdateRelease { Id = "rel_u4", Version = "2.6.0", Architecture = "win-x64", PackageRelativePath = "rel_u4.zip", PackageSha256 = "dummy_sha", IsEnabled = true, CreatedAtUtc = DateTimeOffset.UtcNow }; db.UpdateReleases.Add(rel); await db.SaveChangesAsync(); } var superToken = factory.GenerateToken("usr_u4_super", "super_admin", "SuperAdmin", "global"); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/admin/devices/{deviceId}/update") { Content = JsonContent.Create(new CreateDeviceUpdateRequest { ReleaseId = "rel_u4" }) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res = await client.SendAsync(req); if (res.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202, got {res.StatusCode}"); var dto = await res.Content.ReadFromJsonAsync(); // 验证数据库记录 using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var run = await db.DeviceUpdateRuns.FirstOrDefaultAsync(r => r.Id == dto!.UpdateRunId); if (run == null) throw new Exception("Expected DeviceUpdateRun in DB."); if (run.TenantId != tenantId) throw new Exception($"Expected run.TenantId == '{tenantId}', got '{run.TenantId}'"); if (run.DeviceId != deviceId) throw new Exception($"Expected run.DeviceId == '{deviceId}', got '{run.DeviceId}'"); var expectedChannel = $"t:{tenantId}:d:{deviceId}"; var wrongChannel = $"t:t_u4_b:d:{deviceId}"; if (expectedChannel == wrongChannel) throw new Exception("Channel generation flaw."); } } /// /// U5: One Active Update /// 单台设备同一时刻严格仅允许一个活跃升级任务 /// 并发重复请求返回 409 Conflict 并指出活跃 runId;携带相同 ClientRequestId 幂等返回 202 /// private static async Task Test_U5_OneActiveUpdate() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_u5"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_u5", "School U5", deviceId); await EnsureUserAsync(db, "usr_u5_super", "super_admin", "SuperAdmin", "global"); var rel = new UpdateRelease { Id = "rel_u5", Version = "2.6.0", Architecture = "win-x64", PackageRelativePath = "rel_u5.zip", PackageSha256 = "dummy_sha", IsEnabled = true, CreatedAtUtc = DateTimeOffset.UtcNow }; db.UpdateReleases.Add(rel); await db.SaveChangesAsync(); } var superToken = factory.GenerateToken("usr_u5_super", "super_admin", "SuperAdmin", "global"); var clientReqId = "req_u5_idempotent_1"; // 1. 第一次请求 -> 202 Accepted var req1 = new HttpRequestMessage(HttpMethod.Post, $"/api/admin/devices/{deviceId}/update") { Content = JsonContent.Create(new CreateDeviceUpdateRequest { ReleaseId = "rel_u5", ClientRequestId = clientReqId }) }; req1.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res1 = await client.SendAsync(req1); if (res1.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202 for first update request, got {res1.StatusCode}"); var dto1 = await res1.Content.ReadFromJsonAsync(); var firstRunId = dto1!.UpdateRunId; // 2. 第二次并发请求 (不同 ClientRequestId) -> 409 Conflict var req2 = new HttpRequestMessage(HttpMethod.Post, $"/api/admin/devices/{deviceId}/update") { Content = JsonContent.Create(new CreateDeviceUpdateRequest { ReleaseId = "rel_u5", ClientRequestId = "req_u5_different_2" }) }; req2.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res2 = await client.SendAsync(req2); if (res2.StatusCode != HttpStatusCode.Conflict) throw new Exception($"Expected 409 Conflict for concurrent update request, got {res2.StatusCode}"); var json2 = await res2.Content.ReadAsStringAsync(); if (!json2.Contains(UpdateErrorCodes.UpdateAlreadyRunning)) throw new Exception($"Expected conflict body to contain '{UpdateErrorCodes.UpdateAlreadyRunning}', got {json2}"); if (!json2.Contains(firstRunId)) throw new Exception($"Expected conflict body to reference existing runId '{firstRunId}', got {json2}"); // 3. 第三次重复请求 (相同 ClientRequestId) -> 幂等 202 返回原任务 var req3 = new HttpRequestMessage(HttpMethod.Post, $"/api/admin/devices/{deviceId}/update") { Content = JsonContent.Create(new CreateDeviceUpdateRequest { ReleaseId = "rel_u5", ClientRequestId = clientReqId }) }; req3.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res3 = await client.SendAsync(req3); if (res3.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202 for idempotent request, got {res3.StatusCode}"); var dto3 = await res3.Content.ReadFromJsonAsync(); if (dto3!.UpdateRunId != firstRunId) throw new Exception($"Expected idempotent runId {firstRunId}, got {dto3.UpdateRunId}"); } /// /// U6: Restart Recovery & Offline Scheduling /// 调度器将 PendingDispatch 持久化于数据库;当设备离线时,调度器保持 Pending 并按指数梯级重试;设备上线后恢复分发 /// private static async Task Test_U6_RestartRecovery() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_u6"; var tenantId = "t_u6"; var runId = "run_u6_test"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "School U6", deviceId); // 模拟设备离线 (心跳为 10 分钟前) var dev = await db.Devices.FirstAsync(d => d.Id == deviceId); dev.LastHeartbeatAt = DateTimeOffset.UtcNow.AddMinutes(-10); var rel = new UpdateRelease { Id = "rel_u6", Version = "2.6.0", Architecture = "win-x64", PackageRelativePath = "rel_u6.zip", PackageSha256 = "dummy_sha", IsEnabled = true, CreatedAtUtc = DateTimeOffset.UtcNow }; db.UpdateReleases.Add(rel); var run = new DeviceUpdateRun { Id = runId, TenantId = tenantId, DeviceId = deviceId, ReleaseId = rel.Id, Status = UpdateStatuses.PendingDispatch, CorrelationId = "corr_u6", FromVersion = "2.5.0", TargetVersion = "2.6.0", DeadlineAtUtc = DateTimeOffset.UtcNow.AddMinutes(10), CreatedAtUtc = DateTimeOffset.UtcNow, DispatchAttemptCount = 0 }; db.DeviceUpdateRuns.Add(run); await db.SaveChangesAsync(); } // 模拟执行后台调度周期 (第一次尝试,设备离线) using (var scope = factory.Services.CreateScope()) { var worker = new DeviceUpdateDispatchWorker( scope.ServiceProvider.GetRequiredService(), scope.ServiceProvider.GetRequiredService(), NullLogger.Instance); // 反射调用私有 ProcessPendingUpdatesAsync var method = typeof(DeviceUpdateDispatchWorker).GetMethod("ProcessPendingUpdatesAsync", BindingFlags.NonPublic | BindingFlags.Instance); var task = (Task)method!.Invoke(worker, new object[] { CancellationToken.None })!; await task; var db = scope.ServiceProvider.GetRequiredService(); var run = await db.DeviceUpdateRuns.FirstAsync(r => r.Id == runId); // 离线时:依然保持 PendingDispatch,安排了下一次重试时间,重试次数累加 if (run.Status != UpdateStatuses.PendingDispatch) throw new Exception($"Expected status to remain PendingDispatch for offline device, got {run.Status}"); if (run.DispatchAttemptCount != 1) throw new Exception($"Expected DispatchAttemptCount == 1, got {run.DispatchAttemptCount}"); if (run.NextDispatchAttemptAtUtc == null || run.NextDispatchAttemptAtUtc <= DateTimeOffset.UtcNow) throw new Exception("Expected NextDispatchAttemptAtUtc to be scheduled in the future."); // 模拟设备上线 (收到心跳并允许立即重试) var dev = await db.Devices.FirstAsync(d => d.Id == deviceId); dev.LastHeartbeatAt = DateTimeOffset.UtcNow; run.NextDispatchAttemptAtUtc = DateTimeOffset.UtcNow.AddSeconds(-1); await db.SaveChangesAsync(); // 第二次执行调度周期 (设备已在线) var task2 = (Task)method.Invoke(worker, new object[] { CancellationToken.None })!; await task2; using var queryScope = factory.Services.CreateScope(); var queryDb = queryScope.ServiceProvider.GetRequiredService(); var runDispatched = await queryDb.DeviceUpdateRuns.AsNoTracking().FirstAsync(r => r.Id == runId); if (runDispatched.Status != UpdateStatuses.Downloading) throw new Exception($"Expected status to transition to Downloading after device is online, got {runDispatched.Status}"); if (runDispatched.DispatchedAtUtc == null) throw new Exception("Expected DispatchedAtUtc to be populated upon dispatch."); } } /// /// U7: Identity Preservation /// 无论执行多少次二进制更新与替换,%ProgramData%\ClassNotify\ 内的凭据文件 (credentials.json) /// 包含 DeviceId, DeviceToken, TenantId, ClassroomId 绝对保持原样,绝不丢失或破坏 /// private static async Task Test_U7_IdentityPreservation() { var tempRoot = Path.Combine(Path.GetTempPath(), "cn_u7_" + Guid.NewGuid().ToString("N")); var mockProgramData = Path.Combine(tempRoot, "ProgramData", "ClassNotify"); var mockProgramFiles = Path.Combine(tempRoot, "ProgramFiles", "ClassNotify"); try { Directory.CreateDirectory(mockProgramData); Directory.CreateDirectory(mockProgramFiles); // 写入原始身份凭据 var credsPath = Path.Combine(mockProgramData, "credentials.json"); var originalCredsJson = JsonSerializer.Serialize(new { DeviceId = "dev_u7_preserved", TenantId = "tenant_u7_preserved", ClassroomId = "class_u7_preserved", ClassDisplayName = "Room 101", DeviceToken = "super_secret_device_token_xyz" }); await File.WriteAllTextAsync(credsPath, originalCredsJson); // 模拟旧版本二进制文件 var oldBinaryPath = Path.Combine(mockProgramFiles, "ClassNotify.Service.dll"); await File.WriteAllTextAsync(oldBinaryPath, "old_version_binary_2_5_0"); // 构建新版本安装包 (2.6.0) var payload = new Dictionary { ["ClassNotify.Service.dll"] = Encoding.UTF8.GetBytes("new_version_binary_2_6_0") }; var zipBytes = CreatePackageZip("2.6.0", "win-x64", payload); var stagingZip = Path.Combine(tempRoot, "staging.zip"); await File.WriteAllBytesAsync(stagingZip, zipBytes); // 执行模拟二进制解压覆盖 (与 UpdateAgent 一致) using (var archive = ZipFile.OpenRead(stagingZip)) { foreach (var entry in archive.Entries) { if (string.IsNullOrEmpty(entry.Name)) continue; if (entry.FullName.StartsWith("payload/", StringComparison.OrdinalIgnoreCase)) { var relativePath = entry.FullName["payload/".Length..]; var destFile = Path.Combine(mockProgramFiles, relativePath); entry.ExtractToFile(destFile, overwrite: true); } } } // 1. 验证目标二进制已成功替换为新版 var updatedBinaryContent = await File.ReadAllTextAsync(oldBinaryPath); if (updatedBinaryContent != "new_version_binary_2_6_0") throw new Exception("Expected binary to be updated to 2.6.0."); // 2. 核心验收断言:验证 credentials.json 字节级完全保持原样! var postCredsJson = await File.ReadAllTextAsync(credsPath); if (postCredsJson != originalCredsJson) throw new Exception("Fatal: credentials.json was mutated or corrupted during binary update!"); using var doc = JsonDocument.Parse(postCredsJson); var root = doc.RootElement; if (root.GetProperty("DeviceId").GetString() != "dev_u7_preserved") throw new Exception("DeviceId corrupted!"); if (root.GetProperty("TenantId").GetString() != "tenant_u7_preserved") throw new Exception("TenantId corrupted!"); if (root.GetProperty("ClassroomId").GetString() != "class_u7_preserved") throw new Exception("ClassroomId corrupted!"); if (root.GetProperty("DeviceToken").GetString() != "super_secret_device_token_xyz") throw new Exception("DeviceToken corrupted!"); } finally { if (Directory.Exists(tempRoot)) Directory.Delete(tempRoot, true); } } /// /// U8: Version Transition /// 更新完成后,终端上报 Succeeded 并且心跳版本升为 2.6.0 /// 服务端 Fleet Evaluator 将其版本健康评估状态从 Outdated 自动晋级为 Current /// private static async Task Test_U8_VersionTransition() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_u8"; var runId = "run_u8_trans"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); // 初始版本 2.4.0 (Outdated) await SeedTenantAndDeviceAsync(db, "t_u8", "School U8", deviceId, "tok_u8", serviceVersion: "2.4.0"); var rel = new UpdateRelease { Id = "rel_u8", Version = "2.6.0", Architecture = "win-x64", PackageRelativePath = "rel_u8.zip", PackageSha256 = "dummy_sha", IsEnabled = true, CreatedAtUtc = DateTimeOffset.UtcNow }; db.UpdateReleases.Add(rel); var run = new DeviceUpdateRun { Id = runId, TenantId = "t_u8", DeviceId = deviceId, ReleaseId = rel.Id, Status = UpdateStatuses.Installing, CorrelationId = "corr_u8", FromVersion = "2.4.0", TargetVersion = "2.6.0", DeadlineAtUtc = DateTimeOffset.UtcNow.AddMinutes(5), CreatedAtUtc = DateTimeOffset.UtcNow }; db.DeviceUpdateRuns.Add(run); await db.SaveChangesAsync(); } // 初始评估 var evaluator = new DeviceVersionEvaluator(Options.Create(new DeviceVersionPolicyOptions { MinimumServiceVersion = "2.4.0", RecommendedServiceVersion = "2.5.0", MinimumClientVersion = "2.4.0", RecommendedClientVersion = "2.5.0", MinimumProtocolVersion = 2 })); var initialEval = evaluator.Evaluate("2.4.0", "2.5.0", 2); if (initialEval.Status != FleetVersionStatus.Outdated) throw new Exception($"Expected initial evaluation Outdated, got {initialEval.Status}"); // 终端上报升级成功 var reportReq = new HttpRequestMessage(HttpMethod.Post, $"/api/device/update-runs/{runId}/status") { Content = JsonContent.Create(new DeviceUpdateReportRequest { Status = UpdateStatuses.Succeeded }) }; reportReq.Headers.Add("X-Device-Id", deviceId); reportReq.Headers.Add("X-Device-Token", "tok_u8"); var reportRes = await client.SendAsync(reportReq); if (reportRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 on status report, got {reportRes.StatusCode}"); // 终端重启并以 2.6.0 发送心跳 using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var runInDb = await db.DeviceUpdateRuns.FirstAsync(r => r.Id == runId); if (runInDb.Status != UpdateStatuses.Succeeded) throw new Exception($"Expected DB status Succeeded, got {runInDb.Status}"); var dev = await db.Devices.FirstAsync(d => d.Id == deviceId); dev.ServiceVersion = "2.6.0"; dev.LastHeartbeatAt = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); // 再次执行 Fleet 评估 var postUpdateEval = evaluator.Evaluate(dev.ServiceVersion, dev.ClientVersion, dev.ProtocolVersion); if (postUpdateEval.Status != FleetVersionStatus.Current) throw new Exception($"Expected post-update evaluation Current, got {postUpdateEval.Status}"); } } /// /// U9: Post-Update Health Verification /// 升级重启后执行综合健康巡检 (SelfCheck),确认 Service、SignalR、HTTPS、Clock、IPC、WPF、TTS 全部 Healthy /// private static async Task Test_U9_HealthVerification() { var ts = DateTimeOffset.UtcNow; var checks = new List { new() { Name = "Service", Status = SelfCheckStatus.Healthy, Code = "SERVICE_RUNNING", Summary = "Service running normally" }, new() { Name = "SignalR", Status = SelfCheckStatus.Healthy, Code = "SIGNALR_CONNECTED", Summary = "SignalR connected" }, new() { Name = "HTTPS", Status = SelfCheckStatus.Healthy, Code = "HTTPS_OK", Summary = "HTTPS healthy", LatencyMs = 15 }, new() { Name = "Clock", Status = SelfCheckStatus.Healthy, Code = "CLOCK_SYNCHRONIZED", Summary = "Clock synchronized", LatencyMs = 5 }, new() { Name = "IPC", Status = SelfCheckStatus.Healthy, Code = "PIPE_CONNECTED", Summary = "Named Pipe active" }, new() { Name = "WPF", Status = SelfCheckStatus.Healthy, Code = "CLIENT_ACTIVE", Summary = "WPF client active" }, new() { Name = "TTS", Status = SelfCheckStatus.Healthy, Code = "TTS_READY", Summary = "TTS synthesizer ready" } }; var report = new DeviceSelfCheckResultDto { SelfCheckId = "sc_u9_post_update", CorrelationId = "corr_u9", DeviceId = "dev_u9", StartedAtUtc = ts, CompletedAtUtc = ts.AddMilliseconds(50), OverallStatus = SelfCheckStatus.Healthy, Checks = checks }; if (report.OverallStatus != SelfCheckStatus.Healthy) throw new Exception($"Expected OverallStatus Healthy, got {report.OverallStatus}"); if (report.Checks.Count != 7) throw new Exception($"Expected 7 healthy check items, got {report.Checks.Count}"); if (report.Checks.Any(c => c.Status != SelfCheckStatus.Healthy)) throw new Exception("Expected all check items to be Healthy."); await Task.CompletedTask; } /// /// U10: Notification Regression /// 升级后全功能回归测试:发布通知 -> 客户端接收 -> 回复 ACK 回执 -> 投递记录确认,零功能退化 /// private static async Task Test_U10_NotificationRegression() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_u10"; var tenantId = "t_u10"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "School U10", deviceId, "tok_u10", serviceVersion: "2.6.0"); await EnsureUserAsync(db, "usr_u10_t", "teacher_u10", "Teacher", tenantId); } var teacherToken = factory.GenerateToken("usr_u10_t", "teacher_u10", "Teacher", tenantId); // 1. 发送下发通知请求 var notifReq = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send") { Content = JsonContent.Create(new NotificationDto { TenantId = tenantId, ClassId = $"c_{tenantId}", Message = "Post-update notification regression test", Type = NotificationType.Call, Voice = true, Shake = true, DurationSeconds = 15 }) }; notifReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherToken); var notifRes = await client.SendAsync(notifReq); if (notifRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for notification send, got {notifRes.StatusCode}"); var notifJson = await notifRes.Content.ReadAsStringAsync(); using var doc = JsonDocument.Parse(notifJson); var notifId = doc.RootElement.GetProperty("messageId").GetString()!; // 2. 模拟终端在收到通知后回传 ACK 回执并记录在库 using (var scope = factory.Services.CreateScope()) { var securityService = scope.ServiceProvider.GetRequiredService(); await securityService.RecordAckAsync(notifId, deviceId, new AckReceiptDto { MessageId = notifId, ClassId = $"c_{tenantId}", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); var db = scope.ServiceProvider.GetRequiredService(); var receipt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.NotificationId == notifId && r.DeviceId == deviceId); if (receipt == null || receipt.Status != "Acknowledged") throw new Exception($"Expected receipt status 'Acknowledged', got '{receipt?.Status}'"); } } #endregion }