# ============================================================================== # ClassNotify P1 Batch 10: Remote Command Reliability & Audit Trail Real E2E Test # Validates live Windows Service execution, SignalR round-trip, client restart, # idempotency, and audit history against the live server and local client. # ============================================================================== param ( [string]$BaseUrl = "https://classnotify.paradise.eu.org", [string]$CredentialsPath = "C:\ProgramData\ClassNotify\device_credentials.json", [string]$Username = $env:CLASSNOTIFY_E2E_USERNAME, [string]$Password = $env:CLASSNOTIFY_E2E_PASSWORD ) $ErrorActionPreference = "Stop" if ([string]::IsNullOrWhiteSpace($Username) -or [string]::IsNullOrWhiteSpace($Password)) { throw "Security Guard: CLASSNOTIFY_E2E_USERNAME and CLASSNOTIFY_E2E_PASSWORD environment variables must be configured for E2E testing! Hardcoded fallback credentials are strictly prohibited." } Write-Host "==========================================================" -ForegroundColor Cyan Write-Host " ClassNotify P1 Batch 10: Live Physical Remote Command " -ForegroundColor Cyan Write-Host " E2E Test (Windows Service + Live Server + Real Client) " -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++ } } # --- Step 1: Pre-flight Verification of Local Environment --- Write-Host "`n>>> [1/6] Verifying Local Environment & Device Credentials..." -ForegroundColor Yellow if (-not (Test-Path $CredentialsPath)) { throw "Device credentials not found at '$CredentialsPath'. Device must be activated." } Add-Type -AssemblyName System.Security $rawBytes = [System.IO.File]::ReadAllBytes($CredentialsPath) $creds = $null try { # Try DPAPI decryption $entropy = [System.Text.Encoding]::UTF8.GetBytes("ClassNotify_Device_Credential_V1") $decrypted = [System.Security.Cryptography.ProtectedData]::Unprotect($rawBytes, $entropy, [System.Security.Cryptography.DataProtectionScope]::LocalMachine) $json = [System.Text.Encoding]::UTF8.GetString($decrypted) $creds = $json | ConvertFrom-Json } catch { # Fallback to plaintext JSON $json = [System.Text.Encoding]::UTF8.GetString($rawBytes) $creds = $json | ConvertFrom-Json } $deviceId = $creds.DeviceId $tenantId = $creds.TenantId $classId = $creds.ClassId Write-Host "Local Activated Device: $deviceId (Tenant: $tenantId, Class: $classId)" -ForegroundColor White $svc = Get-Service -Name "ClassNotifyService" -ErrorAction SilentlyContinue if (-not $svc -or $svc.Status -ne "Running") { throw "ClassNotifyService is not running on this machine!" } Write-Host "ClassNotifyService is Running." -ForegroundColor Green $clientProc = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue if (-not $clientProc) { Write-Host "ClassNotify.Client is not currently running. Waiting 5s for Service Watchdog..." -ForegroundColor Yellow Start-Sleep -Seconds 5 $clientProc = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue if (-not $clientProc) { Write-Host "Starting ClassNotify.Client directly..." -ForegroundColor Yellow Start-Process -FilePath "C:\Program Files\ClassNotify\Client\ClassNotify.Client.exe" Start-Sleep -Seconds 3 $clientProc = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue } if (-not $clientProc) { throw "ClassNotify.Client could not be found or started!" } } $initialClientPid = $clientProc.Id Write-Host "ClassNotify.Client running with PID: $initialClientPid (Session: $($clientProc.SessionId))" -ForegroundColor White Report-Result "Local Environment & Device Credentials Healthy" $true "DeviceId: $deviceId, Client PID: $initialClientPid" # --- Step 2: Authenticate Teacher / School Admin --- Write-Host "`n>>> [2/6] Authenticating Teacher on Server..." -ForegroundColor Yellow $loginBody = @{ username = $Username password = $Password } | ConvertTo-Json $loginRes = Invoke-RestMethod -Uri "$BaseUrl/api/auth/login" -Method Post -Body $loginBody -ContentType "application/json" if (-not $loginRes.success -or -not $loginRes.token) { throw "Login failed: $($loginRes.message)" } $token = $loginRes.token $authHeaders = @{ Authorization = "Bearer $token" } Report-Result "Teacher Authentication Succeeded" $true "User: $($loginRes.fullName), Role: $($loginRes.role)" # --- Step 3: Test Whitelist Enforcement (Reject Malicious / Unsupported Commands) --- Write-Host "`n>>> [3/6] Testing Whitelist Enforcement (Rejection of Non-Whitelisted Commands)..." -ForegroundColor Yellow $badCommands = @("rm -rf /", "powershell.exe -enc ...", "calc.exe", "whoami", "cmd.exe /c dir") $allRejected = $true foreach ($badCmd in $badCommands) { try { $body = @{ deviceId = $deviceId commandType = $badCmd } | ConvertTo-Json $res = Invoke-RestMethod -Uri "$BaseUrl/api/device-command/send" -Method Post -Headers $authHeaders -Body $body -ContentType "application/json" $allRejected = $false Write-Host " ERROR: Malicious command '$badCmd' was unexpectedly accepted!" -ForegroundColor Red } catch { # Expected: 400 Bad Request $statusCode = $_.Exception.Response.StatusCode.value__ if ($statusCode -ne 400) { $allRejected = $false Write-Host " ERROR: Malicious command '$badCmd' returned $statusCode instead of 400" -ForegroundColor Red } } } Report-Result "Server Strictly Rejects Arbitrary / Non-Whitelisted Commands" $allRejected "Tested: $($badCommands -join ', ')" # --- Step 4: Dispatch 'SelfCheck' Remote Command --- Write-Host "`n>>> [4/6] Dispatching 'SelfCheck' Remote Command via Live SignalR..." -ForegroundColor Yellow $selfCheckBody = @{ deviceId = $deviceId commandType = "SelfCheck" } | ConvertTo-Json $sendRes = Invoke-RestMethod -Uri "$BaseUrl/api/device-command/send" -Method Post -Headers $authHeaders -Body $selfCheckBody -ContentType "application/json" $cmdId = $sendRes.command.commandId Write-Host "SelfCheck Command dispatched: CommandId = $cmdId (Dispatched: $($sendRes.isDispatched))" -ForegroundColor White # Poll for execution result (up to 15 seconds) $selfCheckSuccess = $false $selfCheckDetails = "" $startTime = Get-Date for ($i = 0; $i -lt 30; $i++) { Start-Sleep -Milliseconds 500 try { $cmdStatus = Invoke-RestMethod -Uri "$BaseUrl/api/device-command/$cmdId" -Method Get -Headers $authHeaders if ($cmdStatus.status -eq "Succeeded") { $selfCheckSuccess = ($cmdStatus.resultCode -eq 0) $selfCheckDetails = "ResultCode=$($cmdStatus.resultCode), Duration=$($cmdStatus.durationMs)ms, Message: $($cmdStatus.resultMessage)" break } elseif ($cmdStatus.status -in @("Failed", "TimedOut", "Expired")) { $selfCheckDetails = "Ended with status '$($cmdStatus.status)': $($cmdStatus.resultMessage)" break } } catch { Write-Host " Polling error: $($_.Message)" -ForegroundColor DarkGray } } Report-Result "Live 'SelfCheck' Executed & Reported Succeeded by Windows Service" $selfCheckSuccess $selfCheckDetails # --- Step 5: Dispatch 'RestartClient' Remote Command (Physical Process Restart) --- Write-Host "`n>>> [5/6] Dispatching 'RestartClient' Remote Command (Physical Process Relaunch)..." -ForegroundColor Yellow $procBefore = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue | Select-Object -First 1 $pidBefore = if ($procBefore) { $procBefore.Id } else { 0 } Write-Host "ClassNotify.Client PID before RestartClient: $pidBefore" -ForegroundColor White $restartBody = @{ deviceId = $deviceId commandType = "RestartClient" } | ConvertTo-Json $restartRes = Invoke-RestMethod -Uri "$BaseUrl/api/device-command/send" -Method Post -Headers $authHeaders -Body $restartBody -ContentType "application/json" $restartCmdId = $restartRes.command.commandId Write-Host "RestartClient Command dispatched: CommandId = $restartCmdId" -ForegroundColor White # Wait for client process PID to change and new client to run $pidChanged = $false $newClientPid = 0 for ($i = 0; $i -lt 30; $i++) { Start-Sleep -Milliseconds 500 $curProc = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue | Select-Object -First 1 if ($curProc -and $curProc.Id -ne $pidBefore) { $pidChanged = $true $newClientPid = $curProc.Id break } } # Also verify server command status transitioned to Succeeded $restartSuccess = $false $restartDetails = "" for ($i = 0; $i -lt 20; $i++) { Start-Sleep -Milliseconds 500 try { $cmdStatus = Invoke-RestMethod -Uri "$BaseUrl/api/device-command/$restartCmdId" -Method Get -Headers $authHeaders if ($cmdStatus.status -eq "Succeeded") { $restartSuccess = $true $restartDetails = "Old PID: $pidBefore -> New PID: $newClientPid, Status: Succeeded, Code: $($cmdStatus.resultCode), Duration: $($cmdStatus.durationMs)ms" break } } catch {} } Report-Result "Physical Client Process Restarted via Remote Command" ($pidChanged -and $restartSuccess) $restartDetails # --- Step 6: Command Audit Trail Verification --- Write-Host "`n>>> [6/6] Verifying Remote Command Audit Trail & History..." -ForegroundColor Yellow $historyRes = Invoke-RestMethod -Uri "$BaseUrl/api/device-command/history?deviceId=$deviceId" -Method Get -Headers $authHeaders $hasSelfCheck = $false $hasRestart = $false foreach ($h in $historyRes) { if ($h.commandId -eq $cmdId -and $h.status -eq "Succeeded" -and $h.durationMs -ne $null) { $hasSelfCheck = $true } if ($h.commandId -eq $restartCmdId -and $h.status -eq "Succeeded" -and $h.durationMs -ne $null) { $hasRestart = $true } } $auditValid = $hasSelfCheck -and $hasRestart Report-Result "Audit Trail Recorded Both Commands with Status, Timestamps, DurationMs, and Result Codes" $auditValid "Found SelfCheck: $hasSelfCheck, Found RestartClient: $hasRestart, Total Records: $($historyRes.Count)" # --- Summary --- Write-Host "`n==========================================================" -ForegroundColor Cyan Write-Host " Test Summary: $passed Passed, $failed Failed " -ForegroundColor $(if ($failed -eq 0) { "Green" } else { "Red" }) Write-Host "==========================================================" -ForegroundColor Cyan if ($failed -gt 0) { exit 1 } else { exit 0 }