[CmdletBinding()] param([string]$EnvFile = '.env') $ErrorActionPreference = 'Stop' Set-Location (Join-Path $PSScriptRoot '..') function Invoke-Probe([string]$Target, [string]$TlsArguments) { $script = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -quiet -connect ${Target}:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1" $output = (& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script 2>&1) return ($output -join "`n") } $published = (& docker compose --env-file $EnvFile port api 8443 2>$null) -join "`n" if (-not [string]::IsNullOrWhiteSpace($published)) { throw "mTLS bypass: API port is published directly at $published" } $replicas = @(& docker compose --env-file $EnvFile ps -q api) if ($replicas.Count -lt 2) { throw 'At least two running API replicas are required for the mTLS test' } foreach($replica in $replicas) { $target = (& docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $replica).Trim() if ([string]::IsNullOrWhiteSpace($target)) { throw "No internal address found for API replica $replica" } $noCertificate = Invoke-Probe $target '' if ($noCertificate -match 'HTTP/1.1' -or $noCertificate -notmatch 'certificate required|handshake failure') { throw "mTLS failure: API replica $replica did not reject a missing client certificate during TLS handshake" } $foreignCa = Invoke-Probe $target '-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key' if ($foreignCa -match 'HTTP/1.1' -or $foreignCa -notmatch 'certificate unknown|unknown ca|bad certificate') { throw "mTLS failure: API replica $replica did not reject a foreign client CA during TLS handshake" } $wrongIdentity = Invoke-Probe $target '-cert /run/pki/wrong-lb-client/tls.crt -key /run/pki/wrong-lb-client/tls.key' if ($wrongIdentity -notmatch 'HTTP/1.1 403') { throw "mTLS failure: API replica $replica accepted or mishandled a trusted certificate with forbidden URI SAN" } $allowed = Invoke-Probe $target '-cert /run/pki/lb/tls.crt -key /run/pki/lb/tls.key' if ($allowed -notmatch 'HTTP/1.1 200') { throw "mTLS failure: allowed LB identity did not reach API replica $replica" } } Write-Host "PASS: $($replicas.Count) API replicas require a client certificate and LB CA; forbidden URI SAN is rejected; only the LB identity succeeds; no API port is published."