[CmdletBinding()] param( [string]$EnvFile = '.env', [string]$ApplicationImage = 'hla-lab7-app:local' ) $ErrorActionPreference = 'Stop' $projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path Set-Location $projectRoot function Invoke-CheckedDocker { param([Parameter(Mandatory=$true)][string[]]$Arguments, [string]$Failure = 'Docker command failed') $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { $output = & docker @Arguments 2>&1 $exitCode = $LASTEXITCODE } finally { $ErrorActionPreference = $previous } if($exitCode -ne 0){ throw "$Failure (exit $exitCode)" } return $output } function Get-ComposeArguments { param([string[]]$Tail) return @('compose','--env-file',$EnvFile) + $Tail } function Get-SecretCandidates { if(-not (Test-Path -LiteralPath $EnvFile)){ return @() } $result = @() foreach($line in Get-Content -LiteralPath $EnvFile) { if($line -notmatch '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$'){ continue } $name = $Matches[1] $value = $Matches[2].Trim() if($value.Length -ge 8 -and $name -match '(?i)(PASSWORD|TOKEN|SECRET|PRIVATE_KEY|UNSEAL|CREDENTIAL)') { $result += [pscustomobject]@{ Name = $name; Value = $value } } } return $result } $configText = Invoke-CheckedDocker (Get-ComposeArguments @('--profile','verification','config','--format','json')) 'docker compose config failed' $config = ($configText -join "`n") | ConvertFrom-Json $allowedPorts = @{ nginx = @{ ContainerPort = '8443/tcp'; PublishedPort = '8443' } openbao = @{ ContainerPort = '8200/tcp'; PublishedPort = '8200' } grafana = @{ ContainerPort = '3000/tcp'; PublishedPort = '3000' } } foreach($property in $config.services.PSObject.Properties) { $name = $property.Name $service = $property.Value if($service.privileged -eq $true){ throw "$name is privileged" } if($service.network_mode -eq 'host'){ throw "$name uses host networking" } foreach($volume in @($service.volumes) | Where-Object { $null -ne $_ }) { if("$($volume.source) $($volume.target)" -match '(?i)docker\.sock') { throw "$name mounts the Docker socket" } } } foreach($serviceName in 'api','worker') { $service = $config.services.$serviceName if(-not ($service.cap_drop -contains 'ALL')){ throw "$serviceName does not drop all capabilities" } if(@($service.cap_add | Where-Object { $null -ne $_ }).Count -gt 0){ throw "$serviceName adds capabilities" } if(-not $service.cpus -or -not $service.mem_limit -or -not $service.pids_limit){ throw "$serviceName has incomplete resource limits" } if($service.read_only -ne $true){ throw "$serviceName root filesystem is writable" } if(-not ($service.security_opt -contains 'no-new-privileges:true')){ throw "$serviceName lacks no-new-privileges" } } $runningServices = @(Invoke-CheckedDocker (Get-ComposeArguments @('ps','--services','--status','running')) 'Cannot list running services') foreach($required in 'api','worker') { if($runningServices -notcontains $required){ throw "$required must be running for the runtime boundary check" } $uid = ((Invoke-CheckedDocker (Get-ComposeArguments @('exec','-T',$required,'id','-u')) "Cannot read $required runtime UID") -join '').Trim() if($uid -notmatch '^\d+$' -or [int]$uid -eq 0){ throw "$required runs as root" } } $containerIds = @(Invoke-CheckedDocker (Get-ComposeArguments @('ps','-q')) 'Cannot list Compose containers') | Where-Object { $_ } if($containerIds.Count -eq 0){ throw 'No running Compose containers found' } foreach($containerId in $containerIds) { $inspect = ((Invoke-CheckedDocker @('inspect',$containerId) 'Container inspect failed') -join "`n") | ConvertFrom-Json $container = $inspect[0] $serviceName = $container.Config.Labels.'com.docker.compose.service' if($container.HostConfig.Privileged){ throw "$serviceName runtime container is privileged" } if($container.HostConfig.NetworkMode -eq 'host'){ throw "$serviceName runtime container uses host networking" } if(-not $container.HostConfig.PidsLimit -or -not $container.HostConfig.Memory -or -not $container.HostConfig.NanoCpus){ throw "$serviceName runtime container is missing resource limits" } if($serviceName -in @('api','worker')) { if(-not ($container.HostConfig.CapDrop -contains 'ALL')){ throw "$serviceName runtime container does not drop all capabilities" } if(@($container.HostConfig.CapAdd | Where-Object { $null -ne $_ }).Count -gt 0){ throw "$serviceName runtime container adds capabilities" } if(-not $container.HostConfig.ReadonlyRootfs){ throw "$serviceName runtime root filesystem is writable" } if(-not ($container.HostConfig.SecurityOpt -contains 'no-new-privileges:true')){ throw "$serviceName runtime container lacks no-new-privileges" } } foreach($mount in @($container.Mounts)) { if("$($mount.Source) $($mount.Destination)" -match '(?i)docker\.sock'){ throw "$serviceName runtime container mounts the Docker socket" } } foreach($portProperty in $container.NetworkSettings.Ports.PSObject.Properties) { foreach($binding in @($portProperty.Value) | Where-Object { $null -ne $_ }) { if(-not $allowedPorts.ContainsKey($serviceName)){ throw "$serviceName publishes unexpected port $($portProperty.Name)" } $expected = $allowedPorts[$serviceName] if($portProperty.Name -ne $expected.ContainerPort -or $binding.HostPort -ne $expected.PublishedPort){ throw "$serviceName publishes unexpected binding $($binding.HostPort):$($portProperty.Name)" } if($binding.HostIp -notin @('127.0.0.1','::1')){ throw "$serviceName is not loopback-bound" } } } } $trackedPrivate = @(& git ls-files -- .env 'secrets/*' '*.key' '*.pem' '*.p12' '*.pfx' '*.jks') if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' } if($trackedPrivate.Count -gt 0){ throw 'Git tracks private material' } $dockerIgnore = Get-Content -LiteralPath '.dockerignore' -Raw foreach($requiredRule in '(?m)^\.env\r?$','(?m)^secrets\r?$','(?m)^\*\.key\r?$') { if($dockerIgnore -notmatch $requiredRule){ throw ".dockerignore is missing required rule $requiredRule" } } $secretCandidates = @(Get-SecretCandidates) $trackedFiles = @(& git ls-files) if($LASTEXITCODE -ne 0){ throw 'git ls-files failed' } $textExtensions = @('.md','.txt','.yaml','.yml','.json','.xml','.properties','.conf','.hcl','.ps1','.sh','.java','.gradle','.example') foreach($path in $trackedFiles) { if(-not (Test-Path -LiteralPath $path -PathType Leaf)){ continue } $item = Get-Item -LiteralPath $path if($item.Length -gt 5MB -or $textExtensions -notcontains $item.Extension){ continue } $content = [System.IO.File]::ReadAllText($item.FullName) foreach($candidate in $secretCandidates) { if($content.Contains($candidate.Value)){ throw "Git-tracked file contains value from $($candidate.Name)" } } } $imageInspectText = Invoke-CheckedDocker @('image','inspect',$ApplicationImage) "Application image $ApplicationImage is unavailable" $imageInspect = (($imageInspectText -join "`n") | ConvertFrom-Json)[0] $imageMetadata = (($imageInspect.Config.Env -join "`n") + "`n" + ((Invoke-CheckedDocker @('history','--no-trunc','--format','{{.CreatedBy}}',$ApplicationImage) 'Image history failed') -join "`n")) foreach($candidate in $secretCandidates) { if($imageMetadata.Contains($candidate.Value)){ throw "Application image metadata contains value from $($candidate.Name)" } } Invoke-CheckedDocker @('run','--rm','--entrypoint','sh',$ApplicationImage,'-c','test ! -e /app/.env && test ! -e /app/secrets && test ! -e /app/runtime.env && ! find /app -type f \( -name "*.key" -o -name "*.p12" -o -name "*.jks" \) -print -quit | grep -q .') 'Application image contains a forbidden secret artifact' | Out-Null $composeLogs = (Invoke-CheckedDocker (Get-ComposeArguments @('logs','--no-color','--tail','2000')) 'Cannot read Compose logs') -join "`n" foreach($candidate in $secretCandidates) { if($composeLogs.Contains($candidate.Value)){ throw "Container logs contain value from $($candidate.Name)" } } $collector = Get-Content -LiteralPath 'infra/otel/collector.yaml' -Raw foreach($attribute in 'http.request.header.authorization','http.request.body','http.response.body','messaging.message.body','db.statement.parameters','url.query') { if($collector -notmatch "(?m)^\s*- key: $([regex]::Escape($attribute))\s*$"){ throw "Telemetry redaction is missing $attribute" } } foreach($pipeline in 'traces','metrics','logs') { if($collector -notmatch "(?ms)^\s{4}${pipeline}:\s+.*?processors:\s*\[[^\]]*attributes/redact[^\]]*\]"){ throw "Telemetry $pipeline pipeline does not use attributes/redact" } } foreach($serviceName in 'api','worker') { $environment = $config.services.$serviceName.environment if($environment.OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_REQUEST_HEADERS -ne '' -or $environment.OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_RESPONSE_HEADERS -ne '') { throw "$serviceName enables HTTP header capture" } } Write-Host "PASS: runtime isolation, non-root app/worker, resource and port boundaries, Git/image/log secret isolation, and telemetry redaction are enforced. Checked $($secretCandidates.Count) local secret values without printing them."