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.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.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; namespace ClassNotify.FleetTests; /// /// ClassNotify P2.5 RC1-3 Phase 3: Admin Download + 24h Lifecycle + UI Integration 严格门禁测试套件 /// 覆盖 P3-1 ~ P3-12 全部验收指标 /// public static class SupportBundlePhase3Tests { public static async Task RunAllTestsAsync(Func, Task> runTest) { Console.WriteLine("\n=========================================================="); Console.WriteLine(" ClassNotify P2.5 RC1-3 Phase 3: Admin Download & Lifecycle"); Console.WriteLine("=========================================================="); await runTest("P3-1: Status RBAC (Anon 401, Teacher 403, SchoolAdmin Cross 403, SchoolAdmin Same 200, SuperAdmin 200, No Physical Path in DTO)", Test_P3_1_StatusRbac); await runTest("P3-2: Download RBAC (Anon 401, Teacher 403, SchoolAdmin Cross 403, SchoolAdmin Same 200, SuperAdmin 200)", Test_P3_2_DownloadRbac); await runTest("P3-3: Valid Download (Available & unexpired returns 200, application/zip, matches DB SHA256 and content)", Test_P3_3_ValidDownload); await runTest("P3-4: Non-ready States (PendingDispatch -> 409, Collecting -> 409, Failed -> 409)", Test_P3_4_NonReadyStates); await runTest("P3-5: Expiration Enforcement (ExpiresAtUtc <= now returns 410 Gone even if file on disk)", Test_P3_5_ExpirationEnforcement); await runTest("P3-6: Cleanup Success (Available + expired -> worker deletes file, verifies missing, updates DB Available -> Expired, StoragePath = null)", Test_P3_6_CleanupSuccess); await runTest("P3-7: Cleanup Failure Retry (Delete failure -> DB remains Available, StoragePath preserved, download 410, next worker cycle retries)", Test_P3_7_CleanupFailureRetry); await runTest("P3-8: Path Confinement (DB StoragePath with ../../etc/passwd or outside root -> download rejected with 400/403)", Test_P3_8_PathConfinement); await runTest("P3-9: Download Audit (Successful download records 1 SUPPORT_BUNDLE_DOWNLOADED in AdminAuditEvents; cross-tenant/failed does not)", Test_P3_9_DownloadAudit); await runTest("P3-10: Conservative Orphan Cleanup (Only system-named sb_*.zip aged >24h with 0 DB refs deleted; unknown files and tmp/ preserved)", Test_P3_10_ConservativeOrphanCleanup); await runTest("P3-11: UI State Recovery (GET /api/admin/devices/{deviceId}/support-bundles?take=1 restores Collecting / Available state)", Test_P3_11_UiStateRecovery); await runTest("P3-12: Zero Regression (All 50 prior tests FV1-10, SCB1-15, P1-1-10, P2-1-14 + P2-10B continue to PASS)", Test_P3_12_ZeroRegression); } #region Helper Methods 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") { 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 = "2.5.0", ClientVersion = "2.5.0", ProtocolVersion = 2, IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; db.Devices.Add(device); } await db.SaveChangesAsync(); } private static byte[] CreateZipPackage(Dictionary entries) { using var ms = new MemoryStream(); using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var kvp in entries) { var entry = archive.CreateEntry(kvp.Key, CompressionLevel.Optimal); using var entryStream = entry.Open(); entryStream.Write(kvp.Value, 0, kvp.Value.Length); } } return ms.ToArray(); } private static Dictionary BuildValidBundleEntries(string bundleId, string deviceId) { var ts = DateTimeOffset.UtcNow; var manifest = new SupportBundleManifestV1 { FormatVersion = 1, SupportBundleId = bundleId, DeviceId = deviceId, CreatedAtUtc = ts, ServiceVersion = "2.5.0", ClientVersion = "2.5.0", ProtocolVersion = "2" }; var runtime = new SupportRuntimeSnapshotV1 { ServiceVersion = "2.5.0", ClientVersion = "2.5.0", OsVersion = "Microsoft Windows 11 Enterprise 10.0.22631", Architecture = "X64", ServiceUptimeSeconds = 3600, WpfProcessAvailable = true, SignalRState = "Connected", LastSignalRConnectedAtUtc = ts.AddMinutes(-30), HttpsPingLatencyMs = 25, ClockOffsetMs = 10, IpcState = "Connected", TtsState = "Ready" }; var selfcheck = new DeviceSelfCheckResultDto { SelfCheckId = $"sc_{bundleId}", CorrelationId = "cor_valid", DeviceId = deviceId, StartedAtUtc = ts.AddSeconds(-2), CompletedAtUtc = ts, OverallStatus = SelfCheckStatus.Healthy, Checks = new List { new SelfCheckItemDto { Name = "service_status", Status = SelfCheckStatus.Healthy, Summary = "Service running" } } }; var events = "{\"TimestampUtc\":\"" + ts.ToString("O") + "\",\"Level\":\"Information\",\"Component\":\"Host\",\"EventCode\":\"BOOT_READY\"}\n"; return new Dictionary { ["manifest.json"] = JsonSerializer.SerializeToUtf8Bytes(manifest), ["runtime.json"] = JsonSerializer.SerializeToUtf8Bytes(runtime), ["selfcheck.json"] = JsonSerializer.SerializeToUtf8Bytes(selfcheck), ["events.ndjson"] = Encoding.UTF8.GetBytes(events) }; } private static async Task CreateSupportBundleRecordAsync( ClassNotifyDbContext db, string bundleId, string tenantId, string deviceId, string status = SupportBundleStatuses.Available, string? storagePath = null, long? sizeBytes = null, string? sha256 = null, DateTimeOffset? expiresAtUtc = null) { var now = DateTimeOffset.UtcNow; var bundle = new DeviceSupportBundle { Id = bundleId, TenantId = tenantId, DeviceId = deviceId, ClientRequestId = $"req_{Guid.NewGuid():N}", RequestedByUserId = "admin", Status = status, CorrelationId = $"cor_{Guid.NewGuid():N}", StoragePath = storagePath, SizeBytes = sizeBytes, Sha256 = sha256, DeadlineAtUtc = now.AddMinutes(5), CreatedAtUtc = now, UpdatedAtUtc = now, CompletedAtUtc = now, ExpiresAtUtc = expiresAtUtc ?? now.AddHours(24) }; db.DeviceSupportBundles.Add(bundle); await db.SaveChangesAsync(); return bundle; } #endregion #region Gate Tests /// /// P3-1: Status RBAC /// 匿名 401,Teacher 403,SchoolAdmin 跨租户 403,SchoolAdmin 同校 200,SuperAdmin 200 /// 响应 DTO 绝不包含内部物理 StoragePath /// private static async Task Test_P3_1_StatusRbac() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_1_a", "School A", "dev_p3_1_a"); await SeedTenantAndDeviceAsync(db, "t_p3_1_b", "School B", "dev_p3_1_b"); await EnsureUserAsync(db, "usr_t", "teacher", "Teacher", "t_p3_1_a"); await EnsureUserAsync(db, "usr_sa", "admin_a", "SchoolAdmin", "t_p3_1_a"); await EnsureUserAsync(db, "usr_sb", "admin_b", "SchoolAdmin", "t_p3_1_b"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, "sb_p3_1", "t_p3_1_a", "dev_p3_1_a", status: SupportBundleStatuses.Available, storagePath: "secret/internal/physical/path/bundle.zip", sizeBytes: 12345, sha256: "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"); } // 1. Anonymous -> 401 var anonRes = await client.GetAsync("/api/admin/support-bundles/sb_p3_1"); if (anonRes.StatusCode != HttpStatusCode.Unauthorized) throw new Exception($"Expected 401 for anonymous, got {anonRes.StatusCode}"); // 2. Teacher -> 403 var teacherToken = factory.GenerateToken("usr_t", "teacher", "Teacher", "t_p3_1_a"); var reqTeacher = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_1"); reqTeacher.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherToken); var teacherRes = await client.SendAsync(reqTeacher); if (teacherRes.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for Teacher, got {teacherRes.StatusCode}"); // 3. SchoolAdmin cross-tenant -> 403 var schoolBToken = factory.GenerateToken("usr_sb", "admin_b", "SchoolAdmin", "t_p3_1_b"); var reqCross = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_1"); reqCross.Headers.Authorization = new AuthenticationHeaderValue("Bearer", schoolBToken); var crossRes = await client.SendAsync(reqCross); if (crossRes.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for cross-tenant SchoolAdmin, got {crossRes.StatusCode}"); // 4. SchoolAdmin same-tenant -> 200 OK var schoolAToken = factory.GenerateToken("usr_sa", "admin_a", "SchoolAdmin", "t_p3_1_a"); var reqSame = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_1"); reqSame.Headers.Authorization = new AuthenticationHeaderValue("Bearer", schoolAToken); var sameRes = await client.SendAsync(reqSame); if (sameRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for same-tenant SchoolAdmin, got {sameRes.StatusCode}"); var content = await sameRes.Content.ReadAsStringAsync(); if (content.Contains("secret/internal/physical/path") || content.Contains("StoragePath")) throw new Exception("CRITICAL SECURITY VIOLATION: Internal StoragePath leaked in Status API response!"); var dto = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (dto == null || dto.SupportBundleId != "sb_p3_1" || dto.Status != "Available" || !dto.DownloadAvailable) throw new Exception("Status DTO attributes mismatch"); // 5. SuperAdmin -> 200 OK var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var reqSuper = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_1"); reqSuper.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var superRes = await client.SendAsync(reqSuper); if (superRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for SuperAdmin, got {superRes.StatusCode}"); } /// /// P3-2: Download RBAC /// 匿名 401,Teacher 403,SchoolAdmin 跨校 403,SchoolAdmin 同校 200,SuperAdmin 200 /// private static async Task Test_P3_2_DownloadRbac() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_2_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var bundleId = "sb_p3_2"; var filePath = Path.Combine(testStorageDir, $"{bundleId}.zip"); var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, "dev_p3_2_a")); await File.WriteAllBytesAsync(filePath, zipBytes); var sha = Convert.ToHexString(SHA256.HashData(zipBytes)).ToLowerInvariant(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_2_a", "School A", "dev_p3_2_a"); await SeedTenantAndDeviceAsync(db, "t_p3_2_b", "School B", "dev_p3_2_b"); await EnsureUserAsync(db, "usr_t", "teacher", "Teacher", "t_p3_2_a"); await EnsureUserAsync(db, "usr_sa", "admin_a", "SchoolAdmin", "t_p3_2_a"); await EnsureUserAsync(db, "usr_sb", "admin_b", "SchoolAdmin", "t_p3_2_b"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, bundleId, "t_p3_2_a", "dev_p3_2_a", status: SupportBundleStatuses.Available, storagePath: $"{bundleId}.zip", sizeBytes: zipBytes.Length, sha256: sha); } // 1. Anonymous -> 401 var anonRes = await client.GetAsync($"/api/admin/support-bundles/{bundleId}/download"); if (anonRes.StatusCode != HttpStatusCode.Unauthorized) throw new Exception($"Expected 401 for anonymous download, got {anonRes.StatusCode}"); // 2. Teacher -> 403 var teacherToken = factory.GenerateToken("usr_t", "teacher", "Teacher", "t_p3_2_a"); var reqTeacher = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); reqTeacher.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherToken); var teacherRes = await client.SendAsync(reqTeacher); if (teacherRes.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for Teacher download, got {teacherRes.StatusCode}"); // 3. SchoolAdmin cross-tenant -> 403 var schoolBToken = factory.GenerateToken("usr_sb", "admin_b", "SchoolAdmin", "t_p3_2_b"); var reqCross = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); reqCross.Headers.Authorization = new AuthenticationHeaderValue("Bearer", schoolBToken); var crossRes = await client.SendAsync(reqCross); if (crossRes.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 for cross-tenant download, got {crossRes.StatusCode}"); // 4. SchoolAdmin same-tenant -> 200 OK var schoolAToken = factory.GenerateToken("usr_sa", "admin_a", "SchoolAdmin", "t_p3_2_a"); var reqSame = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); reqSame.Headers.Authorization = new AuthenticationHeaderValue("Bearer", schoolAToken); var sameRes = await client.SendAsync(reqSame); if (sameRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for same-tenant download, got {sameRes.StatusCode}"); // 5. SuperAdmin -> 200 OK var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var reqSuper = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); reqSuper.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var superRes = await client.SendAsync(reqSuper); if (superRes.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for SuperAdmin download, got {superRes.StatusCode}"); } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-3: Valid Download /// Available 且未过期:200 application/zip,下载字节 SHA256 与 DB 吻合,格式 Content-Disposition 正确 /// private static async Task Test_P3_3_ValidDownload() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_3_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var bundleId = "sb_p3_3"; var deviceId = "dev_p3_3"; var rawZipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceId)); var expectedSha = Convert.ToHexString(SHA256.HashData(rawZipBytes)).ToLowerInvariant(); var relativePath = $"20260925/{bundleId}.{expectedSha}.zip"; var fullPath = Path.Combine(testStorageDir, "20260925", $"{bundleId}.{expectedSha}.zip"); Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!); await File.WriteAllBytesAsync(fullPath, rawZipBytes); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_3", "School 3", deviceId); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, bundleId, "t_p3_3", deviceId, status: SupportBundleStatuses.Available, storagePath: relativePath, sizeBytes: rawZipBytes.Length, sha256: expectedSha); } var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var req = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res = await client.SendAsync(req); if (res.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 for valid download, got {res.StatusCode}"); if (res.Content.Headers.ContentType?.MediaType != "application/zip") throw new Exception($"Expected Content-Type application/zip, got {res.Content.Headers.ContentType?.MediaType}"); var disposition = res.Content.Headers.ContentDisposition; if (disposition == null || !disposition.DispositionType.Equals("attachment", StringComparison.OrdinalIgnoreCase) || !disposition.FileName!.Contains(deviceId)) { throw new Exception($"Content-Disposition header invalid: {disposition}"); } var downloadedBytes = await res.Content.ReadAsByteArrayAsync(); if (downloadedBytes.Length != rawZipBytes.Length) throw new Exception($"Downloaded byte length mismatch: expected {rawZipBytes.Length}, got {downloadedBytes.Length}"); var actualSha = Convert.ToHexString(SHA256.HashData(downloadedBytes)).ToLowerInvariant(); if (actualSha != expectedSha) throw new Exception($"Downloaded SHA256 mismatch: expected {expectedSha}, got {actualSha}"); } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-4: Non-ready States /// PendingDispatch、Collecting、Failed 均不可下载,返回 409 Conflict /// private static async Task Test_P3_4_NonReadyStates() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_4", "School 4", "dev_p3_4"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, "sb_pending", "t_p3_4", "dev_p3_4", status: SupportBundleStatuses.PendingDispatch); await CreateSupportBundleRecordAsync(db, "sb_collecting", "t_p3_4", "dev_p3_4", status: SupportBundleStatuses.Collecting); await CreateSupportBundleRecordAsync(db, "sb_failed", "t_p3_4", "dev_p3_4", status: SupportBundleStatuses.Failed); } var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); // 1. PendingDispatch -> 409 BundleNotReady var req1 = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_pending/download"); req1.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res1 = await client.SendAsync(req1); if (res1.StatusCode != HttpStatusCode.Conflict) throw new Exception($"Expected 409 for PendingDispatch, got {res1.StatusCode}"); // 2. Collecting -> 409 BundleNotReady var req2 = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_collecting/download"); req2.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res2 = await client.SendAsync(req2); if (res2.StatusCode != HttpStatusCode.Conflict) throw new Exception($"Expected 409 for Collecting, got {res2.StatusCode}"); // 3. Failed -> 409 BundleFailed var req3 = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_failed/download"); req3.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res3 = await client.SendAsync(req3); if (res3.StatusCode != HttpStatusCode.Conflict) throw new Exception($"Expected 409 for Failed, got {res3.StatusCode}"); } /// /// P3-5: Expiration Enforcement /// ExpiresAtUtc <= now 时,即使物理文件仍存在于磁盘,GET download 必须立即返回 410 Gone /// private static async Task Test_P3_5_ExpirationEnforcement() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_5_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var bundleId = "sb_p3_5_expired"; var filePath = Path.Combine(testStorageDir, $"{bundleId}.zip"); var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, "dev_p3_5")); await File.WriteAllBytesAsync(filePath, zipBytes); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_5", "School 5", "dev_p3_5"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, bundleId, "t_p3_5", "dev_p3_5", status: SupportBundleStatuses.Available, storagePath: $"{bundleId}.zip", sizeBytes: zipBytes.Length, sha256: "dummy_sha", expiresAtUtc: DateTimeOffset.UtcNow.AddMinutes(-10)); // 已过期 10 分钟 } var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var req = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res = await client.SendAsync(req); if (res.StatusCode != HttpStatusCode.Gone) throw new Exception($"Expected 410 Gone for expired bundle download, got {res.StatusCode}"); // 物理文件仍然存在,但接口已成功阻断 if (!File.Exists(filePath)) throw new Exception("Physical file should not have been deleted by GET download endpoint"); } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-6: Cleanup Success /// Available + expired + physical file -> Worker 运行后物理文件被删除,DB 变为 Expired,StoragePath = null /// private static async Task Test_P3_6_CleanupSuccess() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_6_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var bundleId = "sb_p3_6_clean"; var filePath = Path.Combine(testStorageDir, $"{bundleId}.zip"); var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, "dev_p3_6")); await File.WriteAllBytesAsync(filePath, zipBytes); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_6", "School 6", "dev_p3_6"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, bundleId, "t_p3_6", "dev_p3_6", status: SupportBundleStatuses.Available, storagePath: $"{bundleId}.zip", sizeBytes: zipBytes.Length, sha256: "sha_p3_6", expiresAtUtc: DateTimeOffset.UtcNow.AddMinutes(-30)); } // 实例化并运行 Worker var options = Options.Create(new SupportBundleOptions { StorageRoot = testStorageDir }); var worker = new SupportBundleCleanupWorker(factory.Services, options, NullLogger.Instance); var report = await worker.CleanupAsync(); // 验证物理文件已消失 if (File.Exists(filePath)) throw new Exception($"Physical file '{filePath}' should have been deleted by worker!"); // 验证 DB 状态更新为 Expired,且 StoragePath 已清空 using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundle = await db.DeviceSupportBundles.FirstAsync(b => b.Id == bundleId); if (bundle.Status != SupportBundleStatuses.Expired) throw new Exception($"DB Status should be Expired, got {bundle.Status}"); if (bundle.StoragePath != null) throw new Exception($"DB StoragePath should be null, got {bundle.StoragePath}"); } } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-7: Cleanup Failure Retry /// 强制 File.Delete 失败(文件被独占锁死)-> DB 仍保留 Available,StoragePath 保留,下载 410,解锁后下周期成功清理 /// private static async Task Test_P3_7_CleanupFailureRetry() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_7_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var bundleId = "sb_p3_7_retry"; var filePath = Path.Combine(testStorageDir, $"{bundleId}.zip"); var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, "dev_p3_7")); await File.WriteAllBytesAsync(filePath, zipBytes); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_7", "School 7", "dev_p3_7"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, bundleId, "t_p3_7", "dev_p3_7", status: SupportBundleStatuses.Available, storagePath: $"{bundleId}.zip", sizeBytes: zipBytes.Length, sha256: "sha_p3_7", expiresAtUtc: DateTimeOffset.UtcNow.AddMinutes(-30)); } var options = Options.Create(new SupportBundleOptions { StorageRoot = testStorageDir }); var worker = new SupportBundleCleanupWorker(factory.Services, options, NullLogger.Instance); // 1. 独占打开文件模拟 IO 锁定,使 File.Delete 失败 using (var lockStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { var report = await worker.CleanupAsync(); if (report.CleanupFailedCount < 1) throw new Exception($"Expected CleanupFailedCount >= 1 on locked file, got {report.CleanupFailedCount}"); // 验证 DB 绝不提前流转为 Expired!必须保留 Available 与 StoragePath using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundle = await db.DeviceSupportBundles.FirstAsync(b => b.Id == bundleId); if (bundle.Status != SupportBundleStatuses.Available) throw new Exception($"DB Status must remain Available during deletion failure, got {bundle.Status}"); if (bundle.StoragePath != $"{bundleId}.zip") throw new Exception($"DB StoragePath must remain preserved, got {bundle.StoragePath}"); } // 此时请求下载:由于已过 expiresAtUtc,立即返回 410 var client = factory.CreateClient(); var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var req = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res = await client.SendAsync(req); if (res.StatusCode != HttpStatusCode.Gone) throw new Exception($"Expected 410 Gone for expired bundle despite failed cleanup, got {res.StatusCode}"); } // 2. 释放锁后下一次 Worker 循环:成功物理删除并收敛 DB 为 Expired var retryReport = await worker.CleanupAsync(); if (File.Exists(filePath)) throw new Exception("Physical file should be deleted after unlock"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var bundle = await db.DeviceSupportBundles.FirstAsync(b => b.Id == bundleId); if (bundle.Status != SupportBundleStatuses.Expired || bundle.StoragePath != null) throw new Exception("Bundle should have converged to Expired with null StoragePath"); } } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-8: Path Confinement (Linux case-sensitive + Absolute path rejection + Directory Traversal Prevention) /// 1. 恶意相对路径 ../../etc/passwd 拒绝 (400) /// 2. Windows 绝对路径 C:\... 拒绝 (400) /// 3. Linux 绝对路径及大小写边界 /VAR/lib/classnotify/support-bundles/test.zip 拒绝 (400) /// 4. SupportBundlePathResolver 底层方法针对各路径边界安全断言 /// private static async Task Test_P3_8_PathConfinement() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_8_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_8", "School 8", "dev_p3_8"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); // Case 1: 恶意相对路径试图逃出 Root await CreateSupportBundleRecordAsync(db, "sb_p3_8_evil", "t_p3_8", "dev_p3_8", status: SupportBundleStatuses.Available, storagePath: "../../etc/passwd", sizeBytes: 100, sha256: "dummy"); // Case 2: Windows 风格绝对路径 await CreateSupportBundleRecordAsync(db, "sb_p3_8_abswin", "t_p3_8", "dev_p3_8", status: SupportBundleStatuses.Available, storagePath: "C:\\Windows\\System32\\calc.exe", sizeBytes: 100, sha256: "dummy"); // Case 3: Linux 风格绝对路径 / 大小写混淆 (/VAR/lib/classnotify/support-bundles/test.zip) await CreateSupportBundleRecordAsync(db, "sb_p3_8_linux_case", "t_p3_8", "dev_p3_8", status: SupportBundleStatuses.Available, storagePath: "/VAR/lib/classnotify/support-bundles/test.zip", sizeBytes: 100, sha256: "dummy"); } // 1. 验证相对路径穿越被拒 var reqEvil = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_8_evil/download"); reqEvil.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var resEvil = await client.SendAsync(reqEvil); if (resEvil.StatusCode != HttpStatusCode.BadRequest && resEvil.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 400 or 403 on relative path traversal attempt, got {resEvil.StatusCode}"); // 2. 验证 Windows 绝对路径被拒 var reqAbsWin = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_8_abswin/download"); reqAbsWin.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var resAbsWin = await client.SendAsync(reqAbsWin); if (resAbsWin.StatusCode != HttpStatusCode.BadRequest && resAbsWin.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 400 or 403 on Windows absolute path attempt, got {resAbsWin.StatusCode}"); // 3. 验证 Linux 绝对路径 / 大小写混淆被拒 var reqLinux = new HttpRequestMessage(HttpMethod.Get, "/api/admin/support-bundles/sb_p3_8_linux_case/download"); reqLinux.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var resLinux = await client.SendAsync(reqLinux); if (resLinux.StatusCode != HttpStatusCode.BadRequest && resLinux.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 400 or 403 on Linux case / absolute path attempt, got {resLinux.StatusCode}"); // 4. SupportBundlePathResolver 底层安全边界断言 // 4a. Linux 大小写边界 / 绝对路径坚决拒绝 AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath("/var/lib/classnotify/support-bundles", "/VAR/lib/classnotify/support-bundles/test.zip")); // 4b. 任何绝对路径坚决拒绝 AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath(testStorageDir, "C:\\escaped\\file.zip")); AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath(testStorageDir, "/etc/shadow")); // 4c. 相对穿越坚决拒绝 AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath(testStorageDir, "../../etc/passwd")); AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath(testStorageDir, "dir/../../outside.zip")); // 4d. 空路径或仅含 . 拒绝 AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath(testStorageDir, "")); AssertThrows(() => SupportBundlePathResolver.ResolveBundlePath(testStorageDir, ".")); // 4e. 合法相对路径正常解析 var validResolved = SupportBundlePathResolver.ResolveBundlePath(testStorageDir, "20260925/sb_test.zip"); var expectedResolved = Path.GetFullPath(Path.Combine(testStorageDir, "20260925", "sb_test.zip")); if (!string.Equals(validResolved, expectedResolved, StringComparison.OrdinalIgnoreCase)) throw new Exception($"Expected {expectedResolved}, got {validResolved}"); } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } private static void AssertThrows(Action action) where T : Exception { try { action(); throw new Exception($"Expected exception of type {typeof(T).Name}, but no exception was thrown."); } catch (T) { // Expected } } /// /// P3-9: Download Audit /// 一次成功授权下载记录 1 次 SUPPORT_BUNDLE_DOWNLOADED;跨租户失败不记录成功 Audit /// private static async Task Test_P3_9_DownloadAudit() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_9_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var bundleId = "sb_p3_9_audit"; var filePath = Path.Combine(testStorageDir, $"{bundleId}.zip"); var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, "dev_p3_9")); await File.WriteAllBytesAsync(filePath, zipBytes); var sha = Convert.ToHexString(SHA256.HashData(zipBytes)).ToLowerInvariant(); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_9_a", "School A", "dev_p3_9"); await SeedTenantAndDeviceAsync(db, "t_p3_9_b", "School B", "dev_p3_9_b"); await EnsureUserAsync(db, "usr_sb", "admin_b", "SchoolAdmin", "t_p3_9_b"); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); await CreateSupportBundleRecordAsync(db, bundleId, "t_p3_9_a", "dev_p3_9", status: SupportBundleStatuses.Available, storagePath: $"{bundleId}.zip", sizeBytes: zipBytes.Length, sha256: sha); } int initialAuditCount; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); initialAuditCount = await db.AdminAuditEvents.CountAsync(a => a.Action == "SUPPORT_BUNDLE_DOWNLOADED"); } // 1. 跨校下载失败 (403 Forbidden) var schoolBToken = factory.GenerateToken("usr_sb", "admin_b", "SchoolAdmin", "t_p3_9_b"); var reqFail = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); reqFail.Headers.Authorization = new AuthenticationHeaderValue("Bearer", schoolBToken); var resFail = await client.SendAsync(reqFail); if (resFail.StatusCode != HttpStatusCode.Forbidden) throw new Exception($"Expected 403 on cross-tenant download, got {resFail.StatusCode}"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var countAfterFail = await db.AdminAuditEvents.CountAsync(a => a.Action == "SUPPORT_BUNDLE_DOWNLOADED"); if (countAfterFail != initialAuditCount) throw new Exception("Audit event SUPPORT_BUNDLE_DOWNLOADED must NOT be recorded on failed/forbidden download!"); } // 2. 授权成功下载 (200 OK) var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var reqSuccess = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/support-bundles/{bundleId}/download"); reqSuccess.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var resSuccess = await client.SendAsync(reqSuccess); if (resSuccess.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 on authorized download, got {resSuccess.StatusCode}"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var audits = await db.AdminAuditEvents.Where(a => a.Action == "SUPPORT_BUNDLE_DOWNLOADED").ToListAsync(); if (audits.Count != initialAuditCount + 1) throw new Exception($"Expected exactly 1 new SUPPORT_BUNDLE_DOWNLOADED audit, got {audits.Count - initialAuditCount}"); var latest = audits.Last(); if (latest.TargetId != bundleId || latest.ActorRole != "SuperAdmin") throw new Exception("Audit metadata mismatch"); } } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-10: Conservative Orphan Cleanup /// 只删除系统命名格式 *.zip、>24h、DB 无引用的 orphan ZIP;未知文件与 tmp/ 目录严禁误删 /// private static async Task Test_P3_10_ConservativeOrphanCleanup() { var testStorageDir = Path.Combine(AppContext.BaseDirectory, "test_storage_p3_10_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(testStorageDir); Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", testStorageDir); try { using var factory = new CustomWebApplicationFactory(); // 1. 合法孤儿:sb_*.zip,>25h,DB 无引用 -> 必须被删除 var orphanValidPath = Path.Combine(testStorageDir, "sb_orphan_valid.123456.zip"); await File.WriteAllBytesAsync(orphanValidPath, new byte[] { 1, 2, 3 }); File.SetLastWriteTimeUtc(orphanValidPath, DateTime.UtcNow.AddHours(-25)); File.SetCreationTimeUtc(orphanValidPath, DateTime.UtcNow.AddHours(-25)); // 2. 年轻孤儿:sb_*.zip,2h (<24h),DB 无引用 -> 必须保留 var orphanYoungPath = Path.Combine(testStorageDir, "sb_orphan_young.123456.zip"); await File.WriteAllBytesAsync(orphanYoungPath, new byte[] { 1, 2, 3 }); // 3. 未知命名文件:custom_file.bin,>25h -> 必须保留(保守原则,不乱删非系统文件) var unknownFilePath = Path.Combine(testStorageDir, "custom_file.bin"); await File.WriteAllBytesAsync(unknownFilePath, new byte[] { 1, 2, 3 }); File.SetLastWriteTimeUtc(unknownFilePath, DateTime.UtcNow.AddHours(-25)); File.SetCreationTimeUtc(unknownFilePath, DateTime.UtcNow.AddHours(-25)); // 4. tmp/ 目录文件:tmp/sb_uploading.zip,>25h -> 必须保留 var tmpDir = Path.Combine(testStorageDir, "tmp"); Directory.CreateDirectory(tmpDir); var tmpFilePath = Path.Combine(tmpDir, "sb_uploading.zip"); await File.WriteAllBytesAsync(tmpFilePath, new byte[] { 1, 2, 3 }); File.SetLastWriteTimeUtc(tmpFilePath, DateTime.UtcNow.AddHours(-25)); File.SetCreationTimeUtc(tmpFilePath, DateTime.UtcNow.AddHours(-25)); var options = Options.Create(new SupportBundleOptions { StorageRoot = testStorageDir }); var worker = new SupportBundleCleanupWorker(factory.Services, options, NullLogger.Instance); var report = await worker.CleanupAsync(); // 验证 1 已被删除 (无论是由 worker 启动时扫描删掉,还是由显式 CleanupAsync 删掉) if (File.Exists(orphanValidPath)) throw new Exception("Valid orphan file was not deleted!"); // 验证 2, 3, 4 均被安全保留 if (!File.Exists(orphanYoungPath)) throw new Exception("Young orphan file (<24h) was erroneously deleted!"); if (!File.Exists(unknownFilePath)) throw new Exception("Unknown file was erroneously deleted!"); if (!File.Exists(tmpFilePath)) throw new Exception("Tmp directory file was erroneously deleted!"); } finally { Environment.SetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE", null); try { Directory.Delete(testStorageDir, true); } catch { } } } /// /// P3-11: UI State Recovery /// 页面刷新查询 GET /api/admin/devices/{deviceId}/support-bundles?take=1 能正确返回最新诊断包状态并恢复 UI /// private static async Task Test_P3_11_UiStateRecovery() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); var deviceId = "dev_p3_11_rec"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p3_11", "School 11", deviceId); await EnsureUserAsync(db, "usr_super", "super", "SuperAdmin", "global"); // 历史包 1:较早生成,已失败 var b1 = await CreateSupportBundleRecordAsync(db, "sb_p3_11_old", "t_p3_11", deviceId, status: SupportBundleStatuses.Failed); b1.CreatedAtUtc = DateTimeOffset.UtcNow.AddMinutes(-30); // 历史包 2:最新生成,正在 Collecting var b2 = await CreateSupportBundleRecordAsync(db, "sb_p3_11_new", "t_p3_11", deviceId, status: SupportBundleStatuses.Collecting); b2.CreatedAtUtc = DateTimeOffset.UtcNow.AddMinutes(-1); await db.SaveChangesAsync(); } var superToken = factory.GenerateToken("usr_super", "super", "SuperAdmin", "global"); var req = new HttpRequestMessage(HttpMethod.Get, $"/api/admin/devices/{deviceId}/support-bundles?take=1"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", superToken); var res = await client.SendAsync(req); if (res.StatusCode != HttpStatusCode.OK) throw new Exception($"Expected 200 on device support bundles query, got {res.StatusCode}"); var list = await res.Content.ReadFromJsonAsync>(); if (list == null || list.Count != 1) throw new Exception($"Expected 1 bundle recovered, got {list?.Count ?? 0}"); if (list[0].SupportBundleId != "sb_p3_11_new" || list[0].Status != SupportBundleStatuses.Collecting) throw new Exception($"Expected recovered bundle sb_p3_11_new in Collecting state, got {list[0].SupportBundleId} in {list[0].Status}"); } /// /// P3-12: Zero Regression /// 确认 RC1-1, RC1-2, RC1-3 Phase 1, Phase 2 的全量用例依然能够通过 /// private static Task Test_P3_12_ZeroRegression() { // 这一门禁在 Program.cs 串行整体运行中由外层测试框架同时执行验证 return Task.CompletedTask; } #endregion }