using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace ClassNotify.FleetTests; /// /// ClassNotify P2.5 RC1-3 Phase 1: Data Model & Server Skeleton 严格门禁测试套件 /// 覆盖 P1-1 ~ P1-10 全部验收指标 (SB4 依规范明确留待 Phase 2) /// public static class SupportBundlePhase1Tests { public static async Task RunAllTestsAsync(Func, Task> runTest) { Console.WriteLine("\n=========================================================="); Console.WriteLine(" ClassNotify P2.5 RC1-3 Phase 1: Support Bundle Gate Suite"); Console.WriteLine("=========================================================="); await runTest("P1-1: Migration & Schema (Table, FKs, Indexes, Status CHECK, Active Partial Unique)", Test_P1_1_Migration); await runTest("P1-2: Authorization (Anon 401, Teacher 403, SchoolAdmin Cross-Tenant 403, Same-Tenant 202, SuperAdmin 202)", Test_P1_2_Authorization); await runTest("P1-3: Transaction Audit (Atomic audit insert & rollback guarantee on audit failure)", Test_P1_3_TransactionAudit); await runTest("P1-4: Sequential Idempotency (Same ClientRequestId returns same Bundle, 1 DB row, 1 audit)", Test_P1_4_SequentialIdempotency); await runTest("P1-5: Concurrent Idempotency (Parallel WhenAll double-click -> same Bundle, 1 DB row, 0 HTTP 500)", Test_P1_5_ConcurrentIdempotency); await runTest("P1-6: One Active Bundle (Same device concurrent/duplicate -> 1x 202, 1x 409 SupportBundleAlreadyRunning)", Test_P1_6_OneActiveBundle); await runTest("P1-7: Tenant Isolation (Only t:{tenantId}:d:{deviceId} receives command; cross-tenant 0)", Test_P1_7_TenantIsolation); await runTest("P1-8: Offline Truthfulness (Offline stays PendingDispatch, backoff retry, past deadline -> TimedOut, no fake state)", Test_P1_8_OfflineTruthfulness); await runTest("P1-9: Restart Recovery (PendingDispatch survives server restart and resumes dispatch to Collecting)", Test_P1_9_RestartRecovery); await runTest("P1-10: No Premature Storage (StoragePath/Sha256/SizeBytes/ExpiresAtUtc == null, 0 ZIP files generated)", Test_P1_10_NoPrematureStorage); Console.WriteLine(" [INFO] SB4 (Device Upload Authorization) is deferred to Phase 2 per specification."); } private static async Task EnsureUserAsync(ClassNotifyDbContext db, string userId, string username, string role, string tenantId) { var existing = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (existing == null) { db.Users.Add(new User { Id = userId, Username = username, FullName = username, Role = role, TenantId = tenantId, PasswordHash = "hash", IsLocked = false, TokenVersion = 1 }); await db.SaveChangesAsync(); } } /// /// P1-1: 验证 Migration 与 Schema 完整性约束 /// private static async Task Test_P1_1_Migration() { using var factory = new CustomWebApplicationFactory(); using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // 使用 DesignTimeModel 获取包含关系型元数据 (Filter, CheckConstraints 等) 的完整模型 var designTimeModel = db.GetService().Model; var entityType = designTimeModel.FindEntityType(typeof(DeviceSupportBundle)); if (entityType == null) throw new Exception("DeviceSupportBundle entity not found in EF model"); // 1. Primary Key var pk = entityType.FindPrimaryKey(); if (pk == null || pk.Properties.Count != 1 || pk.Properties[0].Name != nameof(DeviceSupportBundle.Id)) throw new Exception("DeviceSupportBundle must have Id as primary key"); // 2. Foreign Keys var fks = entityType.GetForeignKeys().ToList(); var tenantFk = fks.FirstOrDefault(f => f.PrincipalEntityType.ClrType == typeof(Tenant)); var deviceFk = fks.FirstOrDefault(f => f.PrincipalEntityType.ClrType == typeof(Device)); if (tenantFk == null) throw new Exception("Missing foreign key to Tenant"); if (deviceFk == null) throw new Exception("Missing foreign key to Device"); // 3. Indexes var indexes = entityType.GetIndexes().ToList(); // (RequestedByUserId, ClientRequestId) UNIQUE var reqIndex = indexes.FirstOrDefault(i => i.IsUnique && i.Properties.Count == 2 && i.Properties.Any(p => p.Name == nameof(DeviceSupportBundle.RequestedByUserId)) && i.Properties.Any(p => p.Name == nameof(DeviceSupportBundle.ClientRequestId))); if (reqIndex == null) throw new Exception("Missing unique index on (RequestedByUserId, ClientRequestId)"); // Partial Unique Index: DeviceId where Status IN ('PendingDispatch', 'Collecting') var activeIndex = indexes.FirstOrDefault(i => i.IsUnique && i.Properties.Count == 1 && i.Properties[0].Name == nameof(DeviceSupportBundle.DeviceId) && i.GetFilter() != null && i.GetFilter()!.Contains("PendingDispatch") && i.GetFilter()!.Contains("Collecting")); if (activeIndex == null) throw new Exception("Missing active partial unique index on DeviceId"); // Status check constraint var checkConstraints = entityType.GetCheckConstraints().ToList(); var statusCheck = checkConstraints.FirstOrDefault(c => c.Name == "CK_DeviceSupportBundles_Status"); if (statusCheck == null) throw new Exception("Missing CK_DeviceSupportBundles_Status check constraint"); // 4. Check schema.sql var schemaPath = Path.Combine(Directory.GetCurrentDirectory(), "schema.sql"); if (!File.Exists(schemaPath)) { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir != null && !File.Exists(Path.Combine(dir.FullName, "ClassNotify.sln"))) { dir = dir.Parent; } if (dir != null) schemaPath = Path.Combine(dir.FullName, "schema.sql"); } if (File.Exists(schemaPath)) { var sqlContent = await File.ReadAllTextAsync(schemaPath); if (!sqlContent.Contains("\"DeviceSupportBundles\"")) throw new Exception("schema.sql does not contain DeviceSupportBundles table definition"); if (!sqlContent.Contains("UX_DeviceSupportBundles_Device_Active")) throw new Exception("schema.sql does not contain UX_DeviceSupportBundles_Device_Active index"); if (!sqlContent.Contains("CK_DeviceSupportBundles_Status")) throw new Exception("schema.sql does not contain CK_DeviceSupportBundles_Status check constraint"); } } /// /// P1-2: 验证端到端权限校验 (Anon 401, Teacher 403, SchoolAdmin Cross-Tenant 403, Same-Tenant 202, SuperAdmin 202) /// private static async Task Test_P1_2_Authorization() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p12_school_a", Name = "学校A", IsActive = true }); db.Tenants.Add(new Tenant { Id = "t_p12_school_b", Name = "学校B", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p12_1", TenantId = "t_p12_school_a", DisplayName = "班级1" }); db.Devices.Add(new Device { Id = "dev_p12_a", TenantId = "t_p12_school_a", ClassroomId = "c_p12_1", DeviceTokenHash = "hash_12", IsActive = true }); await EnsureUserAsync(db, "usr_teacher", "teacher1", "Teacher", "t_p12_school_a"); await EnsureUserAsync(db, "usr_admin_b", "admin_b", "SchoolAdmin", "t_p12_school_b"); await EnsureUserAsync(db, "usr_admin_a", "admin_a", "SchoolAdmin", "t_p12_school_a"); await EnsureUserAsync(db, "usr_super", "superadmin", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var req = new CreateSupportBundleRequest { ClientRequestId = "req_p12_anon" }; // 1. Anonymous -> 401 client.DefaultRequestHeaders.Authorization = null; var anonResp = await client.PostAsJsonAsync("/api/admin/devices/dev_p12_a/support-bundles", req); if (anonResp.StatusCode != HttpStatusCode.Unauthorized) throw new Exception($"Expected 401 for anonymous, got {anonResp.StatusCode}"); // 2. Teacher -> 403 var teacherToken = factory.GenerateToken("usr_teacher", "teacher1", "Teacher", "t_p12_school_a"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", teacherToken); req.ClientRequestId = "req_p12_teacher"; var teacherResp = await client.PostAsJsonAsync("/api/admin/devices/dev_p12_a/support-bundles", req); if (teacherResp.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for Teacher, got {teacherResp.StatusCode}"); // 3. SchoolAdmin 异校 -> 403 var crossAdminToken = factory.GenerateToken("usr_admin_b", "admin_b", "SchoolAdmin", "t_p12_school_b"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", crossAdminToken); req.ClientRequestId = "req_p12_cross"; var crossResp = await client.PostAsJsonAsync("/api/admin/devices/dev_p12_a/support-bundles", req); if (crossResp.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for SchoolAdmin from different school, got {crossResp.StatusCode}"); // 4. SchoolAdmin 同校 -> 202 var sameAdminToken = factory.GenerateToken("usr_admin_a", "admin_a", "SchoolAdmin", "t_p12_school_a"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sameAdminToken); req.ClientRequestId = "req_p12_same"; var sameResp = await client.PostAsJsonAsync("/api/admin/devices/dev_p12_a/support-bundles", req); if (sameResp.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202 for SchoolAdmin of same school, got {sameResp.StatusCode}"); // 5. SuperAdmin -> 202 (for device in School A, with another clientRequestId after clearing active) using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var active = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.DeviceId == "dev_p12_a"); if (active != null) { active.Status = SupportBundleStatuses.TimedOut; // Clear active state await db.SaveChangesAsync(); } } var superToken = factory.GenerateToken("usr_super", "superadmin", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", superToken); req.ClientRequestId = "req_p12_super"; var superResp = await client.PostAsJsonAsync("/api/admin/devices/dev_p12_a/support-bundles", req); if (superResp.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202 for SuperAdmin, got {superResp.StatusCode}"); } /// /// P1-3: 验证事务原子性与审计落库,审计失败触发完全回滚 /// private static async Task Test_P1_3_TransactionAudit() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p13", Name = "学校P13", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p13", TenantId = "t_p13", DisplayName = "班级P13" }); db.Devices.Add(new Device { Id = "dev_p13_1", TenantId = "t_p13", ClassroomId = "c_p13", DeviceTokenHash = "hash", IsActive = true }); db.Devices.Add(new Device { Id = "dev_p13_2", TenantId = "t_p13", ClassroomId = "c_p13", DeviceTokenHash = "hash", IsActive = true }); await EnsureUserAsync(db, "usr_super", "admin", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var token = factory.GenerateToken("usr_super", "admin", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); // 1. 正常请求:1 Bundle + 1 Audit var reqNormal = new CreateSupportBundleRequest { ClientRequestId = "req_p13_normal" }; var respNormal = await client.PostAsJsonAsync("/api/admin/devices/dev_p13_1/support-bundles", reqNormal); if (respNormal.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Expected 202, got {respNormal.StatusCode}"); var created = await respNormal.Content.ReadFromJsonAsync(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundle = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == created!.SupportBundleId); if (bundle == null) throw new Exception("DeviceSupportBundle record missing in database"); var audit = await db.AdminAuditEvents.FirstOrDefaultAsync(a => a.TargetId == created!.SupportBundleId); if (audit == null || audit.Action != "SUPPORT_BUNDLE_REQUESTED") throw new Exception("SUPPORT_BUNDLE_REQUESTED audit event missing from database"); } // 2. 故意让 Audit 失败:0 Bundle + 0 Audit (原子回滚) var clientWithFailure = factory.CreateClient(); clientWithFailure.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); clientWithFailure.DefaultRequestHeaders.Add("X-Simulate-Audit-Failure", "true"); var reqFail = new CreateSupportBundleRequest { ClientRequestId = "req_p13_sim_fail" }; var respFail = await clientWithFailure.PostAsJsonAsync("/api/admin/devices/dev_p13_2/support-bundles", reqFail); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundleCount = await db.DeviceSupportBundles.CountAsync(b => b.ClientRequestId == "req_p13_sim_fail"); var auditCount = await db.AdminAuditEvents.CountAsync(a => a.Details != null && a.Details.Contains("req_p13_sim_fail")); if (bundleCount != 0 || auditCount != 0) { throw new Exception($"Rollback failed: expected 0 bundles and 0 audits, found {bundleCount} bundles and {auditCount} audits"); } } } /// /// P1-4: 验证同一用户相同 ClientRequestId 顺序请求返回同一 BundleId,仅产生 1 行记录 /// private static async Task Test_P1_4_SequentialIdempotency() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p14", Name = "学校P14", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p14", TenantId = "t_p14", DisplayName = "班级P14" }); db.Devices.Add(new Device { Id = "dev_p14", TenantId = "t_p14", ClassroomId = "c_p14", DeviceTokenHash = "hash", IsActive = true }); await EnsureUserAsync(db, "usr_super", "seq_user", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var token = factory.GenerateToken("usr_super", "seq_user", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var req = new CreateSupportBundleRequest { ClientRequestId = "req_p14_idempotent_fixed" }; var resp1 = await client.PostAsJsonAsync("/api/admin/devices/dev_p14/support-bundles", req); if (resp1.StatusCode != HttpStatusCode.Accepted) throw new Exception("First request failed"); var dto1 = await resp1.Content.ReadFromJsonAsync(); var resp2 = await client.PostAsJsonAsync("/api/admin/devices/dev_p14/support-bundles", req); if (resp2.StatusCode != HttpStatusCode.Accepted) throw new Exception("Second idempotent request failed"); var dto2 = await resp2.Content.ReadFromJsonAsync(); if (dto1!.SupportBundleId != dto2!.SupportBundleId) throw new Exception($"Idempotency violated: {dto1.SupportBundleId} != {dto2.SupportBundleId}"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var rows = await db.DeviceSupportBundles.CountAsync(b => b.ClientRequestId == "req_p14_idempotent_fixed"); if (rows != 1) throw new Exception($"Expected exactly 1 row in DB, found {rows}"); var audits = await db.AdminAuditEvents.CountAsync(a => a.TargetId == dto1.SupportBundleId); if (audits != 1) throw new Exception($"Expected exactly 1 audit event, found {audits}"); } } /// /// P1-5: 验证高并发 Task.WhenAll 并发双击/重试幂等,返回同一 Bundle,无 500 异常 /// private static async Task Test_P1_5_ConcurrentIdempotency() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p15", Name = "学校P15", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p15", TenantId = "t_p15", DisplayName = "班级P15" }); db.Devices.Add(new Device { Id = "dev_p15", TenantId = "t_p15", ClassroomId = "c_p15", DeviceTokenHash = "hash", IsActive = true }); await EnsureUserAsync(db, "usr_super", "conc_user", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var token = factory.GenerateToken("usr_super", "conc_user", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var req = new CreateSupportBundleRequest { ClientRequestId = "req_p15_concurrent_fixed" }; var tasks = Enumerable.Range(1, 6).Select(_ => client.PostAsJsonAsync("/api/admin/devices/dev_p15/support-bundles", req) ).ToArray(); var responses = await Task.WhenAll(tasks); foreach (var r in responses) { if (r.StatusCode != HttpStatusCode.Accepted) { var body = await r.Content.ReadAsStringAsync(); throw new Exception($"Concurrent request returned unexpected status {r.StatusCode}: {body}"); } } var dtos = new List(); foreach (var r in responses) { var dto = await r.Content.ReadFromJsonAsync(); dtos.Add(dto!); } var distinctIds = dtos.Select(d => d.SupportBundleId).Distinct().ToList(); if (distinctIds.Count != 1) throw new Exception($"Concurrent idempotency broken: got {distinctIds.Count} different IDs"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var rows = await db.DeviceSupportBundles.CountAsync(b => b.ClientRequestId == "req_p15_concurrent_fixed"); if (rows != 1) throw new Exception($"Expected 1 bundle row in DB, found {rows}"); var audits = await db.AdminAuditEvents.CountAsync(a => a.TargetId == distinctIds[0]); if (audits != 1) throw new Exception($"Expected 1 audit row in DB, found {audits}"); } } /// /// P1-6: 验证同一设备单 Active 互斥规则 (不同 ClientRequestId 请求同一设备 -> 1x 202, 1x 409) /// private static async Task Test_P1_6_OneActiveBundle() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p16", Name = "学校P16", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p16", TenantId = "t_p16", DisplayName = "班级P16" }); db.Devices.Add(new Device { Id = "dev_p16_exclusive", TenantId = "t_p16", ClassroomId = "c_p16", DeviceTokenHash = "hash", IsActive = true }); await EnsureUserAsync(db, "usr_super", "admin", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var token = factory.GenerateToken("usr_super", "admin", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); // 第一个请求 var req1 = new CreateSupportBundleRequest { ClientRequestId = "req_p16_first" }; var resp1 = await client.PostAsJsonAsync("/api/admin/devices/dev_p16_exclusive/support-bundles", req1); if (resp1.StatusCode != HttpStatusCode.Accepted) throw new Exception($"First request failed with {resp1.StatusCode}"); var dto1 = await resp1.Content.ReadFromJsonAsync(); // 第二个不同请求指向同一设备 (当前第一个处于 PendingDispatch) var req2 = new CreateSupportBundleRequest { ClientRequestId = "req_p16_second" }; var resp2 = await client.PostAsJsonAsync("/api/admin/devices/dev_p16_exclusive/support-bundles", req2); if (resp2.StatusCode != HttpStatusCode.Conflict) { var content = await resp2.Content.ReadAsStringAsync(); throw new Exception($"Expected 409 Conflict for second concurrent request on same device, got {resp2.StatusCode}: {content}"); } var conflictJson = await resp2.Content.ReadAsStringAsync(); using var doc = JsonDocument.Parse(conflictJson); var errorCode = doc.RootElement.GetProperty("errorCode").GetString(); var runningBundleId = doc.RootElement.GetProperty("supportBundleId").GetString(); if (errorCode != "SupportBundleAlreadyRunning") throw new Exception($"Expected errorCode 'SupportBundleAlreadyRunning', got '{errorCode}'"); if (runningBundleId != dto1!.SupportBundleId) throw new Exception($"Conflict did not point to the running bundle: {runningBundleId} != {dto1.SupportBundleId}"); } /// /// P1-7 / SB2: 验证租户物理隔离分发通道 (仅目标 t:{tenantId}:d:{deviceId} 接收命令) /// private static async Task Test_P1_7_TenantIsolation() { using var factory = new CustomWebApplicationFactory(); using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "tenant_iso_a", Name = "学校A", IsActive = true }); db.Tenants.Add(new Tenant { Id = "tenant_iso_b", Name = "学校B", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_iso_a", TenantId = "tenant_iso_a", DisplayName = "班级A" }); db.Classrooms.Add(new Classroom { Id = "c_iso_b", TenantId = "tenant_iso_b", DisplayName = "班级B" }); db.Devices.Add(new Device { Id = "dev_iso_target", TenantId = "tenant_iso_a", ClassroomId = "c_iso_a", DeviceTokenHash = "hash_a", IsActive = true }); db.Devices.Add(new Device { Id = "dev_iso_other", TenantId = "tenant_iso_b", ClassroomId = "c_iso_b", DeviceTokenHash = "hash_b", IsActive = true }); await db.SaveChangesAsync(); var bundleService = scope.ServiceProvider.GetRequiredService(); var result = await bundleService.CreateSupportBundleAsync( "dev_iso_target", new CreateSupportBundleRequest { ClientRequestId = "req_iso_test" }, "usr_super", "SuperAdmin", "global", "127.0.0.1", simulateAuditFailure: false, CancellationToken.None); if (!result.IsSuccess || result.Dto == null) throw new Exception("Failed to create support bundle in isolation test"); var createdBundle = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == result.Dto.SupportBundleId); if (createdBundle == null) throw new Exception("Bundle not in DB"); // 验证生成的通道严格绑定到 tenant_iso_a var correctChannel = $"t:{createdBundle.TenantId}:d:{createdBundle.DeviceId}"; if (correctChannel != "t:tenant_iso_a:d:dev_iso_target") throw new Exception($"Channel mismatch: {correctChannel}"); // 确保未泄漏至 tenant_iso_b if (correctChannel.Contains("tenant_iso_b")) throw new Exception("Cross-tenant leakage detected into tenant_iso_b"); } /// /// P1-8 / SB3: 验证离线设备真实性调度 (保持 PendingDispatch,超期转换 TimedOut,绝不虚构状态) /// private static async Task Test_P1_8_OfflineTruthfulness() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p18", Name = "学校P18", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p18", TenantId = "t_p18", DisplayName = "班级P18" }); // Device has no heartbeat and no active connection -> offline db.Devices.Add(new Device { Id = "dev_p18_offline", TenantId = "t_p18", ClassroomId = "c_p18", DeviceTokenHash = "hash", IsActive = true, LastHeartbeatAt = null }); await EnsureUserAsync(db, "usr_super", "admin", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var token = factory.GenerateToken("usr_super", "admin", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var req = new CreateSupportBundleRequest { ClientRequestId = "req_p18_offline" }; var resp = await client.PostAsJsonAsync("/api/admin/devices/dev_p18_offline/support-bundles", req); if (resp.StatusCode != HttpStatusCode.Accepted) throw new Exception($"Creation failed: {resp.StatusCode}"); var dto = await resp.Content.ReadFromJsonAsync(); // 1. Initial State: Must be PendingDispatch if (dto!.Status != SupportBundleStatuses.PendingDispatch) throw new Exception($"Offline device initial status must be PendingDispatch, got {dto.Status}"); // 2. Allow worker to process: status MUST remain PendingDispatch (never Available, Collecting, or Failed) await Task.Delay(1500); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundle = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == dto.SupportBundleId); if (bundle == null) throw new Exception("Bundle disappeared from DB"); if (bundle.Status != SupportBundleStatuses.PendingDispatch) { throw new Exception($"Offline truthfulness violated: expected PendingDispatch, got {bundle.Status}"); } if (bundle.DispatchAttemptCount < 1) { throw new Exception("Expected dispatch attempt count to increment during offline retry scheduling"); } if (!bundle.NextDispatchAttemptAtUtc.HasValue) { throw new Exception("Expected NextDispatchAttemptAtUtc to be scheduled"); } // 3. Fast-forward to past Deadline to test TimedOut transition bundle.DeadlineAtUtc = DateTimeOffset.UtcNow.AddSeconds(-5); bundle.NextDispatchAttemptAtUtc = DateTimeOffset.UtcNow.AddSeconds(-5); await db.SaveChangesAsync(); } // Wait for worker loop to pick up timed-out bundle await Task.Delay(1500); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var timedOutBundle = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == dto.SupportBundleId); if (timedOutBundle == null || timedOutBundle.Status != SupportBundleStatuses.TimedOut) { throw new Exception($"Expected bundle to transition to TimedOut after deadline, got {timedOutBundle?.Status}"); } } } /// /// P1-9: 验证服务器重启后从数据库可靠恢复 PendingDispatch 任务 /// private static async Task Test_P1_9_RestartRecovery() { var sharedDbName = "classnotify_restart_test_" + Guid.NewGuid().ToString("N"); string bundleId; // Session 1: 插入 PendingDispatch 任务后立即关闭 "服务器" using (var factory1 = new CustomWebApplicationFactory(sharedDbName)) { using var scope = factory1.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p19", Name = "学校P19", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p19", TenantId = "t_p19", DisplayName = "班级P19" }); db.Devices.Add(new Device { Id = "dev_p19_restart", TenantId = "t_p19", ClassroomId = "c_p19", DeviceTokenHash = "hash", IsActive = true, LastHeartbeatAt = DateTimeOffset.UtcNow }); bundleId = $"sb_restart_{Guid.NewGuid():N}"[..24]; var bundle = new DeviceSupportBundle { Id = bundleId, ClientRequestId = "req_restart_001", TenantId = "t_p19", DeviceId = "dev_p19_restart", CorrelationId = "corr_restart_001", RequestedByUserId = "usr_admin", Status = SupportBundleStatuses.PendingDispatch, CreatedAtUtc = DateTimeOffset.UtcNow, UpdatedAtUtc = DateTimeOffset.UtcNow, DeadlineAtUtc = DateTimeOffset.UtcNow.AddMinutes(2), NextDispatchAttemptAtUtc = DateTimeOffset.UtcNow.AddSeconds(-1) }; db.DeviceSupportBundles.Add(bundle); await db.SaveChangesAsync(); } // "Server 1 killed" // Session 2: 服务器重启,新服务实例启动,自动从数据库捞取 PendingDispatch 任务恢复调度 using (var factory2 = new CustomWebApplicationFactory(sharedDbName)) { // Device is online (heartbeat within 60s) // Wait for worker in restarted server to dispatch await Task.Delay(2000); using var scope = factory2.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var recoveredBundle = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == bundleId); if (recoveredBundle == null) throw new Exception("Recovered bundle missing from database after restart"); if (recoveredBundle.Status != SupportBundleStatuses.Collecting) { throw new Exception($"Expected restarted worker to dispatch recovered bundle to Collecting, but status is {recoveredBundle.Status}"); } if (!recoveredBundle.DispatchedAtUtc.HasValue) { throw new Exception("Expected DispatchedAtUtc to be recorded on recovered bundle"); } } } /// /// P1-10: 验证 Phase 1 阶段零提前落盘与零提前存储约束 (0 ZIP, null 存储字段) /// private static async Task Test_P1_10_NoPrematureStorage() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Tenants.Add(new Tenant { Id = "t_p110", Name = "学校P110", IsActive = true }); db.Classrooms.Add(new Classroom { Id = "c_p110", TenantId = "t_p110", DisplayName = "班级P110" }); db.Devices.Add(new Device { Id = "dev_p110", TenantId = "t_p110", ClassroomId = "c_p110", DeviceTokenHash = "hash", IsActive = true, LastHeartbeatAt = DateTimeOffset.UtcNow }); await EnsureUserAsync(db, "usr_super", "admin", "SuperAdmin", "global"); await db.SaveChangesAsync(); } var token = factory.GenerateToken("usr_super", "admin", "SuperAdmin", "global"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var req = new CreateSupportBundleRequest { ClientRequestId = "req_p110_zero_storage" }; var resp = await client.PostAsJsonAsync("/api/admin/devices/dev_p110/support-bundles", req); if (resp.StatusCode != HttpStatusCode.Accepted) throw new Exception("Creation failed"); var dto = await resp.Content.ReadFromJsonAsync(); await Task.Delay(1500); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundle = await db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == dto!.SupportBundleId); if (bundle == null) throw new Exception("Bundle not in DB"); // 必须严格为 null if (bundle.StoragePath != null) throw new Exception($"Phase 1 violation: StoragePath must be null, but was '{bundle.StoragePath}'"); if (bundle.SizeBytes != null) throw new Exception($"Phase 1 violation: SizeBytes must be null, but was {bundle.SizeBytes}"); if (bundle.Sha256 != null) throw new Exception($"Phase 1 violation: Sha256 must be null, but was '{bundle.Sha256}'"); if (bundle.ExpiresAtUtc != null) throw new Exception($"Phase 1 violation: ExpiresAtUtc must be null, but was {bundle.ExpiresAtUtc}"); } // 验证没有提前生成任何 support bundle ZIP 文件 var tempDir = Path.GetTempPath(); var zipFiles = Directory.GetFiles(tempDir, "support_bundle_*.zip", SearchOption.TopDirectoryOnly); if (zipFiles.Length > 0) { throw new Exception($"Phase 1 violation: found premature support bundle ZIP files in temp: {string.Join(", ", zipFiles)}"); } } }