Модель угроз, worker bounds и полный TLS аудит

This commit is contained in:
EgorAnti
2026-11-27 14:39:11 +03:00
parent 415edbf722
commit 567d568569
12 changed files with 588 additions and 10 deletions
+25 -1
View File
@@ -49,9 +49,26 @@ probe_rejected() {
fi
}
probe_foreign_ca_rejected() {
label=$1; target=$2; name=$3
set +e
printf '\n' | openssl s_client -tls1_2 -brief -verify_return_error -verify_hostname "$name" \
-connect "$target" -servername "$name" -CAfile "$ca" \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key \
>/tmp/tls-probe.log 2>&1
status=$?
set -e
if [ "$status" -eq 0 ] || ! grep -Eq 'unknown ca|certificate unknown|bad certificate' /tmp/tls-probe.log; then
echo "FAIL: $label accepted a client certificate from a foreign CA" >&2
sed -n '1,12p' /tmp/tls-probe.log >&2
exit 1
fi
}
probe_ok postgres postgres:5432 postgres -starttls postgres
probe_ok minio minio:9000 minio
probe_ok openbao openbao:8200 openbao
probe_ok grafana grafana:3000 grafana
probe_ok redis redis:6379 redis \
-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key
@@ -70,24 +87,31 @@ probe_ok otel-ingest-worker otel-gateway:4318 otel-gateway \
probe_ok otel-metrics otel-collector:8889 otel-collector \
-cert /run/pki/prometheus-client/tls.crt -key /run/pki/prometheus-client/tls.key
probe_rejected otel-metrics otel-collector:8889 otel-collector
probe_foreign_ca_rejected otel-metrics otel-collector:8889 otel-collector
probe_ok loki loki:3100 loki \
-cert /run/pki/collector-client/tls.crt -key /run/pki/collector-client/tls.key
probe_ok loki-query loki:3100 loki \
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
probe_rejected loki loki:3100 loki
probe_foreign_ca_rejected loki loki:3100 loki
probe_ok tempo-ingest tempo:4318 tempo \
-cert /run/pki/collector-client/tls.crt -key /run/pki/collector-client/tls.key
probe_rejected tempo-ingest tempo:4318 tempo
probe_foreign_ca_rejected tempo-ingest tempo:4318 tempo
probe_ok tempo-query tempo:3200 tempo \
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
probe_rejected tempo-query tempo:3200 tempo
probe_foreign_ca_rejected tempo-query tempo:3200 tempo
probe_ok prometheus prometheus:9090 prometheus \
-cert /run/pki/grafana-client/tls.crt -key /run/pki/grafana-client/tls.key
probe_rejected prometheus prometheus:9090 prometheus
probe_foreign_ca_rejected prometheus prometheus:9090 prometheus
echo 'PASS: DB, S3, broker, Redis, Collector, telemetry backends and OpenBao verify server CA/hostname; all declared mTLS endpoints reject no-cert clients.'
echo 'PASS: DB, S3, broker, Redis, Collector, telemetry backends and OpenBao verify server CA/hostname; all declared mTLS endpoints reject no-cert and foreign-CA clients.'
'@
$probe | & docker compose --env-file $EnvFile run --rm -T --no-deps --entrypoint /bin/sh nginx -s
+49
View File
@@ -0,0 +1,49 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$BaseUrl = 'https://localhost:8443',
[string]$Python = 'python',
[switch]$SkipWorkerUnitTests,
[switch]$SkipPublicSecurity,
[switch]$IncludeFreshOpenBaoPolicy
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
& "$PSScriptRoot\test-mtls.ps1" -EnvFile $EnvFile
if($LASTEXITCODE -ne 0){ throw 'LB-to-API mTLS audit failed' }
if(-not $SkipPublicSecurity) {
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
& $Python tests/security.py --base-url $BaseUrl --ca-file $ca
if($LASTEXITCODE -ne 0){ throw 'Public TLS/ACL negative audit failed' }
}
# Includes server CA/hostname checks for every declared internal TLS endpoint,
# no-cert/foreign-CA checks, DB/Redis/RabbitMQ ACLs and exact role gateways.
& "$PSScriptRoot\test-internal-tls.ps1" -EnvFile $EnvFile
if($LASTEXITCODE -ne 0){ throw 'Internal TLS/ACL audit failed' }
& docker compose --env-file $EnvFile --profile verification run --rm private-bucket-check
if($LASTEXITCODE -ne 0){ throw 'MinIO private-bucket/API-worker ACL audit failed' }
& "$PSScriptRoot\test-openbao-runtime-boundaries.ps1" -EnvFile $EnvFile -SkipLivePolicy
if($LASTEXITCODE -ne 0){ throw 'OpenBao runtime-boundary audit failed' }
if($IncludeFreshOpenBaoPolicy) {
# SecretID deliberately has a 24 h TTL. Never substitute an operator/root
# token when it expires: refresh it through the documented bootstrap first.
& "$PSScriptRoot\test-openbao-policies.ps1" -EnvFile $EnvFile
if($LASTEXITCODE -ne 0){ throw 'OpenBao policy audit failed; refresh the scoped AppRole SecretID' }
} else {
Write-Host 'INFO: scoped OpenBao allow/deny test skipped; pass -IncludeFreshOpenBaoPolicy after refreshing the 24 h AppRole SecretID.'
}
& "$PSScriptRoot\test-worker-resource-bounds.ps1" -EnvFile $EnvFile `
-SkipUnitTests:$SkipWorkerUnitTests
if($LASTEXITCODE -ne 0){ throw 'Upload worker resource-bound audit failed' }
& "$PSScriptRoot\test-telemetry-redaction.ps1" -EnvFile $EnvFile -BaseUrl $BaseUrl
if($LASTEXITCODE -ne 0){ throw 'Telemetry redaction audit failed' }
Write-Host 'PASS: level-4 audit covered the declared TLS matrix, same/foreign/no-cert identity failures, data-plane ACLs, bounded upload worker and end-to-end telemetry non-disclosure.'
+13 -3
View File
@@ -1,5 +1,8 @@
[CmdletBinding()]
param([string]$EnvFile = '.env')
param(
[string]$EnvFile = '.env',
[switch]$SkipLivePolicy
)
$ErrorActionPreference = 'Stop'
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
@@ -76,6 +79,13 @@ $operatorArtifacts = @(Get-ChildItem -LiteralPath (Join-Path $projectRoot 'secre
Where-Object { $_.Name -match '(?i)(root.*token|unseal)' })
if($operatorArtifacts.Count -gt 0){ throw 'Root token or unseal material exists inside the project secrets tree' }
& "$PSScriptRoot\test-openbao-policies.ps1" -EnvFile $EnvFile
if(-not $SkipLivePolicy) {
& "$PSScriptRoot\test-openbao-policies.ps1" -EnvFile $EnvFile
}
Write-Host 'PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use separate AppRoles, scoped policies and read-only rendered files; operator material is absent.'
Write-Host 'PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use separate AppRoles and read-only rendered files; operator material is absent.'
if($SkipLivePolicy) {
Write-Host 'INFO: live scoped-policy probe skipped; it requires a non-expired 24 h AppRole SecretID.'
} else {
Write-Host 'PASS: scoped OpenBao allow/deny policies were verified with fresh AppRole credentials.'
}
+106
View File
@@ -0,0 +1,106 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[string]$BaseUrl = 'https://localhost:8443',
[int]$ExportWaitSeconds = 15
)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Set-Location $root
$ca = (Resolve-Path 'secrets\pki\public-ca\ca.crt').Path
$canary = 'otel-canary-' + [guid]::NewGuid().ToString('N')
$bodyPath = Join-Path $env:TEMP ('otel-body-' + [guid]::NewGuid().ToString('N') + '.json')
function Invoke-ExpectedHttp([string[]]$Arguments, [string]$ExpectedStatus) {
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$status = (& curl.exe --silent --show-error --output NUL --write-out '%{http_code}' `
--cacert $ca --ssl-no-revoke --connect-timeout 5 --max-time 15 @Arguments 2>$null) -join ''
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($exitCode -ne 0 -or $status -ne $ExpectedStatus){
throw "Telemetry canary request expected HTTP $ExpectedStatus but received $status"
}
}
function Invoke-GrafanaProbe([string]$Script) {
$Script = $Script.Replace("`r", '')
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Script))
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$command = "echo '$encoded' | base64 -d | sh -s -- '$canary'"
$output = @(& docker compose --env-file $EnvFile exec -T grafana sh -c $command 2>&1) -join "`n"
$exitCode = $LASTEXITCODE
} finally {
$ErrorActionPreference = $previous
}
if($exitCode -ne 0){ throw "Telemetry backend probe failed without exposing the canary: $output" }
return $output
}
try {
# Exercise both sensitive carriers. The first value is an invalid Bearer token;
# the second is inside a deliberately malformed JSON body and is never stored.
Invoke-ExpectedHttp @('-H', "Authorization: Bearer $canary",
"$($BaseUrl.TrimEnd('/'))/api/v1/users/me") '401'
[System.IO.File]::WriteAllText($bodyPath,
'{"username":"telemetry_probe","display_name":"' + $canary + '"',
[System.Text.UTF8Encoding]::new($false))
Invoke-ExpectedHttp @('-H','Content-Type: application/json','--data-binary',"@$bodyPath",
"$($BaseUrl.TrimEnd('/'))/api/v1/users") '400'
Start-Sleep -Seconds $ExportWaitSeconds
$logs = (& docker compose --env-file $EnvFile logs --no-color --tail 3000 2>&1) -join "`n"
if($LASTEXITCODE -ne 0){ throw 'Cannot read Compose logs for telemetry canary check' }
if($logs.Contains($canary)){ throw 'Telemetry canary appeared in container stdout/stderr logs' }
$backendProbe = @'
set -eu
canary=$1
ca=/run/pki/service-ca/ca.crt
cert=/run/pki/grafana-client/tls.crt
key=/run/pki/grafana-client/tls.key
tmp=/tmp/telemetry-redaction-$$
trap 'rm -f "$tmp".*' EXIT
curl -fsS --cacert "$ca" --cert "$cert" --key "$key" --get \
--data-urlencode 'query={service_name=~".+"}' \
--data-urlencode "limit=5000" \
https://loki:3100/loki/api/v1/query_range >"$tmp.loki"
if grep -Fq "$canary" "$tmp.loki"; then
echo 'Loki contains the telemetry canary' >&2
exit 20
fi
for tag in http.request.header.authorization http.request.body http.response.body \
messaging.message.body db.statement.parameters url.query; do
curl -fsS --cacert "$ca" --cert "$cert" --key "$key" \
"https://tempo:3200/api/search/tag/$tag/values" >"$tmp.tempo"
if grep -Fq "$canary" "$tmp.tempo"; then
echo "Tempo tag $tag contains the telemetry canary" >&2
exit 21
fi
done
curl -fsS --cacert "$ca" --cert "$cert" --key "$key" \
'https://prometheus:9090/api/v1/series?match%5B%5D=%7B__name__%3D~%22.%2B%22%7D' \
>"$tmp.prometheus"
if grep -Fq "$canary" "$tmp.prometheus"; then
echo 'Prometheus label set contains the telemetry canary' >&2
exit 22
fi
'@
Invoke-GrafanaProbe $backendProbe | Out-Null
Write-Host 'PASS: unique Authorization/body canary was absent from container logs, Loki records, Tempo sensitive tag values and Prometheus label sets.'
Write-Host 'PASS: telemetry backends were queried over CA-verified mTLS with the dedicated Grafana identity.'
} finally {
Remove-Item -LiteralPath $bodyPath -Force -ErrorAction SilentlyContinue
$canary = $null
}
+74
View File
@@ -0,0 +1,74 @@
[CmdletBinding()]
param(
[string]$EnvFile = '.env',
[switch]$SkipUnitTests
)
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
function Convert-DurationToMilliseconds([string]$Value) {
if($Value -notmatch '^([0-9]+)(ms|s|m)$'){ throw "Unsupported duration format: $Value" }
$number = [long]$Matches[1]
switch($Matches[2]) {
'ms' { return $number }
's' { return $number * 1000 }
'm' { return $number * 60000 }
}
}
$configText = & docker compose --env-file $EnvFile config --format json
if($LASTEXITCODE -ne 0){ throw 'docker compose config failed' }
$config = ($configText -join "`n") | ConvertFrom-Json
$worker = $config.services.worker
if($null -eq $worker){ throw 'worker service is missing' }
$cpu = [double]$worker.cpus
$memory = [long]$worker.mem_limit
$pids = [long]$worker.pids_limit
$environment = $worker.environment
$concurrency = [int]$environment.WORKER_CONCURRENCY
$prefetch = [int]$environment.WORKER_PREFETCH
$pixelLimit = [long]$environment.WORKER_MAX_IMAGE_PIXELS
$memoryBudget = [long]$environment.WORKER_MEMORY_BUDGET_BYTES
$jobTimeoutMs = Convert-DurationToMilliseconds ([string]$environment.JOB_TIMEOUT)
$leaseMs = Convert-DurationToMilliseconds ([string]$environment.JOB_LEASE_DURATION)
$memoryWaitMs = Convert-DurationToMilliseconds ([string]$environment.WORKER_MEMORY_WAIT)
if($cpu -le 0 -or $cpu -gt 1.0){ throw "worker CPU limit must be in (0,1], found $cpu" }
if($memory -ne 1GB){ throw "worker memory limit must be 1 GiB, found $memory bytes" }
if($pids -le 0 -or $pids -gt 256){ throw "worker PID limit is missing or excessive: $pids" }
if($concurrency -lt 1 -or $concurrency -gt 2){ throw "worker concurrency must be 1..2, found $concurrency" }
if($prefetch -lt 1 -or $prefetch -gt $concurrency){ throw "worker prefetch exceeds bounded concurrency" }
if($pixelLimit -ne 40000000){ throw "worker decoded-pixel limit must be 40,000,000" }
if($memoryBudget -le 0 -or $memoryBudget -gt 512MB -or $memoryBudget -ge $memory){
throw "worker in-process memory budget is not bounded below the container limit"
}
if($jobTimeoutMs -le 0 -or $jobTimeoutMs -gt 60000){ throw "worker job timeout exceeds 60 seconds" }
if($leaseMs -le $jobTimeoutMs){ throw "worker lease must outlive the processing timeout" }
if($memoryWaitMs -lt 0 -or $memoryWaitMs -gt 2000){ throw "worker memory permit wait exceeds 2 seconds" }
if($worker.read_only -ne $true -or $worker.cap_drop -notcontains 'ALL'){
throw 'worker must use read-only root and drop ALL capabilities'
}
$containerId = (& docker compose --env-file $EnvFile ps -q worker | Select-Object -First 1).Trim()
if(-not $containerId){ throw 'running worker container is required for runtime limit verification' }
$inspect = (& docker inspect $containerId | ConvertFrom-Json)[0]
if([long]$inspect.HostConfig.Memory -ne $memory){ throw 'runtime worker memory limit differs from rendered Compose' }
if([long]$inspect.HostConfig.NanoCpus -ne [long]($cpu * 1000000000)){ throw 'runtime worker CPU limit differs from rendered Compose' }
if(-not $inspect.HostConfig.ReadonlyRootfs -or $inspect.HostConfig.CapDrop -notcontains 'ALL'){
throw 'runtime worker filesystem/capability bounds differ from rendered Compose'
}
if(-not $SkipUnitTests) {
& .\gradlew.bat test `
--tests com.example.mtusi_messenger.worker.ImageVariantProcessorTest `
--tests com.example.mtusi_messenger.worker.AttachmentWorkerLimitsTest `
--no-daemon --console=plain
if($LASTEXITCODE -ne 0){ throw 'worker resource-bound unit tests failed' }
Write-Host 'PASS: image memory/pixel rejection and processing-timeout retry passed as executable unit tests.'
} else {
Write-Host 'INFO: worker unit tests skipped; only rendered/runtime bounds were verified.'
}
Write-Host "PASS: worker CPU=$cpu, RAM=$memory bytes, pids=$pids, concurrency=$concurrency, prefetch=$prefetch, pixels=$pixelLimit, image budget=$memoryBudget bytes, job timeout=$jobTimeoutMs ms and memory wait=$memoryWaitMs ms are bounded."