From 567d568569c4147d835bbd2801b69cb7415329e4 Mon Sep 17 00:00:00 2001 From: EgorAnti Date: Fri, 27 Nov 2026 14:39:11 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=BE=D0=B4=D0=B5=D0=BB=D1=8C=20=D1=83?= =?UTF-8?q?=D0=B3=D1=80=D0=BE=D0=B7,=20worker=20bounds=20=D0=B8=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D0=BD=D1=8B=D0=B9=20TLS=20=D0=B0=D1=83=D0=B4=D0=B8?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 14 ++ REPORT.md | 1 + contracts/trust-matrix.md | 2 + evidence/level4-security-audit.txt | 145 ++++++++++++++++++ scripts/test-internal-tls.ps1 | 26 +++- scripts/test-level4-security-audit.ps1 | 49 ++++++ scripts/test-openbao-runtime-boundaries.ps1 | 16 +- scripts/test-telemetry-redaction.ps1 | 106 +++++++++++++ scripts/test-worker-resource-bounds.ps1 | 74 +++++++++ security/THREAT_MODEL.md | 12 +- .../worker/AttachmentWorkerLimitsTest.java | 123 +++++++++++++++ .../worker/ImageVariantProcessorTest.java | 30 ++++ 12 files changed, 588 insertions(+), 10 deletions(-) create mode 100644 evidence/level4-security-audit.txt create mode 100644 scripts/test-level4-security-audit.ps1 create mode 100644 scripts/test-telemetry-redaction.ps1 create mode 100644 scripts/test-worker-resource-bounds.ps1 create mode 100644 src/test/java/com/example/mtusi_messenger/worker/AttachmentWorkerLimitsTest.java diff --git a/README.md b/README.md index 83fe832..097edf2 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,20 @@ docker compose --env-file .env --profile verification run --rm private-bucket-ch .\scripts\test-openbao-runtime-boundaries.ps1 ``` +Единый аудит уровня 4 дополнительно проверяет всю заявленную TLS/mTLS-матрицу, +same-CA wrong-role/foreign-CA/no-cert отказы, DB/Redis/RabbitMQ/MinIO ACL, +фактические CPU/RAM/PID limits worker, 40M pixel и 512 MiB processing budget, +60 s job timeout и отсутствие уникального Authorization/body canary в +stdout/stderr, Loki, Tempo и Prometheus: + +```powershell +.\scripts\test-level4-security-audit.ps1 +``` + +Scoped OpenBao allow/deny probe требует неистёкший AppRole SecretID (TTL 24 h). +После его документированного обновления добавьте +`-IncludeFreshOpenBaoPolicy`; аудит намеренно не использует root token как fallback. + Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): diff --git a/REPORT.md b/REPORT.md index 1a31b75..e242c5d 100644 --- a/REPORT.md +++ b/REPORT.md @@ -38,6 +38,7 @@ TODO: схема процессов/хранилищ, источник исти | Отказ одной API-реплики | тот же сценарий, mode `failover` | PASS: до отказа наблюдались 2 реплики; после остановки выбранной реплики — 7 успешных записей без неуспешных попыток, восстановление за 5.042 с (предыдущий прогон — 4.763 с); подтверждённые данные не потеряны | `evidence/verify-https-resilience.txt` | | Остальные пункты уровня 3 | TODO | TODO | TODO | | Контейнерные исключения и dependency/image scan | `scripts/check-compose-hardening.ps1`, `scripts/scan-dependencies.ps1`, Trivy image scan | PASS: OSV 139 resolved deps → 0 findings после обновлений; Trivy Java HIGH/CRITICAL → 0; оставшиеся OS-находки разобраны по reachability/fix/временным контролям, stateful writable root объяснён | `evidence/dependency-image-scan.txt` | +| Threat model, worker bounds и полный TLS/telemetry audit | `scripts/test-level4-security-audit.ps1`; worker unit tests | PASS: 13 конкретных угроз связаны с контролями/negative tests; вся заявленная TLS-матрица проверена на CA/hostname и no-cert/foreign-CA, role gateways — на same-CA wrong role; data-plane ACL denied; worker ограничен 1 CPU/1 GiB/256 PID, concurrency 2, 40M pixels, 512 MiB processing budget и 60 s; Authorization/body canary отсутствует в logs/Loki/Tempo/Prometheus | `security/THREAT_MODEL.md`, `evidence/level4-security-audit.txt` | | Выбранный трек 5, если заявлен | TODO | TODO | TODO | TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 419fa42..15368d3 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -67,6 +67,8 @@ burst на границе окна; лимитер ограничивает rate | Read-only root и capability drop | Stateless-сервисы используют `read_only: true` и `cap_drop: ALL`; везде `no-new-privileges:true`, CPU/RAM/PID limits и отдельный tmpfs | `scripts/check-compose-hardening.ps1` проверяет каждый сервис из `docker compose config`; `scripts/test-container-secret-boundaries.ps1` сверяет runtime | **PASS** | | Stateful writable-root исключения | Только postgres, redis, rabbitmq и minio сохраняют writable root: их entrypoints перед сменой UID подготавливают persistent named volume. Drop шести опасных capabilities и `no-new-privileges` сохранены; tmpfs выделен отдельно | Скрипт печатает причину каждого исключения и требует ожидаемый data volume; вывод в `evidence/dependency-image-scan.txt` | **PASS (4 объяснённых исключения)** | | Dependency/image scan | OSV по Gradle `runtimeClasspath`; Trivy по собранному `hla-lab7-app:local`. Для каждого HIGH/CRITICAL указаны package/version, reachability, fix и временный контроль | `scripts/scan-dependencies.ps1 -FailOnHigh`; Trivy command и разбор в `evidence/dependency-image-scan.txt` | **PASS** | +| Upload-worker resource bounds | Container: 1 CPU, 1 GiB, 256 PID; process: concurrency 2/prefetch 1, 40M pixels, 512 MiB fair semaphore, 2 s permit wait, 60 s job timeout и lease 90 s | `scripts/test-worker-resource-bounds.ps1`; `ImageVariantProcessorTest`; `AttachmentWorkerLimitsTest` | **PASS** | +| Telemetry non-disclosure canary | Header/body capture выключен; Collector удаляет Authorization, request/response/message bodies, DB parameters и query во всех pipelines | `scripts/test-telemetry-redaction.ps1`: canary отсутствует в container logs, Loki, Tempo sensitive tags и Prometheus labels | **PASS** | ## Health, scrape и bootstrap diff --git a/evidence/level4-security-audit.txt b/evidence/level4-security-audit.txt new file mode 100644 index 0000000..994e68e --- /dev/null +++ b/evidence/level4-security-audit.txt @@ -0,0 +1,145 @@ +# Level-4 threat model, worker bounds, TLS/ACL and telemetry audit + +Date: 2026-11-27 +Stand: local Docker Desktop, compose project hla-lab7 +Scope: README level-4 final security criterion. No credential, token, canary value +or private key is recorded. + +## Reproducible commands + + powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\test-level4-security-audit.ps1 + +The aggregate command invokes: + + .\scripts\test-mtls.ps1 + python tests/security.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt + .\scripts\test-internal-tls.ps1 + docker compose --env-file .env --profile verification run --rm private-bucket-check + .\scripts\test-openbao-runtime-boundaries.ps1 -SkipLivePolicy + .\scripts\test-worker-resource-bounds.ps1 + .\scripts\test-telemetry-redaction.ps1 + +For a freshly bootstrapped AppRole SecretID (TTL 24 h), include the live OpenBao +allow/deny probe: + + .\scripts\test-level4-security-audit.ps1 -IncludeFreshOpenBaoPolicy + +The audit deliberately does not use an operator/root token as a fallback for an +expired SecretID. The scoped OpenBao policy result is also recorded independently +in evidence/openbao-policies.txt. + +## Threat-to-control-to-negative-test traceability + +The table in security/THREAT_MODEL.md contains 13 concrete threat paths. At least +the following independently reproducible paths cover the required six: + +1. Ingress MITM/wrong hostname -> public CA + SAN verification -> empty/foreign + trust and wrong hostname fail in tests/security.py. +2. Direct API bypass -> client-auth=need + exact LB URI SAN -> no cert, foreign CA + and same-CA wrong SAN fail on each API replica in test-mtls.ps1. +3. Cross-user UUID/header abuse -> Bearer identity + membership predicates -> + forged X-User-Id and outsider chat/message/attachment requests return 401/404 + in tests/security.py. +4. Compromised worker -> separate DB/Redis/RabbitMQ/MinIO/OpenBao identities -> + password_hash SELECT, cache key/admin commands, cross-role broker identity, + MinIO admin/final delete and foreign KV access are denied by the referenced + ACL/policy tests. +5. False telemetry ingest/backend access -> mTLS gateways and telemetry client CA + -> no cert/foreign CA, same-CA migration role and direct backend bypass fail. +6. Authorization/body leakage -> capture disabled + Collector redaction in all + pipelines -> a unique canary is absent from stdout/stderr, Loki, Tempo sensitive + tag values and Prometheus label sets. +7. Image bomb/slow decoder -> byte/pixel/memory/concurrency/time/container bounds + -> 10 MiB upload gets 413; 50M-pixel header and over-budget image are rejected; + a slow worker job is cancelled and scheduled with processing_timeout. +8. Sealed OpenBao fallback -> scoped Agent files and startup deadline -> no + operator material/fallback in app, fresh start without rendered env fails. + +## Observed aggregate output + + PASS: 2 API replicas require a client certificate and LB CA; forbidden URI SAN + is rejected; only the LB identity succeeds; no API port is published. + PASS: trusted HTTPS, ACL/attachment isolation, session cap, upload and login limits. + 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. + PASS: API/worker use distinct broker identities; trusted-CA wrong roles receive + no AMQP access or OTel ingest; direct backend bypass is rejected. + PASS: PostgreSQL, Redis and RabbitMQ runtime identities are separate and + forbidden operations are denied. + PASS: bucket is private; API and worker use separate non-admin prefix/action policies + PASS: OpenBao uses persistent raft storage outside dev mode; API/worker use + separate AppRoles and read-only rendered files; operator material is absent. + INFO: live scoped-policy probe skipped because the local 24 h AppRole SecretID + had expired; no elevated fallback was used. + PASS: image memory/pixel rejection and processing-timeout retry passed as + executable unit tests. + PASS: worker CPU=1, RAM=1073741824 bytes, pids=256, concurrency=2, prefetch=1, + pixels=40000000, image budget=536870912 bytes, job timeout=60000 ms and + memory wait=2000 ms are bounded. + PASS: unique Authorization/body canary was absent from container logs, Loki + records, Tempo sensitive tag values and Prometheus label sets. + PASS: telemetry backends were queried over CA-verified mTLS with the dedicated + Grafana identity. + 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. + +## Worker hard bounds and executable failure paths + +Rendered Compose and runtime docker inspect agree: + + CPU 1.0 core + memory 1 GiB + PID limit 256 + JVM MaxRAM 70% of container + listener concurrency 2 + broker prefetch 1 + decoded pixels 40,000,000 + processing budget 512 MiB (fair semaphore) + memory permit wait 2 s + per-job timeout 60 s + DB lease 90 s (must outlive timeout) + +Unit command: + + .\gradlew.bat test ` + --tests com.example.mtusi_messenger.worker.ImageVariantProcessorTest ` + --tests com.example.mtusi_messenger.worker.AttachmentWorkerLimitsTest ` + --no-daemon --console=plain + +Observed: BUILD SUCCESSFUL. ImageVariantProcessorTest verifies normal transforms, +determinism, rejection above the memory estimate and rejection of a 50M-pixel PNG +header before decoded allocation. AttachmentWorkerLimitsTest rejects invalid +timeout/lease/concurrency settings and proves that a slow operation is cancelled, +acknowledged only after durable retry scheduling, and marked processing_timeout. + +## TLS matrix coverage + +The audit verifies CA and hostname for ingress, PostgreSQL, MinIO, OpenBao, Grafana, Redis, both +RabbitMQ gateways, OTel gateway/Collector, Loki, both Tempo ports and Prometheus. +Every declared mTLS backend is tested with no certificate and a certificate from +the wrong CA. Exact-role gateways additionally test a certificate signed by the +trusted workload CA but assigned to migration/cross-role identity. Valid API, +worker, Collector, Prometheus and Grafana identities pass their respective links. + +Runtime ACL checks execute forbidden operations rather than relying only on config: +API DDL and worker users/password_hash SELECT fail; Redis outside-prefix GET/SET +and CONFIG fail; RabbitMQ application permissions are separate and non-wildcard; +MinIO anonymous/admin/cross-prefix/final-write-or-delete operations fail. + +## Telemetry non-disclosure method + +test-telemetry-redaction.ps1 generates a random in-memory canary and sends it once +as an invalid Bearer value and once inside a malformed JSON body. Expected 401/400 +responses prove the requests reached the protected/error paths. After the export +delay the script, without printing the canary: + + - searches recent Compose stdout/stderr; + - queries Loki records; + - queries Tempo values for authorization, request/response/message bodies, + DB statement parameters and URL query; + - searches all returned Prometheus series label sets. + +All searches returned zero matches. Backend queries themselves use the dedicated +Grafana client certificate with CA and hostname verification. diff --git a/scripts/test-internal-tls.ps1 b/scripts/test-internal-tls.ps1 index 34407c9..f6cf10b 100644 --- a/scripts/test-internal-tls.ps1 +++ b/scripts/test-internal-tls.ps1 @@ -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 diff --git a/scripts/test-level4-security-audit.ps1 b/scripts/test-level4-security-audit.ps1 new file mode 100644 index 0000000..7e47486 --- /dev/null +++ b/scripts/test-level4-security-audit.ps1 @@ -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.' diff --git a/scripts/test-openbao-runtime-boundaries.ps1 b/scripts/test-openbao-runtime-boundaries.ps1 index 1f44721..6c49a19 100644 --- a/scripts/test-openbao-runtime-boundaries.ps1 +++ b/scripts/test-openbao-runtime-boundaries.ps1 @@ -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.' +} diff --git a/scripts/test-telemetry-redaction.ps1 b/scripts/test-telemetry-redaction.ps1 new file mode 100644 index 0000000..d7ba804 --- /dev/null +++ b/scripts/test-telemetry-redaction.ps1 @@ -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 +} diff --git a/scripts/test-worker-resource-bounds.ps1 b/scripts/test-worker-resource-bounds.ps1 new file mode 100644 index 0000000..99aa49a --- /dev/null +++ b/scripts/test-worker-resource-bounds.ps1 @@ -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." diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 7626e2a..7708024 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -52,7 +52,7 @@ Operator ── loopback/protected channel ── admin planes 1. **Публичная:** клиент → nginx. Единственный публикуемый business endpoint — `127.0.0.1:8443` в локальном профиле. Проверяются CA и SAN `localhost`. 2. **DMZ → application:** nginx → API использует обязательный mTLS, отдельный LB client CA и allowlist URI SAN `spiffe://hla-lab7/lb`; API port не публикуется. -3. **Application → data plane:** PostgreSQL, Redis, MinIO и RabbitMQ принимают TLS; API/worker имеют раздельные DB/cache/broker/S3 identities. Prefix-specific S3 policy остаётся улучшением. +3. **Application → data plane:** PostgreSQL, Redis, MinIO и RabbitMQ принимают TLS; API/worker имеют раздельные DB/cache/broker/S3 identities и разные prefix/action S3 policies. 4. **Application → telemetry:** API/worker пишут в Collector по mTLS с раздельными leaf identities; Collector, Prometheus и Grafana также используют отдельные mTLS identities для backend-связей. Redaction processor удаляет известные чувствительные поля. 5. **Secrets control plane:** отдельные API/worker Agents → OpenBao по TLS с разными AppRole и scoped policy; credentials передаются приложениям через разные read-only runtime volumes. 6. **Administrative:** operator → OpenBao/Grafana/MinIO admin. Интерфейсы не публикуются наружу; локальные Grafana/telemetry ports bound к loopback. @@ -61,17 +61,17 @@ Operator ── loopback/protected channel ── admin planes | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | --- | --- | --- | --- | --- | -| MITM подменяет ingress certificate или используется неверный hostname | Basic/Bearer передаются только аутентифицированному ingress | TLS 1.2/1.3, локальный CA, SAN `localhost`, hostname verification, без `-k` | `make test-security CA_FILE=secrets/tls/ca.crt`; пустой/чужой CA и wrong hostname → certificate error | Ручная установка CA — bootstrap trust; компрометация CA требует ротации | +| MITM подменяет ingress certificate или используется неверный hostname | Basic/Bearer передаются только аутентифицированному ingress | TLS 1.2/1.3, локальный CA, SAN `localhost`, hostname verification, без `-k` | `make test-security CA_FILE=secrets/pki/public-ca/ca.crt`; пустой/чужой CA и wrong hostname → certificate error | Ручная установка CA — bootstrap trust; компрометация CA требует ротации | | Внутренний контейнер обращается к API, минуя nginx | Business API доступен только доверенному LB | API TLS `client-auth=need`, отдельный LB CA и точный allowlist SAN `spiffe://hla-lab7/lb`; порт не публикуется | `scripts/test-mtls.ps1`: no cert/foreign CA/wrong SAN rejected; LB accepted | Компрометация LB key требует немедленного отзыва/ротации | | Пользователь меняет `X-User-Id` или UUID и читает чужой чат/attachment | Identity определяется Bearer; membership проверяется сервером | Stateless auth filter, token hash lookup, repository membership predicates и FK | Bob + Alice UUID → 404/401; forged `X-User-Id` не меняет результат | Ошибки намеренно не различают отсутствие объекта и отсутствие прав | | Пользователь прикрепляет чужой attachment или читает object key напрямую | Attachment принадлежит тому же чату; bucket private | Membership/ownership/chat validation, private bucket, opaque keys | Загрузить в чат A, попытаться attach/read из B; anonymous `mc ls/cp` → denied | Компрометация S3 credential даёт доступ в пределах его policy | | Credential stuffing на login истощает CPU Argon2id | Login bounded; ответ не раскрывает существование user | Argon2id 32768 KiB/t=2/p=1, dummy hash; общий Redis fixed-window limit 5/username/60 s и 100/source/60 s, fail-closed, 429/Retry-After | `measure-login-dos.ps1 -SourceBudget`: 6-я/101-я попытки → 429; обе реплики; 429 ≈19 мс против 401 p50 287 мс; `LoginRateLimiterTest` — shared state и fail-closed; existing/unknown user имеют одинаковый 401 | Fixed window допускает burst на границе окна; source limit видит адрес ingress (общий cap за LB), trusted-proxy модель не завершена; лимитер не ограничивает concurrency | | Кража БД раскрывает пароль или активный bearer token | В БД нет plaintext password/session token | Argon2id password hash с rehash при успешном login через CAS; SHA-256 session token hash; TTL/logout | `credential_storage.py`: PHC-префикс, SHA-256 token hash, plaintext password/token/hash отсутствуют в API/LB logs; `DatabaseAuthenticationProviderTest` — rehash и dummy hash; после logout/expiry token → 401 | Offline guessing зависит от качества пароля и измеренных Argon2 параметров | -| Скомпрометированный worker читает users/sessions или admin bucket/queue | Worker видит только jobs и нужные storage operations | Отдельные DB role, S3 key, RabbitMQ/Redis cert+user+ACL; отдельная OpenBao AppRole читает только worker KV | Worker: `SELECT password_hash`, MinIO admin, запрещённый broker route и API KV → denied | MinIO API/worker пока используют одинаковую bucket policy, хотя keys различаются | +| Скомпрометированный worker читает users/sessions или admin bucket/queue | Worker видит только jobs и нужные storage operations | Отдельные DB role, S3 key и prefix/action policy, RabbitMQ/Redis cert+user+ACL; отдельная OpenBao AppRole читает только worker KV | Worker: `SELECT password_hash`, MinIO admin/final delete, cross-role broker gateway и API KV → denied | MinIO остаётся single-tenant; компрометация worker key даёт разрешённые операции над attachment prefix | | Поддельный RabbitMQ job или подтверждение чужой работы | Producer/consumer identities и ACL различаются | mTLS `5671`, отдельные cert/users/regex permissions; plaintext listener disabled; DB lease fencing | No cert/foreign CA → TLS отказ; запрещённая broker operation → access refused | Точная проверка URI SAN выполняется ACL user mapping, не самим Rabbit TLS listener | -| Внутренний контейнер шлёт фальшивую telemetry или читает backends | Только заявленные workload identities могут ingest/query | mTLS на workload→Collector, Collector→Loki/Tempo, Prometheus→Collector и Grafana→backends; отдельные certs; redaction | No cert/foreign CA rejected; Prometheus разрешает exact Grafana SAN; canary отсутствует в telemetry | Single-tenant Loki/Tempo не дают fine-grained query ACL сверх mTLS role | -| Authorization/password/body попадает в signals | Telemetry не содержит credentials/payload | OTel capture headers/bodies выключен; Collector удаляет auth, bodies, DB parameters/query | Запрос с уникальным canary; поиск в Loki/Tempo/Prometheus/logs → 0 | Новые instrumentation attributes требуют повторного canary-теста | -| Image bomb или concurrent uploads исчерпывают worker | Файл и суммарная обработка имеют bounds | 10 MiB limit, pixel limit, semaphore, worker memory budget, timeout/resources | Oversized body → 413; >40M pixels → reject/failed; concurrent test остаётся в limit | Decoder CVE остаются supply-chain риском; нужны scan/upgrade | +| Внутренний контейнер шлёт фальшивую telemetry или читает backends | Только заявленные workload identities могут ingest/query | mTLS на workload→Collector, Collector→Loki/Tempo, Prometheus→Collector и Grafana→backends; отдельные certs; redaction | `test-level4-security-audit.ps1`: no-cert/foreign CA rejected; same-CA migration role получает 403 на ingest; workload cert не обходит gateway | Single-tenant Loki/Tempo не дают fine-grained query ACL сверх mTLS role | +| Authorization/password/body попадает в signals | Telemetry не содержит credentials/payload | OTel capture headers/bodies выключен; Collector удаляет auth, bodies, DB parameters/query | `test-telemetry-redaction.ps1`: уникальный Authorization + malformed-body canary; поиск в stdout/stderr, Loki, Tempo sensitive tag values и Prometheus labels → 0 | Новые instrumentation attributes требуют повторного canary-теста | +| Image bomb или concurrent uploads исчерпывают worker | Файл и суммарная обработка имеют bounds | 10 MiB limit, 40M pixel limit до decode, fair memory semaphore с 512 MiB budget/2 s wait, concurrency 2/prefetch 1, 60 s job timeout; container 1 CPU/1 GiB/256 PID | `test-worker-resource-bounds.ps1`; `ImageVariantProcessorTest` отвергает 50M-pixel header и memory over-budget; `AttachmentWorkerLimitsTest` отменяет slow job и ставит bounded retry с `processing_timeout` | Native decoder может не сразу реагировать на interrupt; container CPU/RAM/PID и lease reaper остаются внешним hard bound | | Private key/secret попадает в Git, image или app env | Operator secrets не поставляются со skeleton | `.gitignore`, `.dockerignore`, local bootstrap в `secrets/`, OpenBao Agent и отдельные runtime files | Secret scanner, `docker history`, inspect app env не содержат root/unseal/runtime password | Dependency bootstrap passwords пока поступают их контейнерам через Compose env; это остаточный локальный риск | | OpenBao sealed, приложение использует hardcoded fallback/plaintext | Отказ secret plane не ослабляет auth/TLS | Agent retry, отсутствие app fallback, controlled startup failure без rendered file; TLS не отключается | `test-openbao-rotation-boundaries.ps1`: при `Sealed true` агенты Running, render keys сохранены, public health 200; fresh startup без rendered env → exit 1 за 2.8 c при лимите 2 c | Уже запущенное приложение продолжает работать со статическими dependency credentials до restart/их отзыва | diff --git a/src/test/java/com/example/mtusi_messenger/worker/AttachmentWorkerLimitsTest.java b/src/test/java/com/example/mtusi_messenger/worker/AttachmentWorkerLimitsTest.java new file mode 100644 index 0000000..0e4bd9f --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/worker/AttachmentWorkerLimitsTest.java @@ -0,0 +1,123 @@ +package com.example.mtusi_messenger.worker; + +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.observability.JobTelemetry; +import com.example.mtusi_messenger.queue.RetryPolicy; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rabbitmq.client.Channel; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class AttachmentWorkerLimitsTest { + private AttachmentWorker worker; + + @AfterEach + void stopProcessingPool() { + if (worker != null) { + worker.shutdownPool(); + } + } + + @Test + void rejectsMissingOrInconsistentTimeBounds() { + assertThrows(IllegalArgumentException.class, + () -> newWorker(Duration.ZERO, Duration.ofSeconds(1), 1)); + assertThrows(IllegalArgumentException.class, + () -> newWorker(Duration.ofSeconds(2), Duration.ofSeconds(2), 1)); + assertThrows(IllegalArgumentException.class, + () -> newWorker(Duration.ofSeconds(1), Duration.ofSeconds(2), 0)); + } + + @Test + void cancelsSlowProcessingAndSchedulesBoundedRetry() throws Exception { + ObjectMapper mapper = new ObjectMapper().findAndRegisterModules(); + AttachmentRepository attachments = mock(AttachmentRepository.class); + ObjectStorage storage = mock(ObjectStorage.class); + ImageVariantProcessor images = mock(ImageVariantProcessor.class); + RetryPolicy retryPolicy = mock(RetryPolicy.class); + TransactionTemplate transaction = mock(TransactionTemplate.class); + JobTelemetry telemetry = mock(JobTelemetry.class); + Channel channel = mock(Channel.class); + + UUID jobId = UUID.randomUUID(); + UUID attachmentId = UUID.randomUUID(); + Instant createdAt = Instant.now(); + AttachmentJob job = AttachmentJob.first(jobId, attachmentId, 2, createdAt); + Attachment attachment = new Attachment( + attachmentId, UUID.randomUUID(), UUID.randomUUID(), "bounded.png", + "image/png", 4, "unused", "attachments/bounded/original", + "staging/bounded/original", "processing", List.of(), null, + createdAt, createdAt); + + MessageProperties properties = new MessageProperties(); + properties.setDeliveryTag(42L); + Message message = new Message(mapper.writeValueAsBytes(job), properties); + + when(attachments.findById(attachmentId)).thenReturn(Optional.of(attachment)); + when(attachments.currentAttempt(jobId)).thenReturn(1); + when(attachments.claim(eq(jobId), eq(attachmentId), eq(2), eq(1), any(), any())) + .thenReturn(true); + when(attachments.markQueuedForRetry(eq(jobId), eq(attachmentId), eq(2), any(), + eq(2), eq("processing_timeout"), any())).thenReturn(true); + when(retryPolicy.delayForAttempt(2)).thenReturn(Duration.ofMillis(1)); + when(telemetry.started()).thenReturn(System.nanoTime()); + doAnswer(invocation -> { + TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(null); + }).when(transaction).execute(any()); + when(storage.get("staging/bounded/original")).thenAnswer(invocation -> { + Thread.sleep(5_000); + return new byte[]{1, 2, 3, 4}; + }); + + worker = new AttachmentWorker(mapper, attachments, storage, images, retryPolicy, + transaction, telemetry, 5, Duration.ofMillis(50), Duration.ofSeconds(1), + false, false, false, 1); + + worker.consume(message, channel); + + verify(attachments).markQueuedForRetry(eq(jobId), eq(attachmentId), eq(2), any(), + eq(2), eq("processing_timeout"), any()); + verify(channel).basicAck(42L, false); + verify(channel, never()).basicReject(42L, false); + verify(telemetry).finished(any(Long.class), eq(createdAt), eq("retry")); + verify(images, never()).createVariants(any(), anyInt()); + } + + private AttachmentWorker newWorker(Duration timeout, Duration lease, int concurrency) { + worker = new AttachmentWorker( + new ObjectMapper().findAndRegisterModules(), + mock(AttachmentRepository.class), + mock(ObjectStorage.class), + mock(ImageVariantProcessor.class), + mock(RetryPolicy.class), + mock(TransactionTemplate.class), + mock(JobTelemetry.class), + 5, timeout, lease, false, false, false, concurrency); + return worker; + } +} diff --git a/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java index 9601467..4408b6b 100644 --- a/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java +++ b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java @@ -10,6 +10,7 @@ import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.Arrays; +import java.util.zip.CRC32; import java.util.function.Function; import java.util.stream.Collectors; @@ -57,6 +58,18 @@ class ImageVariantProcessorTest { assertEquals("image_too_large", error.errorCode()); } + @Test + void rejectsImageHeaderAboveDecodedPixelLimitBeforeAllocation() { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1)); + + var error = assertThrows(ImageVariantProcessor.ProcessingException.class, + () -> processor.createVariants(pngWithDimensions(10_000, 5_000), 2)); + + assertTrue(error.permanent()); + assertEquals("image_too_large", error.errorCode()); + } + @Test void versionsProduceSeparateDeterministicProfiles() { ImageVariantProcessor processor = new ImageVariantProcessor( @@ -91,4 +104,21 @@ class ImageVariantProcessorTest { assertEquals(width, decoded.getWidth()); assertEquals(height, decoded.getHeight()); } + + private byte[] pngWithDimensions(int width, int height) { + byte[] changed = Arrays.copyOf(original, original.length); + writeInt(changed, 16, width); + writeInt(changed, 20, height); + CRC32 crc = new CRC32(); + crc.update(changed, 12, 17); // IHDR type plus its 13-byte payload. + writeInt(changed, 29, (int) crc.getValue()); + return changed; + } + + private static void writeInt(byte[] target, int offset, int value) { + target[offset] = (byte) (value >>> 24); + target[offset + 1] = (byte) (value >>> 16); + target[offset + 2] = (byte) (value >>> 8); + target[offset + 3] = (byte) value; + } }