Files
mtusi2026lab7/scripts/verify-https-resilience.ps1
T

68 lines
2.8 KiB
PowerShell

[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$Python = 'python',
[string]$BaseUrl = 'https://localhost:8443'
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $projectRoot
if(-not (Test-Path (Join-Path $projectRoot 'compose.yaml'))) {
throw "Run the repository copy of this script: $projectRoot does not contain compose.yaml."
}
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
& "$PSScriptRoot\check-compose-hardening.ps1" -EnvFile $EnvFile
& "$PSScriptRoot\check-security-lifecycle.ps1"
& docker info --format '{{.ServerVersion}}' | Out-Null
if($LASTEXITCODE -ne 0){ throw 'Docker engine is unavailable' }
$replicas = @(& docker compose --env-file $EnvFile ps -q api)
if($replicas.Count -lt 2){ throw 'At least two running API replicas are required' }
function Run-Test([string[]]$Arguments) {
& $Python @Arguments
if($LASTEXITCODE -ne 0){ throw "HTTPS test failed: $($Arguments[0])" }
}
function Wait-HttpsReady([int]$TimeoutSeconds = 180) {
$probe = @'
import ssl, sys, urllib.request
context = ssl.create_default_context(cafile=sys.argv[2])
with urllib.request.urlopen(sys.argv[1].rstrip('/') + '/health/ready', context=context, timeout=2) as response:
raise SystemExit(0 if response.status == 200 else 1)
'@
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
do {
# Not ready yet is expected during recovery; do not turn it into a terminating error.
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& $Python -c $probe $BaseUrl $ca 2>&1 | Out-Null
$probeExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($probeExit -eq 0){ return }
Start-Sleep -Milliseconds 500
} while((Get-Date) -lt $deadline)
throw "HTTPS readiness did not recover within $TimeoutSeconds seconds"
}
# All clients receive an explicit CA file. This workflow has no insecure mode and never uses -k.
Wait-HttpsReady
Run-Test @('tests/smoke.py','--base-url',$BaseUrl,'--ca-file',$ca)
Run-Test @('tests/resilience.py','--mode','persistence','--action-script',(Resolve-Path 'scripts/restart.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
Run-Test @('tests/resilience.py','--mode','failover','--action-script',(Resolve-Path 'scripts/stop-one.cmd').Path,'--base-url',$BaseUrl,'--ca-file',$ca)
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& docker compose --env-file $EnvFile up -d --no-deps --scale api=2 api 2>&1 | Out-Null
$restoreExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($restoreExit -ne 0){ throw 'Failed to restore the stopped API replica' }
Write-Host 'PASS: HTTPS smoke, persistence restart and one-replica failure completed with CA and hostname verification enabled.'