# ============================================================================== # ClassNotify P2.3: Supplemental Verification Suite (6 Final Security & Stability Gates) # ============================================================================== param ( [string]$BaseUrl = "https://classnotify.paradise.eu.org", [string]$VpsHost = "158.179.179.29", [string]$SshKey = "C:\Users\Administrator\.ssh\id_rsa_tokyo" ) $ErrorActionPreference = "Continue" Add-Type -AssemblyName System.Net.Http Add-Type -AssemblyName System.Security Write-Host "==========================================================" -ForegroundColor Cyan Write-Host " ClassNotify P2.3 Supplemental Stability & Security Gates " -ForegroundColor Cyan Write-Host "==========================================================" -ForegroundColor Cyan $passed = 0 $failed = 0 function Report-Result([string]$gateName, [bool]$passedCondition, [string]$details = "") { if ($passedCondition) { Write-Host " [PASS] $gateName" -ForegroundColor Green if ($details) { Write-Host " $details" -ForegroundColor DarkGray } $script:passed++ } else { Write-Host " [FAIL] $gateName" -ForegroundColor Red if ($details) { Write-Host " $details" -ForegroundColor Yellow } $script:failed++ } } function Invoke-RemoteSql([string]$sql) { $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($sql)) $remoteCmd = "echo '$b64' | base64 -d > /tmp/run_query.sql && sudo -u postgres psql -d classnotify -t -A -F '|' -f /tmp/run_query.sql && rm -f /tmp/run_query.sql" return (ssh -i $SshKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes root@$VpsHost $remoteCmd).Trim() } function Invoke-RemoteBash([string]$cmd) { $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($cmd)) $remoteCmd = "echo '$b64' | base64 -d > /tmp/run_cmd.sh && bash /tmp/run_cmd.sh && rm -f /tmp/run_cmd.sh" return (ssh -i $SshKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes root@$VpsHost $remoteCmd).Trim() } $handler = [System.Net.Http.HttpClientHandler]::new() $http = [System.Net.Http.HttpClient]::new($handler) $http.Timeout = [TimeSpan]::FromSeconds(15) function Send-HttpReq([string]$method, [string]$url, [byte[]]$body, [string]$contentType, [hashtable]$headers) { $req = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::$method, $url) if ($body -ne $null) { $content = [System.Net.Http.ByteArrayContent]::new($body) if ($contentType) { $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($contentType) } $req.Content = $content } if ($headers) { foreach ($k in $headers.Keys) { $req.Headers.TryAddWithoutValidation($k, [string]$headers[$k]) | Out-Null } } return $http.SendAsync($req).GetAwaiter().GetResult() } # 1. Login Teacher in Tenant A (t_beijing_no4) $tUser = [Environment]::GetEnvironmentVariable('CLASSNOTIFY_E2E_USERNAME', 'User') $tPass = [Environment]::GetEnvironmentVariable('CLASSNOTIFY_E2E_PASSWORD', 'User') $loginUrl = "$BaseUrl/api/auth/login" $loginPayload = [System.Text.Encoding]::UTF8.GetBytes((@{ username = $tUser; password = $tPass } | ConvertTo-Json)) $resLogin = Send-HttpReq "Post" $loginUrl $loginPayload "application/json" $null $teacherToken = ($resLogin.Content.ReadAsStringAsync().GetAwaiter().GetResult() | ConvertFrom-Json).token # Load local device credentials (Tenant A) $credsPath = "C:\ProgramData\ClassNotify\device_credentials.json" $bytes = [System.IO.File]::ReadAllBytes($credsPath) $entropy = [System.Text.Encoding]::UTF8.GetBytes("ClassNotify_Device_Credential_V1") $dec = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, [System.Security.Cryptography.DataProtectionScope]::LocalMachine) $creds = [System.Text.Encoding]::UTF8.GetString($dec) | ConvertFrom-Json $deviceId = $creds.DeviceId $deviceToken = $creds.DeviceToken $sampleJpeg = [byte[]]@( 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43, 0x00, 0x08, 0x06, 0x06, 0x07, 0x06, 0x05, 0x08, 0x07, 0x07, 0x07, 0x09, 0x09, 0x08, 0x0A, 0x0C, 0x14, 0x0D, 0x0C, 0x0B, 0x0B, 0x0C, 0x19, 0x12, 0x13, 0x0F, 0x14, 0x1D, 0x1A, 0x1F, 0x1E, 0x1D, 0x1A, 0x1C, 0x1C, 0x20, 0x24, 0x2E, 0x27, 0x20, 0x22, 0x2C, 0x23, 0x1C, 0x1C, 0x28, 0x37, 0x29, 0x2C, 0x30, 0x31, 0x34, 0x34, 0x34, 0x1F, 0x27, 0x39, 0x3D, 0x38, 0x32, 0x3C, 0x2E, 0x33, 0x34, 0x32, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00, 0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0x7F, 0x00, 0xFF, 0xD9 ) # ------------------------------------------------------------------------------ # Gate S1: Valid JWT Cross-Tenant Visual Receipt Access Blocked (403) # ------------------------------------------------------------------------------ Write-Host "`n>>> [Supplemental Gate 1] Testing Valid JWT Cross-Tenant Access Rejection (403)..." -ForegroundColor Yellow $shanghaiNotifId = "msg_emerg_1790182819050_9ce0" $shanghaiDevId = "dev_shanghai_target_01" $crossTenantUrl = "$BaseUrl/api/notifications/$shanghaiNotifId/receipts/$shanghaiDevId/visual-receipt" $resS1 = Send-HttpReq "Get" $crossTenantUrl $null $null @{ "Authorization" = "Bearer $teacherToken" } $is403 = ([int]$resS1.StatusCode -eq 403) Report-Result "Cross-Tenant Valid JWT Blocked (403)" $is403 "HTTP $([int]$resS1.StatusCode) - Tenant A teacher forbidden from Tenant B receipt" # ------------------------------------------------------------------------------ # Gate S2: Disabled Device / Disabled Tenant Upload Rejected (401/403) # ------------------------------------------------------------------------------ Write-Host "`n>>> [Supplemental Gate 2] Testing Disabled Device Upload Rejection..." -ForegroundColor Yellow # Temporarily disable device in DB Invoke-RemoteSql "UPDATE ""Devices"" SET ""IsActive"" = false WHERE ""Id"" = '$deviceId';" | Out-Null $uploadUrl = "$BaseUrl/api/device/notifications/msg_1790129104698_c152/visual-receipt" $resS2 = Send-HttpReq "Post" $uploadUrl $sampleJpeg "image/jpeg" @{ "X-Device-Id" = $deviceId "X-Device-Token" = $deviceToken } # Re-enable device immediately Invoke-RemoteSql "UPDATE ""Devices"" SET ""IsActive"" = true WHERE ""Id"" = '$deviceId';" | Out-Null $isDisBlocked = ([int]$resS2.StatusCode -eq 401 -or [int]$resS2.StatusCode -eq 403) Report-Result "Disabled Device Upload Blocked" $isDisBlocked "HTTP $([int]$resS2.StatusCode) when device.IsActive = false" # ------------------------------------------------------------------------------ # Gate S3: Client Fail-Silent Guard # ------------------------------------------------------------------------------ Write-Host "`n>>> [Supplemental Gate 3] Verifying Client Fail-Silent Execution (No Throw)..." -ForegroundColor Yellow $failSilentExe = "C:\Users\Administrator\.gemini\antigravity\scratch\ClassNotify\tests\VisualReceiptFailSilentTest\bin\Debug\net8.0-windows\VisualReceiptFailSilentTest.exe" $out = (& $failSilentExe 2>&1) -join " " $failSilentOk = ($LASTEXITCODE -eq 0 -and $out -like "*SUCCESS*") Report-Result "Client SimpleVisualReceipt.Capture(null) Fail-Silent" $failSilentOk "Returned null safely without throwing ($out)" # ------------------------------------------------------------------------------ # Gate S4: CleanupWorker Deletion-Failure Retention Safety & Clean Expire # ------------------------------------------------------------------------------ Write-Host "`n>>> [Supplemental Gate 4] Verifying CleanupWorker File Deletion & Status Transition..." -ForegroundColor Yellow # Phase 1: Fault Injection - When file cannot be deleted, state MUST remain Available + Path intact $testFailReceiptId = "rcpt_fail_" + (Get-Random) $testFailNotifId = "msg_fail_" + (Get-Random) $todayDir = Get-Date -Format "yyyyMMdd" $failFilePath = "/var/lib/classnotify/visual-receipts/$todayDir/${testFailReceiptId}.jpg" # Create immutable test file on VPS (chattr +i) Invoke-RemoteBash "mkdir -p /var/lib/classnotify/visual-receipts/$todayDir && echo 'JPEG_FAIL_TEST' > $failFilePath && chattr +i $failFilePath" | Out-Null $sqlFailPrep = @" INSERT INTO "Notifications" ("Id", "TenantId", "ClassroomId", "Title", "Message", "SenderName", "Priority", "CreatedAt", "ExpiresAt", "Voice", "Shake", "DurationSeconds") VALUES ('$testFailNotifId', 't_beijing_no4', 'cls_802', 'Fail Test', 'Body', 'System', 'Normal', NOW(), NOW() + INTERVAL '1 hour', false, false, 15) ON CONFLICT ("Id") DO NOTHING; INSERT INTO "NotificationReceipts" ("Id", "NotificationId", "DeviceId", "Status", "VisualReceiptState", "VisualReceiptPath", "VisualReceiptExpiresAt", "UpdatedAt") VALUES ('$testFailReceiptId', '$testFailNotifId', '$deviceId', 'Delivered', 'Available', '$todayDir/${testFailReceiptId}.jpg', NOW() - INTERVAL '2 hours', NOW()); "@ Invoke-RemoteSql $sqlFailPrep | Out-Null # Restart service to trigger cleanup pass Invoke-RemoteBash "systemctl restart classnotify.service && sleep 4" | Out-Null # Verify DB state: MUST STILL BE Available because physical file could not be deleted! $dbCheckFail = "SELECT ""VisualReceiptState"", ""VisualReceiptPath"" FROM ""NotificationReceipts"" WHERE ""Id"" = '$testFailReceiptId';" $resFail = Invoke-RemoteSql $dbCheckFail $fieldsFail = if ($resFail) { $resFail.Split('|') } else { @("", "") } $faultSafetyPass = ($fieldsFail[0] -eq "Available" -and -not [string]::IsNullOrEmpty($fieldsFail[1])) # Phase 2: Recovery - Remove immutable flag (chattr -i), trigger cleanup again, verify deletion & Expired status Invoke-RemoteBash "chattr -i $failFilePath && systemctl restart classnotify.service && sleep 4" | Out-Null $postStatus = Invoke-RemoteBash "test -f $failFilePath && echo 'STILL_EXISTS' || echo 'DELETED'" $resRecover = Invoke-RemoteSql $dbCheckFail $fieldsRecover = if ($resRecover) { $resRecover.Split('|') } else { @("", "") } $recoveryPass = ($postStatus -eq "DELETED" -and $fieldsRecover[0] -eq "Expired" -and [string]::IsNullOrEmpty($fieldsRecover[1])) Report-Result "CleanupWorker Deletion-Failure Retention Safety & Clean Expire" ($faultSafetyPass -and $recoveryPass) "Fault-injection: State preserved as '$($fieldsFail[0])' when undeletable; Recovered: File $postStatus, State '$($fieldsRecover[0])'" # ------------------------------------------------------------------------------ # Gate S5: Concurrent Duplicate Upload (First Wins, True Mutex Integrity) # ------------------------------------------------------------------------------ Write-Host "`n>>> [Supplemental Gate 5] Testing Concurrent Duplicate Upload (First Wins)..." -ForegroundColor Yellow $concNotifId = "msg_conc_" + (Get-Random) $concReceiptId = "rcpt_conc_" + (Get-Random) # Insert fresh notification and receipt into DB $sqlConcPrep = @" INSERT INTO "Notifications" ("Id", "TenantId", "ClassroomId", "Title", "Message", "SenderName", "Priority", "CreatedAt", "ExpiresAt", "Voice", "Shake", "DurationSeconds") VALUES ('$concNotifId', 't_beijing_no4', 'cls_802', 'Conc Test', 'Body', 'System', 'Normal', NOW(), NOW() + INTERVAL '1 hour', false, false, 15) ON CONFLICT ("Id") DO NOTHING; INSERT INTO "NotificationReceipts" ("Id", "NotificationId", "DeviceId", "Status", "VisualReceiptState", "UpdatedAt") VALUES ('$concReceiptId', '$concNotifId', '$deviceId', 'Delivered', 'None', NOW()); "@ Invoke-RemoteSql $sqlConcPrep | Out-Null $concUploadUrl = "$BaseUrl/api/device/notifications/$concNotifId/visual-receipt" # Prepare 2 distinct payloads with known SHA256 hashes $jpegA = [byte[]]$sampleJpeg.Clone() $jpegA[20] = 0x11 $shaA = [BitConverter]::ToString([System.Security.Cryptography.SHA256]::Create().ComputeHash($jpegA)).Replace("-", "").ToLowerInvariant() $jpegB = [byte[]]$sampleJpeg.Clone() $jpegB[20] = 0x22 $shaB = [BitConverter]::ToString([System.Security.Cryptography.SHA256]::Create().ComputeHash($jpegB)).Replace("-", "").ToLowerInvariant() # Fire concurrently $reqA = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $concUploadUrl) $contentA = [System.Net.Http.ByteArrayContent]::new($jpegA) $contentA.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("image/jpeg") $reqA.Content = $contentA $reqA.Headers.TryAddWithoutValidation("X-Device-Id", $deviceId) | Out-Null $reqA.Headers.TryAddWithoutValidation("X-Device-Token", $deviceToken) | Out-Null $reqB = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $concUploadUrl) $contentB = [System.Net.Http.ByteArrayContent]::new($jpegB) $contentB.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("image/jpeg") $reqB.Content = $contentB $reqB.Headers.TryAddWithoutValidation("X-Device-Id", $deviceId) | Out-Null $reqB.Headers.TryAddWithoutValidation("X-Device-Token", $deviceToken) | Out-Null $taskA = $http.SendAsync($reqA) $taskB = $http.SendAsync($reqB) [System.Threading.Tasks.Task]::WaitAll(@($taskA, $taskB)) $resConcA = $taskA.Result $resConcB = $taskB.Result # Check winner SHA256 in DB $dbCheckWinner = "SELECT ""VisualReceiptSha256"" FROM ""NotificationReceipts"" WHERE ""Id"" = '$concReceiptId';" $winnerSha = Invoke-RemoteSql $dbCheckWinner $winnerValid = ($winnerSha -eq $shaA -or $winnerSha -eq $shaB) # Phase 2: Send 3rd payload C sequentially and verify winner SHA256 is NEVER overwritten $jpegC = [byte[]]$sampleJpeg.Clone() $jpegC[20] = 0x33 $resConcC = Send-HttpReq "Post" $concUploadUrl $jpegC "image/jpeg" @{ "X-Device-Id" = $deviceId; "X-Device-Token" = $deviceToken } $finalSha = Invoke-RemoteSql $dbCheckWinner $noOverwrite = ($finalSha -eq $winnerSha) $concOk = ($resConcA.IsSuccessStatusCode -and $resConcB.IsSuccessStatusCode -and $resConcC.IsSuccessStatusCode -and $winnerValid -and $noOverwrite) Report-Result "Concurrent Duplicate Upload (First Wins Mutex Integrity)" $concOk "Concurrent A($($resConcA.StatusCode)) & B($($resConcB.StatusCode)), Winner SHA256 locked ($winnerSha), Subsequent C($($resConcC.StatusCode)) did not overwrite." # ------------------------------------------------------------------------------ # Gate S6: Backward Compatibility (P2.2 Client without Visual Receipt) # ------------------------------------------------------------------------------ Write-Host "`n>>> [Supplemental Gate 6] Testing Backward Compatibility with P2.2 Notifications..." -ForegroundColor Yellow $legacyCount = [int](Invoke-RemoteSql 'SELECT COUNT(*) FROM "NotificationReceipts" WHERE "VisualReceiptState" = ''None'';') $legacyOk = ($legacyCount -gt 0) Report-Result "Backward Compatibility (Legacy Receipts Safe)" $legacyOk "Found $legacyCount legacy receipts with VisualReceiptState='None'" Write-Host "`n==========================================================" -ForegroundColor Cyan Write-Host " Supplemental Quality Gates: Passed=$passed, Failed=$failed " -ForegroundColor $(if ($failed -eq 0) { "Green" } else { "Red" }) Write-Host "==========================================================" -ForegroundColor Cyan if ($failed -gt 0) { exit 1 } exit 0