# ============================================================================== # ClassNotify P1 Batch 4 Security & Authentication Automated Verification # Tests: PasswordHasher Migration, JWT Rotation & Validation, CORS, Rate Limiting # ============================================================================== 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" $PSNativeCommandUseErrorActionPreference = $false Write-Host "==========================================================" -ForegroundColor Cyan Write-Host " ClassNotify P1 Batch 4 Live Security Verification " -ForegroundColor Cyan Write-Host "==========================================================" -ForegroundColor Cyan $passed = 0 $failed = 0 function Report-Result([string]$testName, [bool]$condition, [string]$details = "") { if ($condition) { Write-Host "[PASS] $testName" -ForegroundColor Green if ($details) { Write-Host " $details" -ForegroundColor DarkGray } $script:passed++ } else { Write-Host "[FAIL] $testName" -ForegroundColor Red if ($details) { Write-Host " $details" -ForegroundColor Yellow } $script:failed++ } } # 1. Password Verification & Auto-Rehash Write-Host "`n--- [1/5] Testing PasswordHasher & Automatic Migration ---" -ForegroundColor Yellow try { $teacherUser = if ($env:CLASSNOTIFY_E2E_USERNAME) { $env:CLASSNOTIFY_E2E_USERNAME } else { "teacher_zhang" } $teacherPass = $env:CLASSNOTIFY_E2E_PASSWORD if (-not $teacherPass) { throw "CLASSNOTIFY_E2E_PASSWORD is required" } $loginBody = @{ username = $teacherUser; password = $teacherPass } | ConvertTo-Json $loginRes = Invoke-RestMethod -Uri "$BaseUrl/api/auth/login" -Method Post -Body $loginBody -ContentType "application/json" Report-Result "Login with valid teacher credentials" ($loginRes.success -eq $true) "User: $($loginRes.fullName), Role: $($loginRes.role)" $validToken = $loginRes.token # Verify DB hash in PostgreSQL via python on VPS $dbHash = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "sudo -u postgres psql -d classnotify -t -A -c ""SELECT \"\"PasswordHash\"\" FROM \"\"Users\"\" WHERE \"\"Username\"\" = 'teacher_zhang';""" $dbHash = ($dbHash -split "`r?`n" | Where-Object { $_ -match "\S" } | Select-Object -First 1).Trim() $isModernHash = $dbHash.StartsWith("AQAAAA") -and ($dbHash.Length -ge 80) Report-Result "DB PasswordHash upgraded to modern ASP.NET Core format" $isModernHash "Length: $($dbHash.Length) chars, Prefix: $($dbHash.Substring(0, 10))..." # Test wrong password $wrongPassFailed = $false try { $wrongBody = @{ username = "teacher_zhang"; password = "WrongPassword999!" } | ConvertTo-Json Invoke-RestMethod -Uri "$BaseUrl/api/auth/login" -Method Post -Body $wrongBody -ContentType "application/json" } catch { if ($_.Exception.Response.StatusCode -eq 401 -or $_.Exception.Message -match "401") { $wrongPassFailed = $true } } Report-Result "Wrong password rejected with 401 Unauthorized" $wrongPassFailed } catch { Report-Result "Password verification error: $($_.Message)" $false } # 2. JWT Verification (Strict Issuer, Audience, Signature) Write-Host "`n--- [2/5] Testing JWT Validation & Rotation ---" -ForegroundColor Yellow try { # Valid token call to /api/auth/me $headers = @{ Authorization = "Bearer $validToken" } $meRes = Invoke-RestMethod -Uri "$BaseUrl/api/auth/me" -Method Get -Headers $headers Report-Result "Valid JWT token authorized on /api/auth/me" ($meRes.userId -eq "usr_101") "UserId: $($meRes.userId), TenantId: $($meRes.tenantId)" # Tampered token $tamperedToken = $validToken.Substring(0, 25) + "X" + $validToken.Substring(26) $tamperedRejected = $false try { Invoke-RestMethod -Uri "$BaseUrl/api/auth/me" -Method Get -Headers @{ Authorization = "Bearer $tamperedToken" } } catch { if ($_.Exception.Response.StatusCode -eq 401 -or $_.Exception.Message -match "401") { $tamperedRejected = $true } } Report-Result "Tampered JWT token rejected with 401 Unauthorized" $tamperedRejected # Old / Invalid key token $oldToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJ1c3JfMTAxIiwidW5pcXVlX25hbWUiOiLlvKDogIHluIgiLCJyb2xlIjoiVGVhY2hlciIsInRlbmFudF9pZCI6InRfYmVpamluZ19ubzQiLCJuYmYiOjE3ODk1MDAwMDAsImV4cCI6MTc5MTAwMDAwMCwiaWF0IjoxNzg5NTAwMDAwLCJpc3MiOiJDbGFzc05vdGlmeS5TZXJ2ZXIiLCJhdWQiOiJDbGFzc05vdGlmeS5DbGllbnRzIn0.OldInvalidSignatureOldInvalidSignature000" $oldTokenRejected = $false try { Invoke-RestMethod -Uri "$BaseUrl/api/auth/me" -Method Get -Headers @{ Authorization = "Bearer $oldToken" } } catch { if ($_.Exception.Response.StatusCode -eq 401 -or $_.Exception.Message -match "401") { $oldTokenRejected = $true } } Report-Result "Old/Rotated JWT token rejected with 401 Unauthorized" $oldTokenRejected } catch { Report-Result "JWT verification error: $($_.Message)" $false } # 3. CORS Policy Tightening Write-Host "`n--- [3/5] Testing Production CORS Tightening ---" -ForegroundColor Yellow try { # Allowed origin: https://classnotify.paradise.eu.org $corsTest1 = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "curl -s -i -X OPTIONS http://127.0.0.1:5000/api/auth/login -H 'Origin: https://classnotify.paradise.eu.org' -H 'Access-Control-Request-Method: POST'" $hasAllowedOrigin = ($corsTest1 -match "Access-Control-Allow-Origin:\s*https://classnotify.paradise.eu.org") Report-Result "Production CORS permits https://classnotify.paradise.eu.org" $hasAllowedOrigin # Disallowed external origin: https://evil.example.com $corsTest2 = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "curl -s -i -X OPTIONS http://127.0.0.1:5000/api/auth/login -H 'Origin: https://evil.example.com' -H 'Access-Control-Request-Method: POST'" $blocksEvil = -not ($corsTest2 -match "Access-Control-Allow-Origin") Report-Result "Production CORS blocks untrusted origins (evil.example.com)" $blocksEvil # Disallowed localhost in production: http://localhost:5173 $corsTest3 = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "curl -s -i -X OPTIONS http://127.0.0.1:5000/api/auth/login -H 'Origin: http://localhost:5173' -H 'Access-Control-Request-Method: POST'" $blocksLocalhost = -not ($corsTest3 -match "Access-Control-Allow-Origin") Report-Result "Production CORS blocks localhost in Production" $blocksLocalhost } catch { Report-Result "CORS verification error: $($_.Message)" $false } # 4. Sensitive Log Redaction Check Write-Host "`n--- [4/5] Testing Sensitive Log Redaction ---" -ForegroundColor Yellow try { $recentLogs = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "journalctl -u classnotify -n 50 --no-pager" $hasRawPassword = $recentLogs -match "WrongPassword999!" -or ($teacherPass -and $recentLogs -match [regex]::Escape($teacherPass)) $hasRawJwt = $recentLogs -match "eyJhbGci" $isLogSanitized = (-not $hasRawPassword) -and (-not $hasRawJwt) Report-Result "Security logs redact passwords, hashes, and JWT tokens" $isLogSanitized "Checked recent 50 lines in journalctl" } catch { Report-Result "Log check error: $($_.Message)" $false } # 5. Environment & Zero-Leakage Audit Write-Host "`n--- [5/5] Testing Environment Configuration & File Permissions ---" -ForegroundColor Yellow try { $envPerms = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "ls -la /etc/classnotify/classnotify.env" $isChmod600 = $envPerms -match "-rw-------" -and $envPerms -match "root root" Report-Result "/etc/classnotify/classnotify.env permissions are strictly chmod 600 root:root" $isChmod600 $envPerms.Trim() $envKeys = ssh -i $SshKey -o StrictHostKeyChecking=no "root@${VpsHost}" "grep -o '^[^=]*=' /etc/classnotify/classnotify.env" $hasAllKeys = ($envKeys -match "Jwt__SigningKey=") -and ($envKeys -match "Jwt__Issuer=") -and ($envKeys -match "Jwt__Audience=") -and ($envKeys -match "Jwt__LifetimeDays=") Report-Result "All required JWT environment keys exist in /etc/classnotify/classnotify.env" $hasAllKeys } catch { Report-Result "Environment audit error: $($_.Message)" $false } Write-Host "`n==========================================================" -ForegroundColor Cyan Write-Host " Verification Summary: $passed Passed, $failed Failed " -ForegroundColor $(if ($failed -eq 0) { "Green" } else { "Red" }) Write-Host "==========================================================" -ForegroundColor Cyan if ($failed -gt 0) { exit 1 }