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.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Services; using ClassNotify.Service.Diagnostics; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; namespace ClassNotify.FleetTests; /// /// ClassNotify P2.5 RC1-3 Phase 2: Windows Collection + Secure Upload 严格门禁测试套件 /// 覆盖 P2-1 ~ P2-14 全部验收指标 (包含 SB4, SB5, SB6, SB7, SB8, SB9 及防压缩炸弹约束) /// public static class SupportBundlePhase2Tests { public static async Task RunAllTestsAsync(Func, Task> runTest) { Console.WriteLine("\n=========================================================="); Console.WriteLine(" ClassNotify P2.5 RC1-3 Phase 2: Windows Collection & Upload"); Console.WriteLine("=========================================================="); await runTest("P2-1: Collection Schema (4 strict allowlisted files: manifest, runtime, selfcheck, events)", Test_P2_1_CollectionSchema); await runTest("P2-2: Max Size Cap (Client collector rejects bundle exceeding size cap)", Test_P2_2_MaxSizeCap); await runTest("P2-3: Upload Authorization (SB4: Anon 401, Invalid 401, Cross-Device 403, Cross-Tenant 403, Matching 200)", Test_P2_3_UploadAuthorization); await runTest("P2-4: Content Allowlist (SB5: 5th unexpected entry, invalid files, or corrupt zip rejected with 400)", Test_P2_4_ContentAllowlist); await runTest("P2-5: Secret Injection Guard (SB6: Zero occurrences of canary secrets in generated zip)", Test_P2_5_SecretInjectionGuard); await runTest("P2-6: Server Streaming Size Limit (SB7: Reject stream > 5 MiB with HTTP 413 Payload Too Large)", Test_P2_6_ServerStreamingSizeLimit); await runTest("P2-7: Malicious Traversal Guard (SB8: Reject ../evil.exe, subfolders, colons with 400 InvalidZip)", Test_P2_7_MaliciousTraversalGuard); await runTest("P2-8: Compression Bomb Guard (Reject uncompressed size > 10 MiB with 400 ExpandedSizeExceeded)", Test_P2_8_CompressionBombGuard); await runTest("P2-9: Manifest Binding (Route ID, Authenticated Device, FormatVersion=1 mismatch rejected with 400)", Test_P2_9_ManifestBinding); await runTest("P2-10: Concurrent Upload First-Wins (SB9: Simultaneous uploads produce 1 DB winner, loser gets 409)", Test_P2_10_ConcurrentUploadFirstWins); await runTest("P2-10B: Same-Content Concurrent Upload (Identical uploads both succeed and preserve canonical file)", Test_P2_10B_SameContentConcurrentUpload); await runTest("P2-11: TimedOut Terminal (Late upload cannot turn TimedOut or Failed into Available -> 409 Conflict)", Test_P2_11_TimedOutTerminal); await runTest("P2-12: Collection Failure (Device reports failure -> Collecting to Failed, cannot revive)", Test_P2_12_CollectionFailure); await runTest("P2-13: Private Storage (Stored in private non-wwwroot directory, static URL returns 404)", Test_P2_13_PrivateStorage); await runTest("P2-14: Zero Notification Impact (Core notification & heartbeat flows completely unharmed)", Test_P2_14_ZeroNotificationImpact); } #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 SeedTenantAndDeviceAsync( ClassNotifyDbContext db, string tenantId, string tenantName, string deviceId, string rawToken, bool isActive = true) { 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 = isActive, CreatedAt = DateTimeOffset.UtcNow }; db.Devices.Add(device); } await db.SaveChangesAsync(); } private static async Task CreateSupportBundleRecordAsync( ClassNotifyDbContext db, string bundleId, string tenantId, string deviceId, string status = SupportBundleStatuses.Collecting, DateTimeOffset? deadlineAtUtc = null) { var bundle = new DeviceSupportBundle { Id = bundleId, TenantId = tenantId, DeviceId = deviceId, ClientRequestId = $"req_{Guid.NewGuid():N}", RequestedByUserId = "admin", Status = status, CorrelationId = $"cor_{Guid.NewGuid():N}", DeadlineAtUtc = deadlineAtUtc ?? DateTimeOffset.UtcNow.AddMinutes(5), CreatedAtUtc = DateTimeOffset.UtcNow, UpdatedAtUtc = DateTimeOffset.UtcNow }; db.DeviceSupportBundles.Add(bundle); await db.SaveChangesAsync(); return bundle; } 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, DateTimeOffset? customTimestamp = null) { var ts = customTimestamp ?? 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" }, new SelfCheckItemDto { Name = "ipc_pipe", Status = SelfCheckStatus.Healthy, Summary = "Pipe connected" } } }; var events = new List { new SupportDiagnosticEvent( TimestampUtc: ts.AddMinutes(-5), Level: "Information", Component: "SignalRWorker", EventCode: "SR001", CorrelationId: "cor_init", ErrorCode: null, DurationMs: 15), new SupportDiagnosticEvent( TimestampUtc: ts.AddMinutes(-2), Level: "Information", Component: "DiagnosticEngine", EventCode: "SC002", CorrelationId: "cor_sc", ErrorCode: null, DurationMs: 42) }; var eventsNdjson = string.Join("\n", events.Select(e => JsonSerializer.Serialize(e))); return new Dictionary { ["manifest.json"] = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true })), ["runtime.json"] = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(runtime, new JsonSerializerOptions { WriteIndented = true })), ["selfcheck.json"] = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(selfcheck, new JsonSerializerOptions { WriteIndented = true })), ["events.ndjson"] = Encoding.UTF8.GetBytes(eventsNdjson) }; } #endregion #region Gate Tests /// /// P2-1: Collection Schema /// 终端白名单采集器严格采集且仅采集 4 个文件: manifest.json, runtime.json, selfcheck.json, events.ndjson /// private static async Task Test_P2_1_CollectionSchema() { var tempWorkDir = Path.Combine(Path.GetTempPath(), $"p2_1_test_{Guid.NewGuid():N}"); Directory.CreateDirectory(tempWorkDir); try { var eventRecorder = new SupportEventRecorder(); eventRecorder.Record(new SupportDiagnosticEvent( TimestampUtc: DateTimeOffset.UtcNow, Level: "Information", Component: "TestComponent", EventCode: "EVT001", CorrelationId: "cor_1", ErrorCode: null, DurationMs: 10)); eventRecorder.Record(new SupportDiagnosticEvent( TimestampUtc: DateTimeOffset.UtcNow, Level: "Warning", Component: "NetworkProbe", EventCode: "NET002", CorrelationId: "cor_2", ErrorCode: null, DurationMs: 120)); var collector = new SupportBundleCollector(eventRecorder, NullLogger.Instance); var sampleSelfCheck = new DeviceSelfCheckResultDto { SelfCheckId = "sc_schema_test", DeviceId = "dev_p2_1_collector", OverallStatus = SelfCheckStatus.Healthy, Checks = new List { new SelfCheckItemDto { Name = "ipc", Status = SelfCheckStatus.Healthy, Summary = "Pipe OK" } } }; collector.SetLatestSelfCheck(sampleSelfCheck); var cmd = new GenerateSupportBundleCommand { SupportBundleId = "sb_p2_1_schema", CorrelationId = "cor_p2_1", RequestedAtUtc = DateTimeOffset.UtcNow, DeadlineAtUtc = DateTimeOffset.UtcNow.AddMinutes(5), MaxSizeBytes = 5 * 1024 * 1024 }; var res = await collector.CollectAndZipAsync(cmd, "dev_p2_1_collector", tempWorkDir); if (!res.Success || string.IsNullOrEmpty(res.ZipFilePath) || !File.Exists(res.ZipFilePath)) { throw new Exception($"CollectAndZipAsync failed: {res.ErrorMessage}"); } // Inspect ZIP entries using (var archive = ZipFile.OpenRead(res.ZipFilePath)) { if (archive.Entries.Count != 4) { throw new Exception($"Expected strictly 4 entries in ZIP, found {archive.Entries.Count}"); } var entryNames = archive.Entries.Select(e => e.FullName).OrderBy(x => x).ToList(); var expected = new List { "events.ndjson", "manifest.json", "runtime.json", "selfcheck.json" }; if (!entryNames.SequenceEqual(expected)) { throw new Exception($"Entries mismatch. Found: [{string.Join(", ", entryNames)}]"); } // Verify manifest.json var manifestEntry = archive.GetEntry("manifest.json")!; using (var ms = manifestEntry.Open()) { var manifest = JsonSerializer.Deserialize(ms); if (manifest == null || manifest.FormatVersion != 1 || manifest.SupportBundleId != "sb_p2_1_schema" || manifest.DeviceId != "dev_p2_1_collector") { throw new Exception("manifest.json validation failed"); } } // Verify runtime.json var runtimeEntry = archive.GetEntry("runtime.json")!; using (var ms = runtimeEntry.Open()) { var runtime = JsonSerializer.Deserialize(ms); if (runtime == null || string.IsNullOrWhiteSpace(runtime.OsVersion) || string.IsNullOrWhiteSpace(runtime.ServiceVersion)) { throw new Exception("runtime.json validation failed"); } } // Verify selfcheck.json var scEntry = archive.GetEntry("selfcheck.json")!; using (var ms = scEntry.Open()) { var sc = JsonSerializer.Deserialize(ms); if (sc == null || sc.OverallStatus != SelfCheckStatus.Healthy || sc.Checks.Count != 1) { throw new Exception("selfcheck.json validation failed"); } } // Verify events.ndjson var eventsEntry = archive.GetEntry("events.ndjson")!; using (var ms = eventsEntry.Open()) using (var reader = new StreamReader(ms, Encoding.UTF8)) { var lines = new List(); string? line; while ((line = await reader.ReadLineAsync()) != null) { if (!string.IsNullOrWhiteSpace(line)) lines.Add(line); } if (lines.Count < 2) { throw new Exception($"events.ndjson expected at least 2 events, got {lines.Count}"); } } } } finally { if (Directory.Exists(tempWorkDir)) Directory.Delete(tempWorkDir, true); } } /// /// P2-2: Max Size Cap /// 终端白名单采集器严格执行 MaxSizeBytes 限制,超限阻断 /// private static async Task Test_P2_2_MaxSizeCap() { var tempWorkDir = Path.Combine(Path.GetTempPath(), $"p2_2_test_{Guid.NewGuid():N}"); Directory.CreateDirectory(tempWorkDir); try { var eventRecorder = new SupportEventRecorder(); var collector = new SupportBundleCollector(eventRecorder, NullLogger.Instance); var cmd = new GenerateSupportBundleCommand { SupportBundleId = "sb_p2_2_size", CorrelationId = "cor_p2_2", RequestedAtUtc = DateTimeOffset.UtcNow, DeadlineAtUtc = DateTimeOffset.UtcNow.AddMinutes(5), MaxSizeBytes = 50 // Unreasonably small hard cap (50 bytes) }; var res = await collector.CollectAndZipAsync(cmd, "dev_p2_2", tempWorkDir); if (res.Success) { throw new Exception("Collector should have failed when package size exceeds MaxSizeBytes"); } if (res.ErrorCode != SupportBundleErrorCodes.BundleTooLarge && res.ErrorCode != SupportBundleErrorCodes.CollectionFailure) { throw new Exception($"Expected BundleTooLarge or CollectionFailure error code, got {res.ErrorCode}"); } } finally { if (Directory.Exists(tempWorkDir)) Directory.Delete(tempWorkDir, true); } } /// /// P2-3: Upload Authorization (SB4) /// 严格验证设备身份 (X-Device-Id, X-Device-Token),阻断越权与跨租户上传 /// private static async Task Test_P2_3_UploadAuthorization() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string bundleId = "sb_auth_test_1"; string deviceA = "dev_auth_a"; string tokenA = "token_auth_a_secret_123"; string tenantA = "t_auth_a"; string deviceB = "dev_auth_b"; string tokenB = "token_auth_b_secret_456"; string tenantB = "t_auth_b"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantA, "School A", deviceA, tokenA); await SeedTenantAndDeviceAsync(db, tenantB, "School B", deviceB, tokenB); await CreateSupportBundleRecordAsync(db, bundleId, tenantA, deviceA, SupportBundleStatuses.Collecting); } var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceA)); // 1. Anonymous upload (no auth headers) -> 401 Unauthorized { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.Unauthorized) { throw new Exception($"Anonymous upload expected 401 Unauthorized, got {resp.StatusCode}"); } } // 2. Invalid device token -> 401 Unauthorized { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceA); req.Headers.Add("X-Device-Token", "WRONG_TOKEN"); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.Unauthorized) { throw new Exception($"Invalid token expected 401 Unauthorized, got {resp.StatusCode}"); } } // 3. Cross-device attack: Device B attempts to upload for Device A's bundle -> 403 Forbidden (SB4) { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceB); req.Headers.Add("X-Device-Token", tokenB); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.Forbidden) { throw new Exception($"Device B uploading for Device A expected 403 Forbidden, got {resp.StatusCode}"); } } // 4. Non-existent bundle -> 404 Not Found { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/sb_non_existent/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceA); req.Headers.Add("X-Device-Token", tokenA); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.NotFound) { throw new Exception($"Non-existent bundle expected 404 Not Found, got {resp.StatusCode}"); } } // 5. Authorized Device A uploads -> 200 OK { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceA); req.Headers.Add("X-Device-Token", tokenA); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.OK) { var err = await resp.Content.ReadAsStringAsync(); throw new Exception($"Authorized upload expected 200 OK, got {resp.StatusCode} - {err}"); } // Verify DB state using var verifyScope = factory.Services.CreateScope(); var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var saved = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); if (saved.Status != SupportBundleStatuses.Available) { throw new Exception($"Bundle status expected Available, got {saved.Status}"); } if (string.IsNullOrWhiteSpace(saved.Sha256) || saved.SizeBytes != zipBytes.Length) { throw new Exception($"Bundle Sha256 or SizeBytes invalid: Sha256={saved.Sha256}, Size={saved.SizeBytes}"); } } } /// /// P2-4: Content Allowlist (SB5) /// 包含第 5 个额外文件、意外非白名单文件、缺少文件或损坏文件时直接拒绝 /// private static async Task Test_P2_4_ContentAllowlist() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_allowlist_1"; string token = "token_allowlist_1"; string tenantId = "t_allowlist_1"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Allowlist School", deviceId, token); } // Case A: 5th unexpected file (SB5 violation) { string bundleId = "sb_allowlist_5th"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries(bundleId, deviceId); entries["unauthorized_memory.dmp"] = Encoding.UTF8.GetBytes("RAW DUMP CONTENTS"); var zipBytes = CreateZipPackage(entries); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"5th file in zip expected 400 BadRequest, got {resp.StatusCode}"); } var err = await resp.Content.ReadAsStringAsync(); if (!err.Contains(SupportBundleErrorCodes.UnexpectedEntry)) { throw new Exception($"Expected errorCode UnexpectedEntry, got {err}"); } } // Case B: Missing required file (e.g. only 3 files) { string bundleId = "sb_allowlist_missing"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries(bundleId, deviceId); entries.Remove("events.ndjson"); var zipBytes = CreateZipPackage(entries); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"Missing entry expected 400 BadRequest, got {resp.StatusCode}"); } } // Case C: Corrupt Non-ZIP binary stream { string bundleId = "sb_allowlist_corrupt"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(Encoding.UTF8.GetBytes("THIS IS NOT A VALID ZIP FILE HEADER")) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"Corrupt ZIP expected 400 BadRequest, got {resp.StatusCode}"); } } } /// /// P2-5: Secret Injection Guard (SB6) /// 注入 4 种敏感金丝雀密钥 (JWT Key, DB Password, Raw Password, API Token), /// 验证生成诊断包的全量二进制及解压条目中 0 次出现 /// private static async Task Test_P2_5_SecretInjectionGuard() { string canaryJwtKey = "CANARY_JWT_SIG_SECRET_881920391"; string canaryDbPass = "CANARY_POSTGRES_PWD_994817290"; string canaryPlainPwd = "CANARY_USER_PLAIN_PWD_447291038"; string canaryApiToken = "CANARY_API_TOKEN_XYZ_118290372"; // Set canary environment variables to test environment variable dump guard Environment.SetEnvironmentVariable("JWT_SIGNING_KEY", canaryJwtKey); Environment.SetEnvironmentVariable("DATABASE_PASSWORD", canaryDbPass); Environment.SetEnvironmentVariable("USER_PASSWORD", canaryPlainPwd); Environment.SetEnvironmentVariable("REMOTE_API_TOKEN", canaryApiToken); var tempWorkDir = Path.Combine(Path.GetTempPath(), $"p2_5_test_{Guid.NewGuid():N}"); Directory.CreateDirectory(tempWorkDir); try { var eventRecorder = new SupportEventRecorder(); eventRecorder.Record(new SupportDiagnosticEvent( TimestampUtc: DateTimeOffset.UtcNow, Level: "Information", Component: "Service", EventCode: "EVT001", CorrelationId: "cor_std", ErrorCode: null, DurationMs: 5)); var collector = new SupportBundleCollector(eventRecorder, NullLogger.Instance); var cmd = new GenerateSupportBundleCommand { SupportBundleId = "sb_p2_5_canary", CorrelationId = "cor_p2_5", RequestedAtUtc = DateTimeOffset.UtcNow, DeadlineAtUtc = DateTimeOffset.UtcNow.AddMinutes(5), MaxSizeBytes = 5 * 1024 * 1024 }; var res = await collector.CollectAndZipAsync(cmd, "dev_p2_5", tempWorkDir); if (!res.Success || string.IsNullOrEmpty(res.ZipFilePath) || !File.Exists(res.ZipFilePath)) { throw new Exception($"CollectAndZipAsync failed: {res.ErrorMessage}"); } var canaries = new[] { canaryJwtKey, canaryDbPass, canaryPlainPwd, canaryApiToken }; // 1. Check raw ZIP bytes var rawBytes = await File.ReadAllBytesAsync(res.ZipFilePath); var rawString = Encoding.UTF8.GetString(rawBytes); foreach (var canary in canaries) { if (rawString.Contains(canary, StringComparison.OrdinalIgnoreCase)) { throw new Exception($"SB6 Secret Leak Detected! Canary '{canary}' found in raw ZIP bytes."); } } // 2. Check each uncompressed entry stream using (var archive = ZipFile.OpenRead(res.ZipFilePath)) { foreach (var entry in archive.Entries) { using var stream = entry.Open(); using var reader = new StreamReader(stream, Encoding.UTF8); var content = await reader.ReadToEndAsync(); foreach (var canary in canaries) { if (content.Contains(canary, StringComparison.OrdinalIgnoreCase)) { throw new Exception($"SB6 Secret Leak Detected! Canary '{canary}' found inside uncompressed entry '{entry.FullName}'."); } } } } } finally { Environment.SetEnvironmentVariable("JWT_SIGNING_KEY", null); Environment.SetEnvironmentVariable("DATABASE_PASSWORD", null); Environment.SetEnvironmentVariable("USER_PASSWORD", null); Environment.SetEnvironmentVariable("REMOTE_API_TOKEN", null); if (Directory.Exists(tempWorkDir)) Directory.Delete(tempWorkDir, true); } } /// /// P2-6: Server Streaming Size Limit (SB7) /// 服务端流式接收时严格限制 5 MiB,超过直接中断并返回 413 Payload Too Large /// private static async Task Test_P2_6_ServerStreamingSizeLimit() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_size_limit_1"; string token = "token_size_limit_1"; string tenantId = "t_size_limit_1"; string bundleId = "sb_p2_6_size_limit"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Size Limit School", deviceId, token); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } // Generate an oversized payload (5.2 MiB) const int payloadSize = 5 * 1024 * 1024 + 200 * 1024; // 5.2 MiB var dummyData = new byte[payloadSize]; Random.Shared.NextBytes(dummyData); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(dummyData) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.RequestEntityTooLarge) // 413 { throw new Exception($"Stream > 5 MiB expected 413 RequestEntityTooLarge, got {resp.StatusCode}"); } var err = await resp.Content.ReadAsStringAsync(); if (!err.Contains(SupportBundleErrorCodes.BundleTooLarge)) { throw new Exception($"Expected BundleTooLarge error code, got {err}"); } // Verify DB record remains in Collecting status (not mutated to Available) using var verifyScope = factory.Services.CreateScope(); var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var bundle = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); if (bundle.Status != SupportBundleStatuses.Collecting) { throw new Exception($"Bundle status should remain Collecting after 413 reject, got {bundle.Status}"); } } /// /// P2-7: Malicious Traversal Guard (SB8) /// 包含 ../evil.exe、子目录或冒号的 ZIP 包直接拦截并返回 400 InvalidZip /// private static async Task Test_P2_7_MaliciousTraversalGuard() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_traversal_1"; string token = "token_traversal_1"; string tenantId = "t_traversal_1"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Traversal Guard School", deviceId, token); } var maliciousEntries = new[] { "../../evil.exe", "subfolder/manifest.json", "C:manifest.json", "subdir\\runtime.json" }; foreach (var badName in maliciousEntries) { string bundleId = $"sb_traversal_{Guid.NewGuid():N}"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries(bundleId, deviceId); // Replace or add malicious entry entries.Remove("events.ndjson"); entries[badName] = Encoding.UTF8.GetBytes("MALICIOUS CONTENT"); var zipBytes = CreateZipPackage(entries); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"Malicious entry '{badName}' expected 400 BadRequest, got {resp.StatusCode}"); } var err = await resp.Content.ReadAsStringAsync(); if (!err.Contains(SupportBundleErrorCodes.InvalidZip)) { throw new Exception($"Expected InvalidZip errorCode for '{badName}', got {err}"); } } } /// /// P2-8: Compression Bomb Guard /// 压缩包解压总大小 > 10 MiB 时直接阻断并返回 400 ExpandedSizeExceeded /// private static async Task Test_P2_8_CompressionBombGuard() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_bomb_1"; string token = "token_bomb_1"; string tenantId = "t_bomb_1"; string bundleId = "sb_p2_8_bomb"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Bomb Guard School", deviceId, token); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries(bundleId, deviceId); // Add 11 MiB of zero bytes into events.ndjson (compresses to ~11 KiB) entries["events.ndjson"] = new byte[11 * 1024 * 1024]; var zipBytes = CreateZipPackage(entries); if (zipBytes.Length > 100 * 1024) { throw new Exception($"Test assumption invalid: compression bomb should compress small, but got {zipBytes.Length} bytes"); } var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"Compression bomb > 10 MiB expanded expected 400 BadRequest, got {resp.StatusCode}"); } var err = await resp.Content.ReadAsStringAsync(); if (!err.Contains(SupportBundleErrorCodes.ExpandedSizeExceeded)) { throw new Exception($"Expected ExpandedSizeExceeded errorCode, got {err}"); } } /// /// P2-9: Manifest Binding /// manifest.json 中的 SupportBundleId、DeviceId 或 FormatVersion 不匹配时拒绝并返回 400 InvalidManifest /// private static async Task Test_P2_9_ManifestBinding() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_manifest_1"; string token = "token_manifest_1"; string tenantId = "t_manifest_1"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Manifest School", deviceId, token); } // Test A: SupportBundleId mismatch { string bundleId = "sb_p2_9_id_mismatch"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries("sb_different_id", deviceId); var zipBytes = CreateZipPackage(entries); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"Manifest SupportBundleId mismatch expected 400 BadRequest, got {resp.StatusCode}"); } var err = await resp.Content.ReadAsStringAsync(); if (!err.Contains(SupportBundleErrorCodes.InvalidManifest)) { throw new Exception($"Expected InvalidManifest errorCode, got {err}"); } } // Test B: DeviceId mismatch { string bundleId = "sb_p2_9_dev_mismatch"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries(bundleId, "dev_different_id"); var zipBytes = CreateZipPackage(entries); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"Manifest DeviceId mismatch expected 400 BadRequest, got {resp.StatusCode}"); } } // Test C: FormatVersion != 1 { string bundleId = "sb_p2_9_ver_mismatch"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var entries = BuildValidBundleEntries(bundleId, deviceId); var manifest = new SupportBundleManifestV1 { FormatVersion = 99, // Invalid format version SupportBundleId = bundleId, DeviceId = deviceId, CreatedAtUtc = DateTimeOffset.UtcNow }; entries["manifest.json"] = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(manifest)); var zipBytes = CreateZipPackage(entries); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.BadRequest) { throw new Exception($"FormatVersion != 1 expected 400 BadRequest, got {resp.StatusCode}"); } } } /// /// P2-10: Concurrent Upload First-Wins (SB9) /// 模拟并发上传冲突:两个有效但哈希不同的 ZIP 包同时提交,严格原子确保仅 1 个胜出写入 DB,败者被拦截 /// private static async Task Test_P2_10_ConcurrentUploadFirstWins() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_first_wins_1"; string token = "token_first_wins_1"; string tenantId = "t_first_wins_1"; string bundleId = "sb_p2_10_first_wins"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "First-Wins School", deviceId, token); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } // Package A and Package B with different timestamps (guarantees different SHA256) var zipBytesA = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceId, DateTimeOffset.UtcNow.AddMinutes(-10))); var zipBytesB = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceId, DateTimeOffset.UtcNow.AddMinutes(-5))); string shaA = Convert.ToHexString(SHA256.HashData(zipBytesA)).ToLowerInvariant(); string shaB = Convert.ToHexString(SHA256.HashData(zipBytesB)).ToLowerInvariant(); if (shaA == shaB) throw new Exception("Test setup error: shaA and shaB must differ"); var reqA = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytesA) }; reqA.Headers.Add("X-Device-Id", deviceId); reqA.Headers.Add("X-Device-Token", token); var reqB = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytesB) }; reqB.Headers.Add("X-Device-Id", deviceId); reqB.Headers.Add("X-Device-Token", token); // Upload both concurrently var taskA = client.SendAsync(reqA); var taskB = client.SendAsync(reqB); var responses = await Task.WhenAll(taskA, taskB); int okCount = responses.Count(r => r.StatusCode == HttpStatusCode.OK); int conflictCount = responses.Count(r => r.StatusCode == HttpStatusCode.Conflict); if (okCount != 1 || conflictCount != 1) { throw new Exception($"SB9 First-Wins violated: Expected exactly 1x OK and 1x Conflict, got {okCount}x OK and {conflictCount}x Conflict"); } // Verify winner in DB using (var verifyScope = factory.Services.CreateScope()) { var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var saved = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); if (saved.Status != SupportBundleStatuses.Available) { throw new Exception($"Bundle status must be Available, got {saved.Status}"); } if (saved.Sha256 != shaA && saved.Sha256 != shaB) { throw new Exception($"Saved SHA256 '{saved.Sha256}' matches neither package"); } } // Test Sequential Idempotent Re-upload: re-uploading the WINNER's exact bytes returns 200 OK using (var verifyScope = factory.Services.CreateScope()) { var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var winner = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); var winnerBytes = winner.Sha256 == shaA ? zipBytesA : zipBytesB; var idempReq = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(winnerBytes) }; idempReq.Headers.Add("X-Device-Id", deviceId); idempReq.Headers.Add("X-Device-Token", token); var idempResp = await client.SendAsync(idempReq); if (idempResp.StatusCode != HttpStatusCode.OK) { throw new Exception($"Idempotent re-upload of winner package expected 200 OK, got {idempResp.StatusCode}"); } } } /// /// P2-10B: Same-Content Concurrent Upload (ChatGPT Final Concurrency Gate) /// 模拟两份完全相同 ZIP 包并发上传: /// 两个请求均成功返回 200 OK (包含 duplicate: true/false 标记), /// 严格杜绝败者删除 finalFilePath 造成数据库指向不存在文件的问题。 /// 最终断言:DB Status = Available, StoragePath 物理文件存在且 SHA256 吻合。 /// private static async Task Test_P2_10B_SameContentConcurrentUpload() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_same_content_1"; string token = "token_same_content_1"; string tenantId = "t_same_content_1"; string bundleId = "sb_p2_10b_same_content"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Same Content School", deviceId, token); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var fixedTimestamp = new DateTimeOffset(2026, 9, 25, 23, 0, 0, TimeSpan.Zero); var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceId, fixedTimestamp)); string expectedSha = Convert.ToHexString(SHA256.HashData(zipBytes)).ToLowerInvariant(); var reqA = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; reqA.Headers.Add("X-Device-Id", deviceId); reqA.Headers.Add("X-Device-Token", token); var reqB = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; reqB.Headers.Add("X-Device-Id", deviceId); reqB.Headers.Add("X-Device-Token", token); // Upload both concurrently var taskA = client.SendAsync(reqA); var taskB = client.SendAsync(reqB); var responses = await Task.WhenAll(taskA, taskB); int okCount = responses.Count(r => r.StatusCode == HttpStatusCode.OK); if (okCount != 2) { throw new Exception($"P2-10B failed: Both identical concurrent uploads must return 200 OK, got {okCount}x 200 OK and {responses.Count(r => r.StatusCode != HttpStatusCode.OK)}x other status."); } // Verify DB status & referenced file using (var verifyScope = factory.Services.CreateScope()) { var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var saved = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); if (saved.Status != SupportBundleStatuses.Available) { throw new Exception($"DB status must be Available, got {saved.Status}"); } if (string.IsNullOrWhiteSpace(saved.StoragePath)) { throw new Exception("DB StoragePath must not be null"); } if (Path.IsPathRooted(saved.StoragePath)) { throw new Exception($"DB StoragePath must be strictly relative, got '{saved.StoragePath}'"); } var envStorage = Environment.GetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE"); var storageRoot = !string.IsNullOrWhiteSpace(envStorage) ? envStorage : Path.Combine(AppContext.BaseDirectory, "storage", "support-bundles"); var physicalPath = Path.Combine(storageRoot, saved.StoragePath); if (!File.Exists(physicalPath)) { throw new Exception($"CRITICAL BUG DETECTED: DB points to StoragePath '{saved.StoragePath}' (Physical: '{physicalPath}') but the physical file was deleted!"); } var actualFileSha = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(physicalPath))).ToLowerInvariant(); if (actualFileSha != expectedSha || actualFileSha != saved.Sha256) { throw new Exception($"Physical file SHA ({actualFileSha}) does not match DB SHA ({saved.Sha256})"); } } } /// /// P2-11: TimedOut Terminal /// 诊断包一旦进入 TimedOut 或 Failed 终态,迟到的上传请求直接被 409 Conflict 拒绝,绝不复活 /// private static async Task Test_P2_11_TimedOutTerminal() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_timedout_1"; string token = "token_timedout_1"; string tenantId = "t_timedout_1"; string timedOutBundleId = "sb_p2_11_timedout"; string failedBundleId = "sb_p2_11_failed"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Terminal State School", deviceId, token); await CreateSupportBundleRecordAsync(db, timedOutBundleId, tenantId, deviceId, SupportBundleStatuses.TimedOut); await CreateSupportBundleRecordAsync(db, failedBundleId, tenantId, deviceId, SupportBundleStatuses.Failed); } var zipBytesTimedOut = CreateZipPackage(BuildValidBundleEntries(timedOutBundleId, deviceId)); var req1 = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{timedOutBundleId}/upload") { Content = new ByteArrayContent(zipBytesTimedOut) }; req1.Headers.Add("X-Device-Id", deviceId); req1.Headers.Add("X-Device-Token", token); var resp1 = await client.SendAsync(req1); if (resp1.StatusCode != HttpStatusCode.Conflict) { throw new Exception($"Upload to TimedOut bundle expected 409 Conflict, got {resp1.StatusCode}"); } var zipBytesFailed = CreateZipPackage(BuildValidBundleEntries(failedBundleId, deviceId)); var req2 = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{failedBundleId}/upload") { Content = new ByteArrayContent(zipBytesFailed) }; req2.Headers.Add("X-Device-Id", deviceId); req2.Headers.Add("X-Device-Token", token); var resp2 = await client.SendAsync(req2); if (resp2.StatusCode != HttpStatusCode.Conflict) { throw new Exception($"Upload to Failed bundle expected 409 Conflict, got {resp2.StatusCode}"); } // Verify DB records remain unchanged using var verifyScope = factory.Services.CreateScope(); var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var b1 = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == timedOutBundleId); var b2 = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == failedBundleId); if (b1.Status != SupportBundleStatuses.TimedOut || b2.Status != SupportBundleStatuses.Failed) { throw new Exception("Terminal states must be immutable and cannot be revived"); } } /// /// P2-12: Collection Failure /// 终端上报采集失败,服务端将状态推进至 Failed 并记录错误代号,禁止后续上传 /// private static async Task Test_P2_12_CollectionFailure() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_failure_1"; string token = "token_failure_1"; string tenantId = "t_failure_1"; string bundleId = "sb_p2_12_fail"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Failure School", deviceId, token); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var failReport = new SupportBundleFailureReportDto { ErrorCode = SupportBundleErrorCodes.CollectionFailure }; var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/failed") { Content = JsonContent.Create(failReport) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.OK) { throw new Exception($"Report failure expected 200 OK, got {resp.StatusCode}"); } // Verify DB status is Failed using (var verifyScope = factory.Services.CreateScope()) { var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var saved = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); if (saved.Status != SupportBundleStatuses.Failed) { throw new Exception($"Expected Failed status, got {saved.Status}"); } if (saved.ErrorCode != SupportBundleErrorCodes.CollectionFailure) { throw new Exception($"Expected ErrorCode {SupportBundleErrorCodes.CollectionFailure}, got {saved.ErrorCode}"); } } // Subsequent upload to this failed bundle should be rejected with 409 Conflict var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceId)); var uploadReq = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; uploadReq.Headers.Add("X-Device-Id", deviceId); uploadReq.Headers.Add("X-Device-Token", token); var uploadResp = await client.SendAsync(uploadReq); if (uploadResp.StatusCode != HttpStatusCode.Conflict) { throw new Exception($"Subsequent upload to Failed bundle expected 409 Conflict, got {uploadResp.StatusCode}"); } } /// /// P2-13: Private Storage /// 诊断包必须落入私有不可直接访问的目录,绝不存入 wwwroot,静态 HTTP 请求返回 404 /// private static async Task Test_P2_13_PrivateStorage() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string deviceId = "dev_private_1"; string token = "token_private_1"; string tenantId = "t_private_1"; string bundleId = "sb_p2_13_private"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, tenantId, "Private Storage School", deviceId, token); await CreateSupportBundleRecordAsync(db, bundleId, tenantId, deviceId, SupportBundleStatuses.Collecting); } var zipBytes = CreateZipPackage(BuildValidBundleEntries(bundleId, deviceId)); var req = new HttpRequestMessage(HttpMethod.Post, $"/api/device/support-bundles/{bundleId}/upload") { Content = new ByteArrayContent(zipBytes) }; req.Headers.Add("X-Device-Id", deviceId); req.Headers.Add("X-Device-Token", token); var resp = await client.SendAsync(req); if (resp.StatusCode != HttpStatusCode.OK) { throw new Exception($"Upload failed: {resp.StatusCode}"); } string storagePath; using (var verifyScope = factory.Services.CreateScope()) { var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var saved = await verifyDb.DeviceSupportBundles.AsNoTracking().FirstAsync(b => b.Id == bundleId); storagePath = saved.StoragePath ?? ""; } if (string.IsNullOrWhiteSpace(storagePath)) { throw new Exception("StoragePath must not be null or empty"); } if (Path.IsPathRooted(storagePath)) { throw new Exception($"DB StoragePath must be strictly relative, got '{storagePath}'"); } var envStorageP2 = Environment.GetEnvironmentVariable("CLASSNOTIFY_SUPPORT_BUNDLE_STORAGE"); var storageRootP2 = !string.IsNullOrWhiteSpace(envStorageP2) ? envStorageP2 : Path.Combine(AppContext.BaseDirectory, "storage", "support-bundles"); var physicalFile = Path.Combine(storageRootP2, storagePath); if (!File.Exists(physicalFile)) { throw new Exception($"StoragePath '{storagePath}' (Physical: '{physicalFile}') does not exist on disk"); } if (storagePath.Contains("wwwroot", StringComparison.OrdinalIgnoreCase) || physicalFile.Contains("wwwroot", StringComparison.OrdinalIgnoreCase)) { throw new Exception($"StoragePath '{storagePath}' MUST NOT be placed inside wwwroot!"); } // Test static URL access attempt via web client (e.g. /storage/support-bundles/...) var filename = Path.GetFileName(storagePath); var staticReq = new HttpRequestMessage(HttpMethod.Get, $"/storage/support-bundles/{DateTime.UtcNow:yyyyMMdd}/{filename}"); var staticResp = await client.SendAsync(staticReq); if (staticResp.StatusCode != HttpStatusCode.NotFound) { throw new Exception($"Static HTTP access to support bundle expected 404 NotFound, got {staticResp.StatusCode}"); } } /// /// P2-14: Zero Notification Impact /// 诊断包系统引入后,核心业务逻辑 (通知广播、生命周期、设备心跳及指令分发) 零破坏、零回归 /// private static async Task Test_P2_14_ZeroNotificationImpact() { using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); string teacherToken = factory.GenerateToken("usr_teacher_p214", "teacher1", "Teacher", "t_p214"); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await SeedTenantAndDeviceAsync(db, "t_p214", "Regression School", "dev_p214", "token_p214"); db.Users.Add(new User { Id = "usr_teacher_p214", Username = "teacher1", FullName = "Teacher One", Role = "Teacher", TenantId = "t_p214", PasswordHash = "hash", IsLocked = false, TokenVersion = 1 }); await db.SaveChangesAsync(); } // Verify standard notification post var notifDto = new NotificationDto { ClassId = "c_t_p214", Message = "Regression Notification Test" }; var notifReq = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send") { Content = JsonContent.Create(notifDto) }; notifReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherToken); var notifResp = await client.SendAsync(notifReq); if (notifResp.StatusCode != HttpStatusCode.OK && notifResp.StatusCode != HttpStatusCode.Created) { var err = await notifResp.Content.ReadAsStringAsync(); throw new Exception($"Notification send regression failed: {notifResp.StatusCode} - {err}"); } // Verify notification successfully stored in DB using (var verifyScope = factory.Services.CreateScope()) { var verifyDb = verifyScope.ServiceProvider.GetRequiredService(); var count = await verifyDb.Notifications.CountAsync(n => n.TenantId == "t_p214"); if (count == 0) { throw new Exception("Notification was not persisted in database"); } } } #endregion }