From 5976ab02ff564112d581927d54599e47be510c3c Mon Sep 17 00:00:00 2001 From: casablanca Date: Mon, 7 Dec 2026 00:40:17 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 8 + .env.example | 38 +- .gitignore | 7 + Dockerfile | 27 + REPORT.md | 240 ++++- alembic.ini | 149 +++ compose.yaml | 646 ++++++++++++ contracts/trust-matrix.md | 68 +- docs/threat-model.md | 205 ++++ evidence/grade3-argon2-checks.txt | 11 + evidence/grade3-argon2-container.txt | 6 + evidence/grade3-argon2-runtime.txt | 10 + evidence/grade3-argon2-wsl.txt | 6 + evidence/grade3-certificates.txt | 149 +++ evidence/grade3-clean-bootstrap.txt | 127 +++ evidence/grade3-clean-build.txt | 375 +++++++ evidence/grade3-clean-ca-isolation.txt | 5 + evidence/grade3-clean-container-audit.txt | 302 ++++++ evidence/grade3-clean-containers-initial.txt | 23 + evidence/grade3-clean-containers.txt | 23 + evidence/grade3-clean-dependency-audit.txt | 1 + evidence/grade3-clean-final-containers.txt | 23 + evidence/grade3-clean-final-security.txt | 2 + evidence/grade3-clean-final-smoke.txt | 2 + evidence/grade3-clean-hardening.txt | 24 + evidence/grade3-clean-image-audit.txt | 46 + evidence/grade3-clean-isolation.txt | 13 + evidence/grade3-clean-network-audit.txt | 79 ++ evidence/grade3-clean-openbao-config.txt | 13 + evidence/grade3-clean-openbao-init.txt | 1 + evidence/grade3-clean-openbao-integration.txt | 4 + evidence/grade3-clean-openbao-seed.txt | 7 + evidence/grade3-clean-openbao-status.txt | 13 + evidence/grade3-clean-openbao-unseal.txt | 9 + ...ade3-clean-rabbitmq-cold-start-details.txt | 7 + evidence/grade3-clean-rabbitmq-cold-start.txt | 10 + .../grade3-clean-rabbitmq-healthcheck.txt | 6 + evidence/grade3-clean-rabbitmq-startup.txt | 150 +++ evidence/grade3-clean-secret-audit.txt | 5 + evidence/grade3-clean-security.txt | 2 + evidence/grade3-clean-smoke.txt | 2 + evidence/grade3-clean-startup-initial.txt | 142 +++ evidence/grade3-clean-startup-recovery.txt | 58 ++ evidence/grade3-collector-security.txt | 35 + evidence/grade3-container-audit.txt | 302 ++++++ evidence/grade3-container-resources.txt | 21 + evidence/grade3-data-security.txt | 30 + evidence/grade3-dependency-audit.txt | 1 + evidence/grade3-failover-first-containers.txt | 6 + evidence/grade3-failover-first-health.txt | 10 + ...e3-failover-first-recovered-containers.txt | 6 + evidence/grade3-failover-first-recovery.txt | 10 + evidence/grade3-failover-first.txt | 4 + evidence/grade3-failover-openbao-recovery.txt | 2 + .../grade3-failover-second-containers.txt | 6 + evidence/grade3-failover-second-health.txt | 10 + ...3-failover-second-recovered-containers.txt | 6 + evidence/grade3-failover-second-recovery.txt | 10 + evidence/grade3-failover-second.txt | 4 + evidence/grade3-final-build.txt | 129 +++ evidence/grade3-final-secret-audit.txt | 5 + evidence/grade3-grafana-security.txt | 17 + evidence/grade3-hardening-config.txt | 23 + evidence/grade3-hardening-runtime.txt | 24 + .../grade3-image-audit-initial-failure.txt | 23 + evidence/grade3-image-audit.txt | 10 + evidence/grade3-image-content-audit.txt | 46 + evidence/grade3-loki-secret-audit-final.txt | 11 + evidence/grade3-loki-secret-audit.txt | 10 + evidence/grade3-messaging-storage-config.txt | 33 + evidence/grade3-minio-init-sanitized.txt | 8 + evidence/grade3-minio-security.txt | 33 + evidence/grade3-mtls-security.txt | 18 + evidence/grade3-network-audit-final.txt | 79 ++ evidence/grade3-network-audit-hardened.txt | 79 ++ evidence/grade3-network-audit.txt | 79 ++ evidence/grade3-openbao-config.txt | 13 + evidence/grade3-openbao-fail-closed.txt | 11 + evidence/grade3-openbao-integration.txt | 44 + evidence/grade3-openbao-persistence.txt | 70 ++ evidence/grade3-openbao-recovery.txt | 4 + evidence/grade3-openbao-restart.txt | 4 + evidence/grade3-openbao-security.txt | 70 ++ evidence/grade3-openbao-seed.txt | 7 + evidence/grade3-openbao-status.txt | 13 + evidence/grade3-openbao-tls.txt | 10 + evidence/grade3-persistence-after.txt | 20 + evidence/grade3-persistence-before.txt | 20 + evidence/grade3-persistence.txt | 3 + evidence/grade3-postgres-roles.txt | 130 +++ evidence/grade3-process-privileges-final.txt | 60 ++ evidence/grade3-process-privileges.txt | 60 ++ evidence/grade3-prometheus-secret-audit.txt | 10 + evidence/grade3-prometheus-security.txt | 14 + evidence/grade3-public-security.txt | 2 + evidence/grade3-public-tls-negative.txt | 4 + evidence/grade3-public-tls.txt | 10 + evidence/grade3-published-ports.txt | 4 + evidence/grade3-rabbitmq-config.txt | 27 + evidence/grade3-rabbitmq-security.txt | 17 + evidence/grade3-rate-limit-ip.txt | 70 ++ evidence/grade3-rate-limit-username.txt | 14 + evidence/grade3-secret-audit.txt | 5 + evidence/grade3-session-expiry.txt | 6 + evidence/grade3-smoke-after-failover.txt | 2 + evidence/grade3-smoke-after-hardening.txt | 2 + .../grade3-smoke-after-network-hardening.txt | 2 + evidence/grade3-smoke-after-rate-limit.txt | 2 + evidence/grade3-smoke-after-security.txt | 2 + evidence/grade3-smoke-final.txt | 2 + evidence/grade3-smoke.txt | 2 + ...grade3-telemetry-audit-initial-failure.txt | 48 + evidence/grade3-telemetry-backends.txt | 31 + evidence/grade3-telemetry-queries.txt | 6 + evidence/grade3-tempo-secret-audit.txt | 23 + evidence/grade3-upload-limits.txt | 6 + infra/api-proxy/nginx.conf.template | 57 ++ infra/grafana/dashboards/messenger.json | 923 ++++++++++++++++++ .../provisioning/dashboards/dashboards.yaml | 12 + .../provisioning/datasources/datasources.yaml | 40 + infra/loki/loki.yaml | 42 + infra/minio/api-policy.json | 35 + infra/minio/init.sh | 37 + infra/minio/worker-policy.json | 24 + infra/nginx.conf | 57 ++ infra/openbao/openbao.hcl | 25 + infra/openbao/policies/api.hcl | 3 + infra/openbao/policies/dispatcher.hcl | 3 + infra/openbao/policies/worker.hcl | 3 + infra/otel/config.yaml | 94 ++ infra/postgres/grants.sql | 11 + infra/postgres/init-roles.sh | 44 + infra/postgres/pg_hba.conf | 5 + infra/prometheus/RUNBOOK.md | 74 ++ infra/prometheus/prometheus.yaml | 43 + infra/prometheus/rules.yaml | 58 ++ infra/rabbitmq/enabled_plugins | 1 + infra/rabbitmq/tls.conf | 23 + infra/redis/redis.conf | 18 + infra/telemetry-proxy/loki.conf | 149 +++ infra/telemetry-proxy/otel-collector.conf | 64 ++ infra/telemetry-proxy/tempo.conf | 125 +++ infra/tempo/tempo.yaml | 29 + migrations/README | 1 + migrations/env.py | 56 ++ migrations/script.py.mako | 28 + .../versions/a6b12026a002_job_retries.py | 42 + .../a7b12026a003_failed_publication.py | 33 + .../b3a91c0e7d42_message_idempotency.py | 61 ++ .../versions/b8b12026a004_job_generation.py | 24 + .../versions/c8f42a19e6b0_attachments.py | 78 ++ .../versions/c9b12026a005_execution_id.py | 19 + .../versions/d6a12026a006_trace_context.py | 25 + .../d9e53b20f7c1_attachment_metadata.py | 80 ++ .../versions/e5a12026a001_async_jobs.py | 77 ++ .../versions/e7a12026a007_security_grants.py | 46 + .../versions/f7c51e1e945b_initial_schema.py | 110 +++ requirements.txt | 34 + scripts/bao-entrypoint.py | 150 +++ scripts/bootstrap-data-security.sh | 65 ++ scripts/bootstrap-messaging-security.sh | 105 ++ scripts/bootstrap-telemetry-security.sh | 208 ++++ scripts/bootstrap.sh | 47 + scripts/cleanup_staging.py | 68 ++ scripts/configure-mtls.sh | 25 + scripts/configure-openbao.py | 124 +++ scripts/configure-openbao.sh | 33 + scripts/generate-certs.sh | 111 +++ scripts/init-openbao.sh | 59 ++ scripts/prepare-tls-permissions.sh | 46 + scripts/replay_job.py | 83 ++ scripts/restart.sh | 40 + scripts/seed-openbao.py | 46 + scripts/seed-openbao.sh | 61 ++ scripts/stop-one.sh | 20 + scripts/unseal-openbao.sh | 73 ++ src/__init__.py | 0 src/cursor.py | 86 ++ src/database.py | 183 ++++ src/dispatcher.py | 175 ++++ src/errors.py | 12 + src/images.py | 71 ++ src/main.py | 861 ++++++++++++++++ src/models.py | 153 +++ src/queue.py | 120 +++ src/rate_limit.py | 104 ++ src/repositories.py | 876 +++++++++++++++++ src/runtime_metrics.py | 158 +++ src/security.py | 24 + src/sessions.py | 90 ++ src/storage.py | 117 +++ src/telemetry.py | 369 +++++++ src/worker.py | 489 ++++++++++ student-tests/audit_containers.py | 52 + student-tests/audit_images.py | 203 ++++ student-tests/audit_network.py | 41 + student-tests/audit_secrets.py | 133 +++ student-tests/audit_telemetry.py | 292 ++++++ student-tests/benchmark_argon2.py | 57 ++ student-tests/diagnose_secrets.py | 126 +++ student-tests/test_collector_security.py | 250 +++++ student-tests/test_container_hardening.py | 90 ++ student-tests/test_data_security.py | 190 ++++ student-tests/test_grafana_security.py | 141 +++ student-tests/test_minio_security.py | 280 ++++++ student-tests/test_mtls.py | 70 ++ student-tests/test_openbao_security.py | 167 ++++ student-tests/test_openbao_tls.py | 134 +++ student-tests/test_prometheus_security.py | 177 ++++ student-tests/test_public_tls.py | 36 + student-tests/test_rabbitmq_security.py | 234 +++++ student-tests/test_rate_limit.py | 97 ++ student-tests/test_rate_limit_ip.py | 98 ++ student-tests/test_session_expiry.py | 111 +++ student-tests/test_telemetry_backends.py | 269 +++++ student-tests/test_telemetry_queries.py | 91 ++ student-tests/test_upload_limits.py | 110 +++ 217 files changed, 16359 insertions(+), 39 deletions(-) create mode 100644 Dockerfile create mode 100644 alembic.ini create mode 100644 compose.yaml create mode 100644 docs/threat-model.md create mode 100644 evidence/grade3-argon2-checks.txt create mode 100644 evidence/grade3-argon2-container.txt create mode 100644 evidence/grade3-argon2-runtime.txt create mode 100644 evidence/grade3-argon2-wsl.txt create mode 100644 evidence/grade3-certificates.txt create mode 100644 evidence/grade3-clean-bootstrap.txt create mode 100644 evidence/grade3-clean-build.txt create mode 100644 evidence/grade3-clean-ca-isolation.txt create mode 100644 evidence/grade3-clean-container-audit.txt create mode 100644 evidence/grade3-clean-containers-initial.txt create mode 100644 evidence/grade3-clean-containers.txt create mode 100644 evidence/grade3-clean-dependency-audit.txt create mode 100644 evidence/grade3-clean-final-containers.txt create mode 100644 evidence/grade3-clean-final-security.txt create mode 100644 evidence/grade3-clean-final-smoke.txt create mode 100644 evidence/grade3-clean-hardening.txt create mode 100644 evidence/grade3-clean-image-audit.txt create mode 100644 evidence/grade3-clean-isolation.txt create mode 100644 evidence/grade3-clean-network-audit.txt create mode 100644 evidence/grade3-clean-openbao-config.txt create mode 100644 evidence/grade3-clean-openbao-init.txt create mode 100644 evidence/grade3-clean-openbao-integration.txt create mode 100644 evidence/grade3-clean-openbao-seed.txt create mode 100644 evidence/grade3-clean-openbao-status.txt create mode 100644 evidence/grade3-clean-openbao-unseal.txt create mode 100644 evidence/grade3-clean-rabbitmq-cold-start-details.txt create mode 100644 evidence/grade3-clean-rabbitmq-cold-start.txt create mode 100644 evidence/grade3-clean-rabbitmq-healthcheck.txt create mode 100644 evidence/grade3-clean-rabbitmq-startup.txt create mode 100644 evidence/grade3-clean-secret-audit.txt create mode 100644 evidence/grade3-clean-security.txt create mode 100644 evidence/grade3-clean-smoke.txt create mode 100644 evidence/grade3-clean-startup-initial.txt create mode 100644 evidence/grade3-clean-startup-recovery.txt create mode 100644 evidence/grade3-collector-security.txt create mode 100644 evidence/grade3-container-audit.txt create mode 100644 evidence/grade3-container-resources.txt create mode 100644 evidence/grade3-data-security.txt create mode 100644 evidence/grade3-dependency-audit.txt create mode 100644 evidence/grade3-failover-first-containers.txt create mode 100644 evidence/grade3-failover-first-health.txt create mode 100644 evidence/grade3-failover-first-recovered-containers.txt create mode 100644 evidence/grade3-failover-first-recovery.txt create mode 100644 evidence/grade3-failover-first.txt create mode 100644 evidence/grade3-failover-openbao-recovery.txt create mode 100644 evidence/grade3-failover-second-containers.txt create mode 100644 evidence/grade3-failover-second-health.txt create mode 100644 evidence/grade3-failover-second-recovered-containers.txt create mode 100644 evidence/grade3-failover-second-recovery.txt create mode 100644 evidence/grade3-failover-second.txt create mode 100644 evidence/grade3-final-build.txt create mode 100644 evidence/grade3-final-secret-audit.txt create mode 100644 evidence/grade3-grafana-security.txt create mode 100644 evidence/grade3-hardening-config.txt create mode 100644 evidence/grade3-hardening-runtime.txt create mode 100644 evidence/grade3-image-audit-initial-failure.txt create mode 100644 evidence/grade3-image-audit.txt create mode 100644 evidence/grade3-image-content-audit.txt create mode 100644 evidence/grade3-loki-secret-audit-final.txt create mode 100644 evidence/grade3-loki-secret-audit.txt create mode 100644 evidence/grade3-messaging-storage-config.txt create mode 100644 evidence/grade3-minio-init-sanitized.txt create mode 100644 evidence/grade3-minio-security.txt create mode 100644 evidence/grade3-mtls-security.txt create mode 100644 evidence/grade3-network-audit-final.txt create mode 100644 evidence/grade3-network-audit-hardened.txt create mode 100644 evidence/grade3-network-audit.txt create mode 100644 evidence/grade3-openbao-config.txt create mode 100644 evidence/grade3-openbao-fail-closed.txt create mode 100644 evidence/grade3-openbao-integration.txt create mode 100644 evidence/grade3-openbao-persistence.txt create mode 100644 evidence/grade3-openbao-recovery.txt create mode 100644 evidence/grade3-openbao-restart.txt create mode 100644 evidence/grade3-openbao-security.txt create mode 100644 evidence/grade3-openbao-seed.txt create mode 100644 evidence/grade3-openbao-status.txt create mode 100644 evidence/grade3-openbao-tls.txt create mode 100644 evidence/grade3-persistence-after.txt create mode 100644 evidence/grade3-persistence-before.txt create mode 100644 evidence/grade3-persistence.txt create mode 100644 evidence/grade3-postgres-roles.txt create mode 100644 evidence/grade3-process-privileges-final.txt create mode 100644 evidence/grade3-process-privileges.txt create mode 100644 evidence/grade3-prometheus-secret-audit.txt create mode 100644 evidence/grade3-prometheus-security.txt create mode 100644 evidence/grade3-public-security.txt create mode 100644 evidence/grade3-public-tls-negative.txt create mode 100644 evidence/grade3-public-tls.txt create mode 100644 evidence/grade3-published-ports.txt create mode 100644 evidence/grade3-rabbitmq-config.txt create mode 100644 evidence/grade3-rabbitmq-security.txt create mode 100644 evidence/grade3-rate-limit-ip.txt create mode 100644 evidence/grade3-rate-limit-username.txt create mode 100644 evidence/grade3-secret-audit.txt create mode 100644 evidence/grade3-session-expiry.txt create mode 100644 evidence/grade3-smoke-after-failover.txt create mode 100644 evidence/grade3-smoke-after-hardening.txt create mode 100644 evidence/grade3-smoke-after-network-hardening.txt create mode 100644 evidence/grade3-smoke-after-rate-limit.txt create mode 100644 evidence/grade3-smoke-after-security.txt create mode 100644 evidence/grade3-smoke-final.txt create mode 100644 evidence/grade3-smoke.txt create mode 100644 evidence/grade3-telemetry-audit-initial-failure.txt create mode 100644 evidence/grade3-telemetry-backends.txt create mode 100644 evidence/grade3-telemetry-queries.txt create mode 100644 evidence/grade3-tempo-secret-audit.txt create mode 100644 evidence/grade3-upload-limits.txt create mode 100644 infra/api-proxy/nginx.conf.template create mode 100644 infra/grafana/dashboards/messenger.json create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/loki/loki.yaml create mode 100644 infra/minio/api-policy.json create mode 100755 infra/minio/init.sh create mode 100644 infra/minio/worker-policy.json create mode 100644 infra/nginx.conf create mode 100644 infra/openbao/openbao.hcl create mode 100644 infra/openbao/policies/api.hcl create mode 100644 infra/openbao/policies/dispatcher.hcl create mode 100644 infra/openbao/policies/worker.hcl create mode 100644 infra/otel/config.yaml create mode 100644 infra/postgres/grants.sql create mode 100755 infra/postgres/init-roles.sh create mode 100644 infra/postgres/pg_hba.conf create mode 100644 infra/prometheus/RUNBOOK.md create mode 100644 infra/prometheus/prometheus.yaml create mode 100644 infra/prometheus/rules.yaml create mode 100644 infra/rabbitmq/enabled_plugins create mode 100644 infra/rabbitmq/tls.conf create mode 100644 infra/redis/redis.conf create mode 100644 infra/telemetry-proxy/loki.conf create mode 100644 infra/telemetry-proxy/otel-collector.conf create mode 100644 infra/telemetry-proxy/tempo.conf create mode 100644 infra/tempo/tempo.yaml create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/a6b12026a002_job_retries.py create mode 100644 migrations/versions/a7b12026a003_failed_publication.py create mode 100644 migrations/versions/b3a91c0e7d42_message_idempotency.py create mode 100644 migrations/versions/b8b12026a004_job_generation.py create mode 100644 migrations/versions/c8f42a19e6b0_attachments.py create mode 100644 migrations/versions/c9b12026a005_execution_id.py create mode 100644 migrations/versions/d6a12026a006_trace_context.py create mode 100644 migrations/versions/d9e53b20f7c1_attachment_metadata.py create mode 100644 migrations/versions/e5a12026a001_async_jobs.py create mode 100644 migrations/versions/e7a12026a007_security_grants.py create mode 100644 migrations/versions/f7c51e1e945b_initial_schema.py create mode 100644 requirements.txt create mode 100644 scripts/bao-entrypoint.py create mode 100755 scripts/bootstrap-data-security.sh create mode 100755 scripts/bootstrap-messaging-security.sh create mode 100755 scripts/bootstrap-telemetry-security.sh create mode 100755 scripts/bootstrap.sh create mode 100644 scripts/cleanup_staging.py create mode 100755 scripts/configure-mtls.sh create mode 100644 scripts/configure-openbao.py create mode 100755 scripts/configure-openbao.sh create mode 100755 scripts/generate-certs.sh create mode 100755 scripts/init-openbao.sh create mode 100755 scripts/prepare-tls-permissions.sh create mode 100644 scripts/replay_job.py create mode 100755 scripts/restart.sh create mode 100644 scripts/seed-openbao.py create mode 100755 scripts/seed-openbao.sh create mode 100755 scripts/stop-one.sh create mode 100755 scripts/unseal-openbao.sh create mode 100644 src/__init__.py create mode 100644 src/cursor.py create mode 100644 src/database.py create mode 100644 src/dispatcher.py create mode 100644 src/errors.py create mode 100644 src/images.py create mode 100644 src/main.py create mode 100644 src/models.py create mode 100644 src/queue.py create mode 100644 src/rate_limit.py create mode 100644 src/repositories.py create mode 100644 src/runtime_metrics.py create mode 100644 src/security.py create mode 100644 src/sessions.py create mode 100644 src/storage.py create mode 100644 src/telemetry.py create mode 100644 src/worker.py create mode 100644 student-tests/audit_containers.py create mode 100644 student-tests/audit_images.py create mode 100644 student-tests/audit_network.py create mode 100644 student-tests/audit_secrets.py create mode 100644 student-tests/audit_telemetry.py create mode 100644 student-tests/benchmark_argon2.py create mode 100644 student-tests/diagnose_secrets.py create mode 100644 student-tests/test_collector_security.py create mode 100644 student-tests/test_container_hardening.py create mode 100644 student-tests/test_data_security.py create mode 100644 student-tests/test_grafana_security.py create mode 100644 student-tests/test_minio_security.py create mode 100644 student-tests/test_mtls.py create mode 100644 student-tests/test_openbao_security.py create mode 100644 student-tests/test_openbao_tls.py create mode 100644 student-tests/test_prometheus_security.py create mode 100644 student-tests/test_public_tls.py create mode 100644 student-tests/test_rabbitmq_security.py create mode 100644 student-tests/test_rate_limit.py create mode 100644 student-tests/test_rate_limit_ip.py create mode 100644 student-tests/test_session_expiry.py create mode 100644 student-tests/test_telemetry_backends.py create mode 100644 student-tests/test_telemetry_queries.py create mode 100644 student-tests/test_upload_limits.py diff --git a/.dockerignore b/.dockerignore index bc16e556..b3b003bd 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,11 @@ __pycache__ node_modules evidence .DS_Store +.idea +secrets/ +certs/ +openbao-local/ +infra/rabbitmq/rabbitmq.conf +**/__pycache__ +*.pyc +evidence/ diff --git a/.env.example b/.env.example index 2e9f0541..74115002 100644 --- a/.env.example +++ b/.env.example @@ -1,24 +1,25 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. # These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 +APP_HOST=127.0.0.1 APP_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url +DATABASE_URL_FILE=/run/app-secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +SESSION_STORE=redis +CACHE_URL_FILE=/run/app-secrets/cache_url API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 S3_ENDPOINT=https://s3:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +S3_ACCESS_KEY_ID_FILE=/run/app-secrets/s3_access_key_id +S3_SECRET_ACCESS_KEY_FILE=/run/app-secrets/s3_secret_access_key MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url +RABBITMQ_HOST=rabbitmq +RABBITMQ_PASSWORD_FILE=/run/app-secrets/rabbitmq_password WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 @@ -30,12 +31,25 @@ OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab # TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. PUBLIC_BASE_URL=https://localhost:8443 -TLS_CA_FILE=/run/secrets/ca.crt -TLS_CERT_FILE=/run/secrets/service.crt -TLS_KEY_FILE=/run/secrets/service.key +TLS_CA_FILE=/run/ca/ca.crt +TLS_CERT_FILE=/run/tls/tls.crt +TLS_KEY_FILE=/run/tls/tls.key BAO_ADDR=https://openbao:8200 -BAO_CACERT=/run/secrets/bao-ca.crt +BAO_CACERT=/run/ca/ca.crt # No root token here. Bootstrap operator -> short-lived service auth -> scoped token. -ARGON2_MEMORY_KIB=19456 +ARGON2_MEMORY_KIB=32768 ARGON2_ITERATIONS=2 ARGON2_PARALLELISM=1 + +# Logical settings; actual runtime values are defined in compose.yaml +# and src/security.py. Not every variable is read directly by the app. +LOGIN_WINDOW_SECONDS=60 +LOGIN_USERNAME_LIMIT=5 +LOGIN_IP_LIMIT=60 + +TELEMETRY_ENABLED=1 +TELEMETRY_TRACE_SAMPLE_RATIO=1.0 +TELEMETRY_BENCHMARK_ENABLED=0 + +# Generated locally by scripts/bootstrap.sh. +GRAFANA_ADMIN_PASSWORD= diff --git a/.gitignore b/.gitignore index b5a71896..7e1077f8 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,10 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. + +# Generated local security configuration +/infra/rabbitmq/rabbitmq.conf +/certs/ +/openbao-local/ + +openbao-local/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..efe8e6a4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +FROM python:3.13.15-slim + +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY alembic.ini . +COPY migrations ./migrations +COPY src ./src +COPY scripts ./scripts +COPY tests ./tests + +RUN useradd --create-home --uid 10001 appuser + +USER appuser + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)" || exit 1 + +CMD ["uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8080"] \ No newline at end of file diff --git a/REPORT.md b/REPORT.md index 9801db45..84610536 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,247 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +## Безопасность, mTLS и OpenBao + +- **Автор, группа:** Травкин Станислав, БВТ2304. +- **Целевая оценка:** 3. +- **Ветка:** `solution/bvt2304-travkin`. +- **Commit/PR:** итоговый коммит и PR будут созданы после проверки отчёта. +- **Источники и инструменты:** README и контракты курса, реализация lab6, документация используемых компонентов; Python, FastAPI, SQLAlchemy, Alembic, asyncpg, argon2-cffi, redis, pika, boto3, Pillow, Docker Compose, OpenSSL, OpenTelemetry. ChatGPT использовался для проектирования, подготовки кода и команд, диагностики, тестирования и оформления отчёта. Команды выполнялись на локальном стенде. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +### Окружение + +WSL2 Ubuntu, PyCharm, Python 3.13.15, Docker Engine 29.8.0, Docker Compose 5.5.1, OpenSSL 3.0.2. Образы: PostgreSQL 17.6, Redis 8.2.2, RabbitMQ 4.1.4-management-alpine, MinIO RELEASE.2025-09-07T16-13-09Z, Nginx 1.29-alpine, OpenBao 2.3.2, Collector Contrib 0.120.0 (тег), Prometheus 3.2.1, Grafana 11.5.2, Loki 3.4.2, Tempo 2.7.1. + +Необходимы Git, Python 3.13, Docker Compose, OpenSSL, доступ к registry и sudo для подготовки прав TLS keys. + +```bash +git clone -b solution/bvt2304-travkin ssh://git@gitea.privcloud.tech:2222/casablancawastaken/mtusi2026lab7.git +cd mtusi2026lab7 +python3.13 -m venv .venv +source .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install -r requirements.txt +make check +make validate +bash scripts/bootstrap.sh +docker compose config --quiet +docker compose build +docker compose up -d openbao +``` + +Bootstrap создаёт локальный CA, leaf certificates, mTLS allowlist, инфраструктурные credentials, конфигурации аутентификации и `.env`. Секреты не поставляются в Git. + +После готовности OpenBao выполнить **только для нового хранилища**: + +```bash +bash scripts/init-openbao.sh +bash scripts/unseal-openbao.sh +bash scripts/configure-openbao.sh +bash scripts/seed-openbao.sh +docker compose up -d --no-build +docker compose ps -a +``` + +Операторские материалы сохраняются вне репозитория в `$HOME/.local/share/lab7-openbao-operator/init.json` (каталог 700, файл 600). Для независимого стенда можно задать `BAO_OPERATOR_FILE`. Три unseal shares, порог два. Root token используется оператором, не приложениями. + +Дождаться готовности API и завершения `migrate` и `s3-init` с кодом 0: + +```bash +curl --fail --cacert certs/ca/ca.crt https://localhost:8443/health/ready +export BASE_URL=https://localhost:8443 +export CA_FILE="$PWD/certs/ca/ca.crt" +make test BASE_URL="$BASE_URL" CA_FILE="$CA_FILE" +make test-security BASE_URL="$BASE_URL" CA_FILE="$CA_FILE" +python student-tests/test_public_tls.py +``` + +API: `https://localhost:8443`. Grafana: `https://localhost:3000`. MinIO Console: `https://localhost:9001`. Последние два опубликованы только на loopback. OpenBao доступен по `https://openbao:8200` внутри Docker-сети. Для браузера требуется доверие локальному CA; отключать TLS verification не нужно. Административные credentials находятся в локальных `.env` и `secrets/`. + +Обычный перезапуск: `bash scripts/restart.sh`. После полной остановки: + +```bash +docker compose up -d openbao +bash scripts/unseal-openbao.sh +docker compose up -d +``` + +Повторные init и seed не нужны. Безопасная остановка: `docker compose down`. Намеренное удаление учебных Docker volumes: `docker compose down -v` (удаляет данные). OpenBao использует отдельный bind mount `openbao-local/data`, который эта команда не удаляет; его полный сброс требует отдельного осознанного удаления storage и подготовки новых операторских материалов. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Из lab6 перенесены бизнес-API, модели, миграции, обработка вложений, идемпотентность, worker, dispatcher и наблюдаемость. Добавлены PKI, HTTPS, mTLS, Argon2id, rate limiting, Redis ACL, scoped identities, OpenBao и hardening. + +```text +Client -- HTTPS :8443 --> Nginx + | mandatory mTLS + +--------+--------+ + v v + API-1 proxy API-2 proxy + | loopback HTTP | loopback HTTP + v v + API-1 API-2 + +--------+--------+ + +-- TLS --> PostgreSQL / Redis / MinIO +Dispatcher -- TLS --> PostgreSQL / RabbitMQ +Worker ----- TLS --> PostgreSQL / RabbitMQ / MinIO +API / Worker / Dispatcher -- TLS + cert auth --> OpenBao +API / Worker / Dispatcher -- TLS + Basic Auth --> Collector +Collector -- TLS --> Loki / Tempo +Prometheus -- TLS --> Collector metrics +Grafana -- TLS --> Prometheus / Loki / Tempo +``` + +PostgreSQL — источник истины для пользователей, чатов, сообщений, метаданных вложений и задач. Redis хранит сессии и общие rate-limit counters. MinIO хранит оригиналы и производные изображения. RabbitMQ доставляет фоновые задачи. Dispatcher публикует задачи на основании состояния PostgreSQL; повторная доставка учитывается через идемпотентность, generation и execution_id. Бизнес-изменения фиксируются транзакциями PostgreSQL; S3 и broker не входят в единую распределённую транзакцию. Обе API-реплики используют общие хранилища. + +`.env.example` документирует настройки; фактические runtime values определены в `compose.yaml` и коде. Сессии используют Redis, Uvicorn слушает loopback, секреты приложений находятся в `/run/app-secrets`, CA — `/run/ca/ca.crt`. Argon2id фиксируется в `src/security.py`. + +### Модель угроз и доверие + +- [Модель угроз](docs/threat-model.md). +- [Матрица доверия](contracts/trust-matrix.md): 12 обязательных связей и дополнительные служебные каналы. + +CA RSA 3072 действует 365 дней; leaf RSA 2048 — 90 дней, с SAN и EKU. LB проверяет CA и SAN `api.internal`; API sidecars требуют клиентский сертификат и allowlist fingerprint LB. HTTP до Uvicorn ограничен loopback. + +OpenBao работает в server mode с persistent file storage. Четыре cert identities: `bao-api-1`, `bao-api-2`, `bao-worker`, `bao-dispatcher`. API имеют общую scoped policy, worker и dispatcher — отдельные. Token TTL 900 s, max TTL 3600 s. При старте читается только собственный KV path; credentials записываются в tmpfs, token не сохраняется. Новый запуск при sealed OpenBao завершается ошибкой. ## Доказательства критериев +Все файлы доказательств находятся в `evidence/`, собственные тесты — в `student-tests/`. Публичные тесты и обязательный контракт не ослаблялись. + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный HTTPS smoke | make test с BASE_URL и CA_FILE | PASS | grade3-smoke-final.txt | +| Внешний TLS | make test-security; test_public_tls.py | TLS 1.3, неверные CA и hostname отклонены | grade3-public-security.txt; grade3-public-tls-negative.txt | +| Argon2id | benchmark_argon2.py; проверка хешей | m=32768, t=2, p=1, уникальные salt | grade3-argon2-container.txt; grade3-argon2-runtime.txt | +| mTLS обеих API | test_mtls.py | LB 200; без cert и чужой CA 400; запрещённая identity 403 | grade3-mtls-security.txt | +| Нет обхода API | audit_network.py | HTTP 8080 недоступен по сети | grade3-network-audit-final.txt | +| PostgreSQL TLS и ACL | test_data_security.py | TLS 1.3; plaintext, неверный CA/hostname и лишние права запрещены | grade3-data-security.txt; grade3-postgres-roles.txt | +| Redis TLS и ACL | test_data_security.py | Сессии и Lua counters работают; чужие keys и CONFIG запрещены | grade3-data-security.txt | +| MinIO TLS и scoped access | test_minio_security.py | Разрешённые операции проходят, лишние запрещены | grade3-minio-security.txt | +| RabbitMQ TLS и ACL | test_rabbitmq_security.py | Раздельные producer/consumer permissions | grade3-rabbitmq-security.txt | +| Collector TLS/auth | test_collector_security.py | Авторизованный ingest проходит, anonymous отклонён | grade3-collector-security.txt | +| Loki/Tempo TLS/ACL | test_telemetry_backends.py; test_telemetry_queries.py | Ingest и queries работают с нужными identities | grade3-telemetry-backends.txt; grade3-telemetry-queries.txt | +| Prometheus TLS | test_prometheus_security.py | Три HTTPS targets UP | grade3-prometheus-security.txt | +| Grafana TLS/data sources | test_grafana_security.py | Prometheus/Loki health и Tempo TraceQL query проходят | grade3-grafana-security.txt | +| OpenBao scoped policies | test_openbao_security.py | Own read разрешён; foreign path/write запрещены | grade3-openbao-security.txt | +| OpenBao TLS | test_openbao_tls.py | Неверные CA/hostname и отсутствие identity отклонены | grade3-openbao-tls.txt | +| OpenBao persistence | Пересоздание, unseal, повторная авторизация | Cluster ID и данные сохранены | grade3-openbao-persistence.txt; grade3-openbao-recovery.txt | +| OpenBao fail-closed | Новый API при sealed OpenBao | Запуск отклонён | grade3-openbao-fail-closed.txt | +| Нет root token в app | Проверка окружения, tmpfs, policies | Только scoped credentials | grade3-openbao-integration.txt | +| Hardening | test_container_hardening.py | 22 контейнера проверены | grade3-hardening-runtime.txt | +| Порты | audit_network.py; Docker inspect | Ingress 8443, локальные 3000/9001 | grade3-published-ports.txt; grade3-network-audit-final.txt | +| Секреты | audit_secrets.py | 253 файла, 44 шаблона, 0 совпадений на момент проверки | grade3-final-secret-audit.txt | +| Образы | audit_images.py | 5 образов, 13 слоёв, 11237 файлов на чистом стенде, 0 совпадений | grade3-clean-image-audit.txt; grade3-image-content-audit.txt | +| Зависимости | pip-audit | Известные уязвимости не обнаружены на момент проверки | grade3-dependency-audit.txt | +| Username limit | test_rate_limit.py | 5 попыток, затем 429/Retry-After; TTL восстанавливает доступ | grade3-rate-limit-username.txt | +| IP limit | test_rate_limit_ip.py | 60 попыток, затем 429; spoofed X-Forwarded-For не обходит лимит | grade3-rate-limit-ip.txt | +| Upload limits | test_upload_limits.py | 413 при превышении лимита, 415 для неподдерживаемого типа | grade3-upload-limits.txt | +| Чужие чаты и вложения | make test | Доступ запрещён; X-User-Id не меняет identity | grade3-smoke-final.txt | +| Logout | make test | Старый token отклонён | grade3-smoke-final.txt | +| Session expiry | test_session_expiry.py | До TTL 200, после 401 | grade3-session-expiry.txt | +| PKI bootstrap | generate-certs.sh | Проверены CA chain, SAN, EKU | grade3-certificates.txt | +| Persistence | make test-persistence | Данные и существующая сессия сохранены | grade3-persistence.txt | +| Failover API-1 | make test-failover | 91 успешная запись; recovery 2.157 s | grade3-failover-first.txt | +| Failover API-2 | make test-failover | 93 успешные записи; recovery 2.12 s | grade3-failover-second.txt | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Argon2id + +Гипотеза: параметры выше минимума OWASP (19456 KiB, t=2, p=1) обеспечат приемлемую стоимость проверки пароля. WSL2: 20 логических CPU, около 11 GiB RAM. API ограничен 1 CPU и 512 MiB RAM. Методика: прогрев, 10 измерений на конфигурацию, медиана в API-контейнере. + +| Memory, KiB | Time cost | Parallelism | Hash, ms | Verify, ms | +| --- | --- | --- | --- | --- | +| 19456 | 2 | 1 | 51.58 | 51.69 | +| 32768 | 2 | 1 | 94.14 | 98.93 | +| 65536 | 3 | 1 | 267.54 | 273.54 | +| 65536 | 3 | 4 | 343.41 | 302.98 | + +Выбрано 32768 KiB, t=2, p=1, salt 16 bytes, hash 32 bytes. Медиана около 100 ms. Это последовательный benchmark, не нагрузочный тест параллельных login-запросов. + +### Rate limiting и сессии + +Общие Redis counters: 5 запросов на username и 60 на IP за 60 секунд, атомарное обновление Lua. Проверены обе реплики, HTTP 429 и Retry-After, восстановление после TTL. Сессии имеют TTL 3600 s, чтение не продлевает TTL, logout удаляет токен. API ограничивает upload 10 MiB и 40 млн пикселей, Nginx — 12 MiB. + +### Persistence и failover + +```bash +make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=https://localhost:8443 CA_FILE="$PWD/certs/ca/ca.crt" +make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=https://localhost:8443 CA_FILE="$PWD/certs/ca/ca.crt" +``` + +Persistence: перезапущены API, worker, dispatcher, Nginx, TLS proxies, PostgreSQL, Redis, RabbitMQ, MinIO, OpenBao и наблюдаемость. Volumes сохранены. OpenBao распечатан без повторного init/seed. `migrate` и `s3-init` повторно завершились с кодом 0. Подтверждённые данные и существующая сессия сохранены; отдельное доказательство сохранности вложений в этом тесте не заявляется. Доказательства: `grade3-persistence-before.txt`, `grade3-persistence-after.txt`, `grade3-persistence.txt`. + +Failover: публичный тест выбирает реплику по X-Instance-Id, hook останавливает её и TLS proxy. После первого теста реплика восстановлена, проверены обе реплики, затем проведён второй тест. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Перезапуск стенда | Сохранность данных и сессии | PASS | 72.389 s — длительность всего теста; потерь не обнаружено | +| Остановка API-1 | Работа через API-2 | 91 успешная запись, 2 неудачные попытки | 2.157 s; подтверждённые записи сохранены | +| Остановка API-2 | Работа через API-1 | 93 успешные записи, 2 неудачные попытки | 2.12 s; подтверждённые записи сохранены | +| Sealed OpenBao | Новый API не стартует | PASS, fail-closed | Восстановление после unseal | + +В обоих failover-тестах до отказа наблюдались две реплики; тестовый цикл записи длился 15 s. Дублирования и потери подтверждённых сообщений не обнаружено. Неудачные попытки не равнозначны потере данных. После восстановления HTTPS smoke прошёл. Raw evidence: `grade3-failover-first.txt`, `grade3-failover-second.txt`, сопутствующие файлы состояния контейнеров и health probes. Полноценный нагрузочный эксперимент с RPS, p95/p99 и исследовательским сравнением не заявляется. + +### Hardening и scan triage + +Проверено 22 контейнера, включая два одноразовых. Приложения работают с UID 10001, без capabilities, с no-new-privileges, CPU/RAM limits и pids_limit 256. Нет privileged mode, host network и Docker socket mounts. Сетевые порты проверены probes. + +`pip-audit` не обнаружил известных уязвимостей Python-зависимостей. Проверка файловой системы пяти образов не выявила секретных путей. Первичный аудит обнаружил MinIO Access Key ID в evidence и логах s3-init; совпадений с проверяемыми секретными ключами и паролями не выявлено. Вывод идентификаторов устранён, evidence обезличен, s3-init пересоздан. Повторный аудит: 0 совпадений. Дополнительно проверены конфигурации, история и содержимое слоёв пяти актуальных прикладных образов. Полный CVE-скан сторонних образов не проводился. + +### Жизненный цикл credentials + +Оператор создаёт CA и leaf certificates; CA private key не передаётся приложениям. При истечении leaf требуется перевыпуск и обновление trust binding; для LB — fingerprint allowlist, для OpenBao — cert identity. Статические DB/Redis/S3/broker/telemetry credentials не имеют автоматического TTL; смена требует согласованного обновления зависимости, KV и потребителя. При старте приложение повторяет cert auth. После рестарта OpenBao выполняется unseal. Автоматический CA rollover, ротация и эксперимент с отзывом не заявляются. + +### Дополнительный аудит сохранённой телеметрии + +`student-tests/audit_telemetry.py` выполняет запросы через Grafana с проверкой CA и hostname. Проверены 46 известных шаблонов credentials и маркеры приватных ключей. + +| Источник | Объём проверки | Результат | Evidence | +| --- | --- | --- | --- | +| Loki | 3377 записей, 3 service_name, окно 7 суток | 0 совпадений | grade3-loki-secret-audit-final.txt | +| Tempo | 3259 найденных trace ID за 10 минут, 100 тел трасс | 0 совпадений | grade3-tempo-secret-audit.txt | +| Prometheus | 4121 набор labels за 7 суток | 0 совпадений | grade3-prometheus-secret-audit.txt | + +Первоначальный запрос Tempo завершился HTTP 500; ошибка сохранена в `grade3-telemetry-audit-initial-failure.txt`. Повторная проверка с ограниченным окном и выборкой завершилась успешно. Это не исчерпывающий аудит raw storage, всех трасс, потоков без service_name или exemplars. + +### Расширенный аудит образов + +`student-tests/audit_images.py` проверяет конфигурацию и историю образов, имена и содержимое файлов в экспортированных слоях. На основном стенде: 5 образов, 13 уникальных слоёв, 10819 файлов, 44 шаблона, 0 совпадений (`grade3-image-content-audit.txt`). На чистом стенде после исправления зависимостей: 5 образов, 13 слоёв, 11237 файлов, 41 шаблон, 0 совпадений (`grade3-clean-image-audit.txt`). Проверяются актуальные собранные образы, а не все исторические образы Docker-хоста. Повторный `pip-audit` не выявил известных уязвимостей (`grade3-clean-dependency-audit.txt`). + +### Воспроизводимость из чистого clone + +Проверка выполнена в отдельном Git-клоне снимка подготовленных изменений, проект Compose `lab7verify`, независимые volumes, CA, секреты и операторский файл. Порты 18443, 13000 и 19001 опубликованы на loopback. Основной стенд оставался доступным. Сборка пяти прикладных образов выполнена с использованием доступного Docker cache. + +Обнаружены и устранены проблемы: системный Python 3.10 несовместим с выбранными зависимостями (использован Python 3.13); добавлен `openapi-spec-validator==0.7.2` в requirements.txt; healthcheck RabbitMQ изменён с timeout 15s/start_period 40s на 30s/120s, без ослабления check_running. Первый общий запуск потребовал повторной команды. Холодный запуск RabbitMQ с отдельным пустым томом после исправления: 67.392 s загрузка брокера, 87.131 s до завершения команды ожидания; обе durable queues созданы, TLS включён. Затем восстановлен исходный том проверочного стенда. + +| Проверка | Результат | Evidence | +| --- | --- | --- | +| Изоляция, bootstrap и сборка | PASS | grade3-clean-isolation.txt; grade3-clean-bootstrap.txt; grade3-clean-build.txt | +| OpenBao init/unseal/config/seed | PASS | grade3-clean-openbao-init.txt; grade3-clean-openbao-unseal.txt; grade3-clean-openbao-config.txt; grade3-clean-openbao-seed.txt | +| Первый запуск и восстановление | Первоначальная ошибка RabbitMQ, повторный запуск PASS | grade3-clean-startup-initial.txt; grade3-clean-startup-recovery.txt | +| Холодный запуск RabbitMQ | PASS | grade3-clean-rabbitmq-cold-start.txt; grade3-clean-rabbitmq-cold-start-details.txt | +| Итоговое состояние | 20 running, migrate и s3-init exit 0 | grade3-clean-final-containers.txt | +| Smoke и внешний TLS | PASS | grade3-clean-final-smoke.txt; grade3-clean-final-security.txt | +| Независимые CA | Взаимное недоверие подтверждено | grade3-clean-ca-isolation.txt | +| Сеть и hardening | PASS, 22 контейнера | grade3-clean-network-audit.txt; grade3-clean-hardening.txt | +| Секреты | 0 совпадений, 41 шаблон | grade3-clean-secret-audit.txt | + +Проверочный стенд остановлен без удаления volumes. Доказательства перенесены в основной репозиторий. Финальные make check, make validate, make test, make test-security и аудит 253 файлов основного проекта (44 шаблона, 0 совпадений) прошли успешно. Основной стенд не пересоздавался ради обновления отчёта; новые образы и исправленный healthcheck проверены на независимом стенде. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Один Docker-хост, нет HA-кластеров хранилищ и балансировщика; проверен отказ каждой API отдельно, не одновременный отказ обеих. +- OpenBao требует операторского unseal. Уже запущенные приложения могут работать с ранее полученными статическими credentials при sealed OpenBao. +- Компрометация хоста/Docker daemon вне модели защиты. Bootstrap credentials остаются в закрытом локальном каталоге; unseal shares хранятся совместно в учебном операторском файле. +- Redis хранит рабочие session tokens. Rate limit не исключает распределённый login DoS и временную блокировку username. Параллельная нагрузка Argon2id отдельно не измерялась. +- PostgreSQL local trust ограничен Unix socket внутри контейнера; Prometheus Basic Auth не предоставляет endpoint RBAC. +- Расширенное mTLS RabbitMQ/Collector, автоматическая ротация и полный image scan не реализованы в заявленном объёме. +- Аудит секретов ограничен известными локальными значениями и шаблонами приватных ключей; проверка образов охватывает слои пяти актуальных прикладных образов, но не все сторонние и ранее собранные образы. +- Чистое развёртывание проверено в независимом клоне. Первый общий запуск потребовал повторной команды из-за RabbitMQ; после изменения healthcheck отдельно проверен холодный запуск брокера с пустым томом. Полный запуск всех сервисов с нуля после последнего изменения healthcheck не повторялся. + +## Итог + +Реализован защищённый вариант мессенджера lab6 с HTTPS, обязательным mTLS LB → API, TLS инфраструктурных связей, Argon2id, rate limiting, scoped identities и OpenBao. Публичный HTTPS smoke, отрицательные проверки безопасности, persistence и последовательный failover обеих API-реплик успешно пройдены. Дополнительно выполнены чистое развёртывание, аудит сохранённой телеметрии и слоёв прикладных образов. Задания на оценки 4 и 5 не выполнялись. Работа представляется на оценку 3. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 00000000..017e41ad --- /dev/null +++ b/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..0443eaff --- /dev/null +++ b/compose.yaml @@ -0,0 +1,646 @@ +x-api: &api + build: + context: . + dockerfile: Dockerfile + environment: &api-environment + APP_ENV: lab + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_USERNAME: messenger_api + TELEMETRY_ENABLED: "${TELEMETRY_ENABLED:-1}" + TELEMETRY_TRACE_SAMPLE_RATIO: "${TELEMETRY_TRACE_SAMPLE_RATIO:-1.0}" + TELEMETRY_BENCHMARK_ENABLED: "${TELEMETRY_BENCHMARK_ENABLED:-0}" + SESSION_TTL_SECONDS: 3600 + DATABASE_URL_FILE: /run/app-secrets/database_url + CACHE_URL_FILE: /run/app-secrets/cache_url + S3_ENDPOINT: https://s3:9000 + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + S3_ACCESS_KEY_ID_FILE: /run/app-secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/app-secrets/s3_secret_access_key + MAX_UPLOAD_BYTES: 10485760 + MAX_IMAGE_PIXELS: 40000000 + RABBITMQ_HOST: rabbitmq + RABBITMQ_PASSWORD_FILE: /run/app-secrets/rabbitmq_password + volumes: + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + s3-init: + condition: service_completed_successfully + entrypoint: ["python", "/app/scripts/bao-entrypoint.py"] + tmpfs: + - /run/app-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700,uid=10001,gid=10001 + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + restart: unless-stopped + stop_grace_period: 15s + mem_limit: 512m + cpus: 1.0 + pids_limit: 256 + +services: + openbao: + image: openbao/openbao:2.3.2 + user: "100:1000" + entrypoint: ["bao"] + command: ["server", "-config=/config/openbao.hcl"] + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/ca/ca.crt + volumes: + - ./infra/openbao/openbao.hcl:/config/openbao.hcl:ro + - ./certs/runtime/openbao:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + - ./openbao-local/data:/openbao/data + cap_drop: + - ALL + restart: unless-stopped + mem_limit: 256m + cpus: 0.5 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + postgres: + image: postgres:17.6 + command: + - postgres + - -c + - ssl=on + - -c + - ssl_cert_file=/run/tls/tls.crt + - -c + - ssl_key_file=/run/tls/tls.key + - -c + - hba_file=/etc/postgresql/pg_hba.conf + - -c + - ssl_min_protocol_version=TLSv1.2 + - -c + - password_encryption=scram-sha-256 + environment: + POSTGRES_DB: messenger + POSTGRES_USER: lab2 + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + - db_migrate_password + - db_api_password + - db_worker_password + - db_dispatcher_password + volumes: + - postgres_data:/var/lib/postgresql/data + - ./certs/runtime/postgres:/run/tls:ro + - ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro + - ./infra/postgres/init-roles.sh:/docker-entrypoint-initdb.d/10-roles.sh:ro + - ./infra/postgres/grants.sql:/config/grants.sql:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -h postgres -U lab2 -d messenger"] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + cpus: 1.0 + mem_limit: 768m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + redis: + image: redis:8.2.2 + command: ["redis-server", "/config/redis.conf"] + secrets: + - redis_acl + - redis_api_password + volumes: + - redis_data:/data + - ./infra/redis/redis.conf:/config/redis.conf:ro + - ./certs/runtime/redis:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + healthcheck: + test: + - CMD-SHELL + - 'REDISCLI_AUTH="$$(cat /run/secrets/redis_api_password)" redis-cli --tls --cacert /run/ca/ca.crt --sni redis -h redis --user messenger_api ping | grep -qx PONG' + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + cpus: 0.5 + mem_limit: 256m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + s3: + image: dappros/minio:RELEASE.2025-09-07T16-13-09Z + command: server /data --console-address ":9001" --certs-dir /run/minio-certs + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + secrets: + - minio_root_user + - minio_root_password + volumes: + - s3_data:/data + - ./certs/services/s3/tls.crt:/run/minio-certs/public.crt:ro + - ./certs/services/s3/tls.key:/run/minio-certs/private.key:ro + - ./certs/ca/ca.crt:/run/minio-certs/CAs/ca.crt:ro + ports: + - "127.0.0.1:9001:9001" + healthcheck: + test: + - CMD-SHELL + - 'curl --fail --silent --show-error --cacert /run/minio-certs/CAs/ca.crt https://s3:9000/minio/health/ready >/dev/null' + interval: 10s + timeout: 5s + retries: 10 + start_period: 15s + restart: unless-stopped + cpus: 1.0 + mem_limit: 512m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + s3-init: + image: dappros/minio:RELEASE.2025-09-07T16-13-09Z + entrypoint: [ "/bin/sh", "/config/init.sh" ] + volumes: + - ./infra/minio/init.sh:/config/init.sh:ro + - ./infra/minio/api-policy.json:/config/api-policy.json:ro + - ./infra/minio/worker-policy.json:/config/worker-policy.json:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + secrets: + - minio_root_user + - minio_root_password + - s3_api_access_key_id + - s3_api_secret_access_key + - s3_worker_access_key_id + - s3_worker_secret_access_key + depends_on: + s3: + condition: service_healthy + restart: "no" + cpus: 0.5 + mem_limit: 256m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + migrate: + build: + context: . + dockerfile: Dockerfile + command: ["alembic", "upgrade", "head"] + volumes: + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + secrets: + - source: database_url_migrate + target: database_url + depends_on: + postgres: + condition: service_healthy + restart: "no" + cpus: 1.0 + mem_limit: 512m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + api-1: + <<: *api + environment: + <<: *api-environment + BAO_IDENTITY: bao-api-1 + BAO_ROLE: api + INSTANCE_ID: api-1 + volumes: + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + - ./certs/runtime/bao-api-1:/run/bao-client:ro + + command: ["uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8080", "--proxy-headers", "--forwarded-allow-ips", "127.0.0.1"] + + api-2: + <<: *api + environment: + <<: *api-environment + BAO_IDENTITY: bao-api-2 + BAO_ROLE: api + INSTANCE_ID: api-2 + volumes: + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + - ./certs/runtime/bao-api-2:/run/bao-client:ro + + command: ["uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8080", "--proxy-headers", "--forwarded-allow-ips", "127.0.0.1"] + + api-1-proxy: + image: nginx:1.29-alpine + network_mode: "service:api-1" + entrypoint: ["nginx", "-g", "daemon off;"] + volumes: + - ./certs/generated/api-proxy.conf:/etc/nginx/nginx.conf:ro + - ./certs/services/api-1:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + depends_on: + api-1: + condition: service_healthy + restart: true + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + api-2-proxy: + image: nginx:1.29-alpine + network_mode: "service:api-2" + entrypoint: ["nginx", "-g", "daemon off;"] + volumes: + - ./certs/generated/api-proxy.conf:/etc/nginx/nginx.conf:ro + - ./certs/services/api-2:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + depends_on: + api-2: + condition: service_healthy + restart: true + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + nginx: + image: nginx:1.29-alpine + ports: + - "8443:8443" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + - ./certs/services/nginx:/etc/nginx/tls:ro + - ./certs/services/lb-client:/etc/nginx/client:ro + - ./certs/ca/ca.crt:/etc/nginx/ca/ca.crt:ro + depends_on: + - api-1-proxy + - api-2-proxy + restart: unless-stopped + cpus: 0.5 + mem_limit: 256m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + rabbitmq: + image: rabbitmq:4.1.4-management-alpine + hostname: rabbitmq + extra_hosts: + - "rabbitmq:127.0.0.1" + environment: + ERL_EPMD_ADDRESS: 127.0.0.1 + RABBITMQ_CONFIG_FILE: /etc/rabbitmq/rabbitmq + secrets: + - rabbitmq_definitions + volumes: + - rabbitmq_data:/var/lib/rabbitmq + - ./infra/rabbitmq/tls.conf:/etc/rabbitmq/rabbitmq.conf:ro + - ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro + - ./certs/runtime/rabbitmq:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "check_running"] + interval: 10s + timeout: 30s + retries: 10 + start_period: 120s + restart: unless-stopped + mem_limit: 512m + cpus: 0.5 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + dispatcher: + <<: *api + environment: + <<: *api-environment + BAO_IDENTITY: bao-dispatcher + BAO_ROLE: dispatcher + RABBITMQ_USERNAME: messenger_producer + OTEL_USERNAME: messenger_dispatcher + command: [ "python", "-m", "src.dispatcher" ] + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + s3-init: + condition: service_completed_successfully + healthcheck: + disable: true + volumes: + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + - ./certs/runtime/bao-dispatcher:/run/bao-client:ro + + worker: + <<: *api + environment: + <<: *api-environment + BAO_IDENTITY: bao-worker + BAO_ROLE: worker + RABBITMQ_USERNAME: messenger_consumer + OTEL_USERNAME: messenger_worker + command: [ "python", "-m", "src.worker" ] + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + s3-init: + condition: service_completed_successfully + healthcheck: + disable: true + volumes: + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + - ./certs/runtime/bao-worker:/run/bao-client:ro + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.120.0 + command: ["--config=/etc/otelcol/config.yaml"] + volumes: + - ./infra/otel/config.yaml:/etc/otelcol/config.yaml:ro + - ./certs/runtime/otel-collector:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + secrets: + - otel_htpasswd + - otel_backend_authorization + depends_on: + - loki-proxy + - tempo-proxy + restart: unless-stopped + mem_limit: 256m + cpus: 0.5 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + otel-collector-proxy: + image: nginx:1.29-alpine + network_mode: "service:otel-collector" + entrypoint: ["nginx", "-g", "daemon off;"] + volumes: + - ./infra/telemetry-proxy/otel-collector.conf:/etc/nginx/nginx.conf:ro + - ./certs/services/otel-collector:/run/tls:ro + secrets: + - prometheus_scrape_htpasswd + depends_on: + otel-collector: + condition: service_started + restart: true + restart: unless-stopped + mem_limit: 128m + cpus: 0.25 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + prometheus: + image: prom/prometheus:v3.2.1 + command: + - --config.file=/etc/prometheus/prometheus.yml + - --web.config.file=/run/secrets/prometheus_web + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + - --storage.tsdb.retention.size=1GB + volumes: + - ./infra/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/rules.yaml:/etc/prometheus/rules.yml:ro + - ./certs/runtime/prometheus:/run/tls:ro + - ./certs/ca/ca.crt:/run/ca/ca.crt:ro + - prometheus_data:/prometheus + secrets: + - prometheus_web + - prometheus_scrape_password + depends_on: + - otel-collector-proxy + restart: unless-stopped + mem_limit: 512m + cpus: 0.5 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + loki-proxy: + image: nginx:1.29-alpine + network_mode: "service:loki" + entrypoint: ["nginx", "-g", "daemon off;"] + volumes: + - ./infra/telemetry-proxy/loki.conf:/etc/nginx/nginx.conf:ro + - ./certs/services/loki:/run/tls:ro + secrets: + - otel_backend_htpasswd + - grafana_datasource_htpasswd + depends_on: + loki: + condition: service_started + restart: true + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + loki: + image: grafana/loki:3.4.2 + command: ["-config.file=/etc/loki/config.yaml"] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/config.yaml:ro + - loki_data:/loki + restart: unless-stopped + mem_limit: 512m + cpus: 0.5 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + tempo-proxy: + image: nginx:1.29-alpine + network_mode: "service:tempo" + entrypoint: ["nginx", "-g", "daemon off;"] + volumes: + - ./infra/telemetry-proxy/tempo.conf:/etc/nginx/nginx.conf:ro + - ./certs/services/tempo:/run/tls:ro + secrets: + - otel_backend_htpasswd + - grafana_datasource_htpasswd + depends_on: + tempo: + condition: service_started + restart: true + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + pids_limit: 256 + security_opt: + - no-new-privileges:true + + tempo: + image: grafana/tempo:2.7.1 + command: ["-config.file=/etc/tempo/config.yaml"] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/config.yaml:ro + - tempo_data:/var/tempo + restart: unless-stopped + mem_limit: 512m + cpus: 0.5 + pids_limit: 256 + security_opt: + - no-new-privileges:true + + grafana: + pids_limit: 256 + security_opt: + - no-new-privileges:true + image: grafana/grafana:11.5.2 + environment: + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /run/tls/tls.crt + GF_SERVER_CERT_KEY: /run/tls/tls.key + GF_SERVER_ROOT_URL: https://localhost:3000/ + GF_SECURITY_COOKIE_SECURE: "true" + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env} + GF_USERS_ALLOW_SIGN_UP: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + volumes: + - ./certs/runtime/grafana:/run/tls:ro + - grafana_data:/var/lib/grafana + - ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro + - ./secrets/grafana_datasources.yaml:/etc/grafana/provisioning/datasources/datasources.yaml:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + ports: + - "127.0.0.1:3000:3000" + depends_on: + - prometheus + - loki + - tempo + restart: unless-stopped + mem_limit: 384m + cpus: 0.5 + +secrets: + + prometheus_scrape_password: + file: ./secrets/prometheus_scrape_password + + prometheus_web: + file: ./secrets/prometheus_web.yaml + + otel_backend_authorization: + file: ./secrets/otel_backend_authorization + + prometheus_scrape_htpasswd: + file: ./secrets/prometheus_scrape_htpasswd + + otel_backend_htpasswd: + file: ./secrets/otel_backend_htpasswd + + grafana_datasource_htpasswd: + file: ./secrets/grafana_datasource_htpasswd + + otel_api_password: + file: ./secrets/otel_api_password + + otel_worker_password: + file: ./secrets/otel_worker_password + + otel_dispatcher_password: + file: ./secrets/otel_dispatcher_password + + otel_htpasswd: + file: ./secrets/otel_htpasswd + + postgres_password: + file: ./secrets/postgres_password + + database_url_api: + file: ./secrets/database_url_api + + database_url_worker: + file: ./secrets/database_url_worker + + database_url_dispatcher: + file: ./secrets/database_url_dispatcher + + database_url_migrate: + file: ./secrets/database_url_migrate + + db_api_password: + file: ./secrets/db_api_password + + db_worker_password: + file: ./secrets/db_worker_password + + db_dispatcher_password: + file: ./secrets/db_dispatcher_password + + db_migrate_password: + file: ./secrets/db_migrate_password + + redis_acl: + file: ./secrets/redis_acl + + redis_api_password: + file: ./secrets/redis_api_password + + cache_url: + file: ./secrets/cache_url + + minio_root_user: + file: ./secrets/minio_root_user + + minio_root_password: + file: ./secrets/minio_root_password + + s3_api_access_key_id: + file: ./secrets/s3_api_access_key_id + + s3_api_secret_access_key: + file: ./secrets/s3_api_secret_access_key + + s3_worker_access_key_id: + file: ./secrets/s3_worker_access_key_id + + s3_worker_secret_access_key: + file: ./secrets/s3_worker_secret_access_key + + rabbitmq_producer_password: + file: ./secrets/rabbitmq_producer_password + + rabbitmq_consumer_password: + file: ./secrets/rabbitmq_consumer_password + + rabbitmq_definitions: + file: ./secrets/rabbitmq_definitions.json + +volumes: + + prometheus_data: + + loki_data: + + tempo_data: + + grafana_data: + + postgres_data: + + redis_data: + + s3_data: + rabbitmq_data: diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a9777..ccfd5393 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -4,18 +4,18 @@ | Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | | --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | -| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | -| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | -| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | -| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | -| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | -| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | +| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | HTTPS localhost:8443; CA certs/ca/ca.crt; SAN localhost/127.0.0.1; Bearer TTL 3600 s. Leaf 90 дней. make test и make test-security с CA_FILE; logout/expiry и rate limit. infra/nginx.conf; evidence/grade3-public-security.txt; grade3-public-tls.txt; grade3-session-expiry.txt. | +| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | HTTPS api-1:8443 и api-2:8443; локальный CA; проверка SAN api.internal; client identity lb-client; обязательный client cert и allowlist SHA-1 fingerprint leaf. Leaf 90 дней. student-tests/test_mtls.py: правильная identity 200, без cert/чужой CA 400, запрещённая trusted identity 403, порт 8080 закрыт. infra/nginx.conf; infra/api-proxy/nginx.conf.template; evidence/grade3-mtls-security.txt. | +| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | postgres:5432, TLS verify-full, CA /run/ca/ca.crt, SAN postgres. Роли messenger_api, messenger_worker, messenger_dispatcher и отдельная messenger_migrate. API CRUD бизнес-таблиц; worker/dispatcher SELECT и UPDATE attachments и attachment_jobs; migrate выполняет DDL. Статические пароли без TTL, leaf 90 дней. student-tests/test_data_security.py: TLS/roles allow, plaintext/чужой CA/неверный hostname/лишние права deny. infra/postgres/pg_hba.conf; src/database.py; evidence/grade3-data-security.txt; grade3-postgres-roles.txt. | +| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | https://s3:9000; локальный CA, SAN s3; раздельные API/worker access keys; private bucket. API: ListBucket, staging Get/Put/Delete, attachments и variants Get. Worker: staging Get, attachments и variants Put. Статические keys без TTL; leaf 90 дней. student-tests/test_minio_security.py: разрешённые и запрещённые операции. infra/minio/*-policy.json; src/storage.py; evidence/grade3-minio-security.txt. | +| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | Фактические клиенты dispatcher и worker; AMQPS rabbitmq:5671, локальный CA, SAN rabbitmq; vhost messenger. messenger_producer публикует через default exchange, messenger_consumer читает attachment.process.v1. Configure запрещён обоим. API напрямую broker не использует. Пароли статические, leaf 90 дней. student-tests/test_rabbitmq_security.py: publish/consume allow, лишние ACL и TLS deny. infra/rabbitmq/tls.conf; src/queue.py; evidence/grade3-rabbitmq-security.txt. | +| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | HTTPS otel-collector:4318, OTLP HTTP; локальный CA, SAN otel-collector. Basic Auth messenger_api, messenger_worker, messenger_dispatcher. Статические пароли, leaf 90 дней. student-tests/test_collector_security.py: авторизованный ingest 200, anonymous/wrong credentials 401, неверный TLS deny. infra/otel/config.yaml; src/telemetry.py; evidence/grade3-collector-security.txt. | +| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | HTTPS loki:3100/otlp/v1/logs и tempo:3200/v1/traces; локальный CA, SAN loki/tempo. Basic Auth collector, разрешены только ingest endpoints. Статический пароль, leaf 90 дней. student-tests/test_telemetry_backends.py и student-tests/test_telemetry_queries.py: ingest allow, query/чужие credentials deny. infra/telemetry-proxy/loki.conf и tempo.conf; evidence/grade3-telemetry-backends.txt; grade3-telemetry-queries.txt. | +| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | HTTPS prometheus:9090, loki:3100, tempo:3200; локальный CA, SAN каждого сервиса; Basic Auth grafana. Loki/Tempo разрешают только query endpoints; Prometheus Basic Auth без endpoint RBAC. Статический пароль, leaf 90 дней. student-tests/test_grafana_security.py: datasource health и TraceQL query, anonymous deny. student-tests/test_telemetry_backends.py: ingest deny. evidence/grade3-grafana-security.txt. | +| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | HTTPS openbao:8200; локальный CA, SAN openbao; cert auth bao-api-1, bao-api-2, bao-worker, bao-dispatcher. Policies messenger-api/worker/dispatcher; read только secret/data/messenger/. Token TTL 900 s, max TTL 3600 s, leaf 90 дней. student-tests/test_openbao_security.py и student-tests/test_openbao_tls.py: own read allow, foreign path/write/policy/anonymous/impersonation deny. infra/openbao/policies; scripts/bao-entrypoint.py; evidence/grade3-openbao-security.txt; grade3-openbao-tls.txt. | +| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | OpenBao HTTPS openbao:8200 только внутри Docker-сети; операторские команды через compose и TLS, root token только для административного bootstrap. Grafana https://localhost:3000 и MinIO https://localhost:9001 опубликованы на loopback. Локальный CA, SAN openbao/grafana/s3/localhost. Отдельные admin credentials, статические; leaf 90 дней. bao status, scripts/unseal-openbao.sh, student-tests/test_grafana_security.py; student-tests/audit_network.py; evidence/grade3-openbao-status.txt; grade3-published-ports.txt; grade3-grafana-security.txt. | +| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | rediss://redis:6379/0; локальный CA, SAN redis; ACL messenger_api, default user off. Только session:* и rate:login:*; ограниченный набор команд для сессий и rate limit. Пароль статический, leaf 90 дней, session TTL 3600 s. student-tests/test_data_security.py: session/rate operations allow, foreign key и CONFIG deny. infra/redis/redis.conf; src/sessions.py; evidence/grade3-data-security.txt. | +| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | N/A: кластерная репликация хранилищ не используется. Две API-реплики используют общие хранилища. RabbitMQ distribution/EPMD и OpenBao cluster listener изолированы loopback. student-tests/audit_network.py; evidence/grade3-network-audit-final.txt. Отказ обеих API-реплик по очереди проверен make test-failover; evidence/grade3-failover-first.txt и grade3-failover-second.txt. | Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. @@ -35,3 +35,47 @@ OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. + +## Дополнительные служебные каналы + +| Канал | Защита и ограничение | Доказательство | +| --- | --- | --- | +| Prometheus -> Collector metrics | HTTPS otel-collector:8888 и :8889, CA/SAN verification, Basic Auth prometheus, только GET /metrics | student-tests/test_collector_security.py; evidence/grade3-collector-security.txt | +| Prometheus -> собственные metrics | HTTPS prometheus:9090, CA/SAN verification, Basic Auth prometheus | student-tests/test_prometheus_security.py; evidence/grade3-prometheus-security.txt | +| API sidecar -> Uvicorn | HTTP 127.0.0.1:8080 внутри общего network namespace, после mTLS и allowlist | evidence/grade3-mtls-security.txt; grade3-network-audit-final.txt | +| Loki proxy -> Loki | HTTP 127.0.0.1:13100 после TLS и ACL | evidence/grade3-telemetry-backends.txt | +| Tempo proxy -> Tempo | HTTP 127.0.0.1:13200 и :14318 после TLS и ACL | evidence/grade3-telemetry-backends.txt | +| Collector proxy -> metrics | HTTP 127.0.0.1:18888 и :18889 после TLS и Basic Auth | evidence/grade3-collector-security.txt | +| API healthcheck | HTTP loopback:8080; внешний health endpoint через HTTPS/mTLS | evidence/grade3-network-audit-final.txt | +| PostgreSQL healthcheck | pg_isready внутри контейнера; сетевые DB-соединения требуют TLS | infra/postgres/pg_hba.conf; evidence/grade3-data-security.txt | +| Redis healthcheck | TLS, CA и ACL messenger_api | compose.yaml; evidence/grade3-data-security.txt | +| RabbitMQ healthcheck | Локальный rabbitmq-diagnostics, distribution ограничен loopback | evidence/grade3-network-audit-hardened.txt | +| MinIO healthcheck | HTTPS s3:9000/minio/health/ready с CA | compose.yaml | +| migrate -> PostgreSQL | TLS verify-full, отдельная роль messenger_migrate, Docker secret | migrations/env.py; evidence/grade3-postgres-roles.txt | +| s3-init -> MinIO | HTTPS s3:9000, CA, отдельные root credentials для provisioning | infra/minio/init.sh; evidence/grade3-minio-init-sanitized.txt | +| Операторский bootstrap OpenBao | HTTPS openbao:8200, CA/SAN verification, операторские данные передаются через stdin | scripts/init-openbao.sh; scripts/unseal-openbao.sh; scripts/configure-openbao.sh; scripts/seed-openbao.sh | + +Все локальные plaintext hops ограничены loopback +соответствующего network namespace. Прямой сетевой +доступ к ним отсутствует. + +Публично опубликован только HTTPS ingress :8443. +Grafana :3000 и MinIO console :9001 доступны +на loopback хоста. + +Leaf certificates действуют 90 дней, CA — 365 дней. +Статические инфраструктурные credentials не имеют +автоматического TTL. OpenBao tokens действуют +15 минут, максимальный TTL — 1 час. + +Модель угроз, жизненный цикл credentials и остаточные +риски описаны в ../docs/threat-model.md. + +Заявлена оценка 3. Требования расширенного уровня 4 +и исследовательских треков уровня 5 не заявляются. + +Дополнительная проверка внешнего TLS: +python student-tests/test_public_tls.py. +Проверяются правильный CA/hostname, пустой trust store +и неправильный hostname с доверенным CA. +Результат: evidence/grade3-public-tls-negative.txt. diff --git a/docs/threat-model.md b/docs/threat-model.md new file mode 100644 index 00000000..d6bc7d7d --- /dev/null +++ b/docs/threat-model.md @@ -0,0 +1,205 @@ +# Модель угроз — лабораторная работа №7 + +Автор: Травкин Станислав, БВТ2304. +Целевая оценка: 3. + +## 1. Область применения + +Учебный мессенджер, перенесённый из lab6. +Две реплики API, балансировщик Nginx, PostgreSQL, +Redis, RabbitMQ, MinIO, worker, dispatcher, +OpenBao и стек наблюдаемости. + +Модель рассматривает сетевого нарушителя, +неавторизованного пользователя, авторизованного +пользователя вне чата и компрометацию отдельной +сервисной identity. + +Полная компрометация хоста или Docker daemon +находится за пределами модели защиты. + +## 2. Защищаемые активы + +- Пароли пользователей и сессионные токены. +- Сообщения, чаты и принадлежность пользователей к чатам. +- Оригиналы вложений и производные изображения. +- Состояния задач обработки вложений. +- Учётные данные инфраструктурных сервисов. +- CA private key, leaf keys, root token и unseal shares. +- Метрики, логи и трассировки. +- Доступность API и сохранность подтверждённых данных. + +## 3. Акторы + +- Неавторизованный внешний клиент. +- Авторизованный пользователь мессенджера. +- Пользователь, не являющийся участником чата. +- Nginx — доверенный балансировщик. +- API-1 и API-2 — обработчики бизнес-запросов. +- Worker — обработчик вложений. +- Dispatcher — публикация фоновых задач. +- Collector и Grafana — наблюдаемость. +- Оператор — bootstrap, управление PKI и OpenBao. + +## 4. Границы доверия + +1. Клиент -> Nginx: HTTPS, проверка CA и hostname. +2. Nginx -> API: обязательное mTLS и allowlist + сертификата балансировщика. +3. TLS sidecar -> приложение: HTTP только через + loopback общего network namespace. +4. Приложения -> хранилища и broker: + TLS с проверкой сервера и scoped credentials. +5. Приложения -> OpenBao: TLS, cert auth, + отдельные сервисные identities и scoped policies. +6. Приложения -> Collector -> telemetry backends: + TLS и раздельная аутентификация. +7. Оператор -> административные интерфейсы: + локальные порты либо защищённая Docker-сеть. +8. Хост -> контейнеры: ограниченные mounts, + отсутствие Docker socket и privileged mode. + +Полная матрица связей приведена в +contracts/trust-matrix.md. + +## 5. Угрозы и меры защиты + +| Угроза | Мера защиты | Проверка и доказательство | +| --- | --- | --- | +| Перехват трафика клиента | HTTPS, доверенный CA, проверка hostname | make test-security; evidence/grade3-public-security.txt | +| Подмена балансировщика | Обязательное mTLS, allowlist leaf fingerprint | student-tests/test_mtls.py; evidence/grade3-mtls-security.txt | +| Обход TLS через API-порт | Uvicorn слушает только loopback | evidence/grade3-network-audit-final.txt | +| Подбор пароля | Argon2id, Redis rate limit по username и IP | evidence/grade3-argon2-container.txt; grade3-rate-limit-username.txt; grade3-rate-limit-ip.txt | +| Кража базы паролей | Argon2id, индивидуальные salt, параметры в хеше | evidence/grade3-argon2-runtime.txt | +| Подмена пользователя | Bearer identity, игнорирование X-User-Id | make test; evidence/grade3-smoke-final.txt | +| Доступ постороннего к чату и вложениям | Проверка membership на стороне API | make test; evidence/grade3-smoke-final.txt | +| Использование завершённой сессии | Удаление токена при logout, Redis TTL | evidence/grade3-session-expiry.txt; grade3-smoke-final.txt | +| Чрезмерный размер загрузки | Ограничения Nginx, API и количества пикселей | evidence/grade3-upload-limits.txt | +| Повышение привилегий в PostgreSQL | Раздельные роли и ограниченные GRANT | evidence/grade3-data-security.txt; grade3-postgres-roles.txt | +| Несанкционированный доступ к S3 | Private bucket, раздельные prefix policies | evidence/grade3-minio-security.txt | +| Несанкционированная публикация или чтение задач | Раздельные RabbitMQ producer/consumer ACL | evidence/grade3-rabbitmq-security.txt | +| Произвольный telemetry ingest | TLS и аутентификация отправителей | evidence/grade3-collector-security.txt | +| Несанкционированное чтение telemetry | Раздельные credentials для ingest и queries | evidence/grade3-telemetry-backends.txt; grade3-grafana-security.txt | +| Чтение чужих секретов OpenBao | Cert auth и scoped KV policies | evidence/grade3-openbao-security.txt | +| Запуск приложения без доступных секретов | Fail-closed bootstrap | evidence/grade3-openbao-fail-closed.txt | +| Утечка секретов в Git и логи | Исключение файлов, локальный аудит, редактирование идентификаторов | evidence/grade3-secret-audit.txt | +| Утечка секретов в образ | Ограниченный build context и COPY | evidence/grade3-image-audit.txt | +| Избыточные права контейнера | Non-root для приложений, cap_drop, no-new-privileges, limits | evidence/grade3-hardening-runtime.txt | +| Потеря данных при перезапуске | Persistent storage, сохранение volumes | evidence/grade3-persistence.txt | +| Отказ одной реплики API | Две реплики, Nginx failover, общие хранилища, idempotency | evidence/grade3-failover-first.txt; grade3-failover-second.txt | + +## 6. Параметры защиты + +Argon2id: +- memory_cost = 32768 KiB; +- time_cost = 2; +- parallelism = 1; +- salt_len = 16 bytes; +- hash_len = 32 bytes. + +Медианное время в API-контейнере: +хеширование 94.14 ms, проверка 98.93 ms. +Параметры выбраны по результатам измерений. + +Login rate limit: +- 5 запросов на username за 60 секунд; +- 60 запросов на IP за 60 секунд; +- общие Redis-счётчики для обеих реплик; +- HTTP 429 и Retry-After при превышении; +- атомарное обновление счётчиков через Lua. + +Сессии: +- случайный Bearer token; +- хранение в Redis; +- TTL 3600 секунд; +- logout удаляет сессию; +- обычное чтение сессии не продлевает TTL. + +Загрузка: +- API: максимум 10 MiB; +- Nginx: максимум 12 MiB; +- максимум 40 миллионов пикселей; +- проверка формата изображения. + +## 7. Жизненный цикл сертификатов и секретов + +Локальный CA создаётся оператором. +CA RSA 3072, срок действия 365 дней. +Leaf certificates RSA 2048, срок действия 90 дней. +Сертификаты имеют SAN и соответствующий EKU. + +CA private key не передаётся приложениям. +Сервисы получают только необходимые leaf keys, +публичный CA и scoped credentials. + +OpenBao работает в server mode с persistent +file storage, без dev-mode. + +Первичная инициализация создаёт три unseal shares, +порог распечатывания — два. + +Операторские материалы хранятся вне репозитория +в каталоге с правами 700 и файле с правами 600. + +API-1, API-2, worker и dispatcher используют +индивидуальные клиентские сертификаты OpenBao. + +Рабочие OpenBao tokens имеют TTL 15 минут +и maximum TTL 1 час, без default policy. + +Приложение получает только свой набор KV secrets, +сохраняет его в tmpfs с ограниченными правами +и не сохраняет OpenBao token. + +При новом запуске приложение повторно проходит +cert auth. Постоянный renewal не используется: +OpenBao token нужен для стартового чтения KV. + +После рестарта OpenBao оператор выполняет unseal. +Повторная инициализация и повторный seed +при обычном рестарте не требуются. + +При истечении leaf certificate оператор должен +выпустить новый сертификат, обновить trust binding +и перезапустить соответствующий сервис. +Для LB также обновляется fingerprint allowlist. + +Статические DB, Redis, S3, RabbitMQ и telemetry +credentials не имеют автоматического TTL. +Их ротация требует согласованного обновления +учётных данных, OpenBao KV и потребителей. + +Автоматическая ротация и эксперимент с отзывом +credentials не заявляются для оценки 3. + +## 8. Остаточные риски и ограничения + +- Один Docker-хост является общей точкой отказа. +- PostgreSQL, Redis, RabbitMQ, MinIO, Nginx и + OpenBao не имеют HA-кластеров. +- Компрометация хоста или Docker daemon позволяет + обойти контейнерную изоляцию. +- Операторские unseal shares хранятся совместно + в защищённом локальном файле учебного стенда. + Для production требуется раздельное хранение. +- Bootstrap credentials остаются в закрытом + локальном каталоге secrets. +- Уже запущенные приложения могут использовать + полученные статические credentials при sealed + OpenBao до своего перезапуска или отзыва credentials. +- Rate limit снижает риск перебора и login DoS, + но не гарантирует защиту от распределённой атаки. +- Username rate limit допускает временную блокировку + входа конкретного пользователя. +- Redis хранит рабочие сессионные токены; + компрометация Redis остаётся существенной угрозой. +- PostgreSQL local trust ограничен локальным + Unix socket внутри контейнера. +- Prometheus использует Basic Auth без отдельного + RBAC для каждого HTTP endpoint. +- Проверка секретов ограничена известными локальными + значениями и шаблонами приватных ключей. +- Проверка образов не является полным layer scan. +- mTLS для RabbitMQ и Collector, автоматическая + ротация, CA rollover и расширенный image scan + не входят в заявленный уровень 3. diff --git a/evidence/grade3-argon2-checks.txt b/evidence/grade3-argon2-checks.txt new file mode 100644 index 00000000..ff9a5759 --- /dev/null +++ b/evidence/grade3-argon2-checks.txt @@ -0,0 +1,11 @@ +PASS: Argon2id parameters +Memory: 32768 KiB +Time cost: 2 +Parallelism: 1 +Salt length: 16 +Hash length: 32 +PASS: independent random salts +PASS: correct password accepted +PASS: incorrect password rejected +PASS: lab6 password hash compatibility +PASS: all Argon2id checks diff --git a/evidence/grade3-argon2-container.txt b/evidence/grade3-argon2-container.txt new file mode 100644 index 00000000..7afbbd73 --- /dev/null +++ b/evidence/grade3-argon2-container.txt @@ -0,0 +1,6 @@ +Argon2id benchmark: 10 iterations per configuration +m=19456 KiB, t=2, p=1: hash=51.58 ms, verify=51.69 ms +m=32768 KiB, t=2, p=1: hash=94.14 ms, verify=98.93 ms +m=65536 KiB, t=3, p=1: hash=267.54 ms, verify=273.54 ms +m=65536 KiB, t=3, p=4: hash=343.41 ms, verify=302.98 ms +PASS: all configurations verified successfully diff --git a/evidence/grade3-argon2-runtime.txt b/evidence/grade3-argon2-runtime.txt new file mode 100644 index 00000000..a05fd5bc --- /dev/null +++ b/evidence/grade3-argon2-runtime.txt @@ -0,0 +1,10 @@ +Algorithm: Argon2id +Memory: 32768 KiB +Iterations: 2 +Parallelism: 1 +Salt: 16 bytes +Hash: 32 bytes +PASS: unique random salts +PASS: correct password accepted +PASS: incorrect password rejected +PASS: ARGON2ID RUNTIME CONFIGURATION diff --git a/evidence/grade3-argon2-wsl.txt b/evidence/grade3-argon2-wsl.txt new file mode 100644 index 00000000..b2d989e4 --- /dev/null +++ b/evidence/grade3-argon2-wsl.txt @@ -0,0 +1,6 @@ +Argon2id benchmark: 10 iterations per configuration +m=19456 KiB, t=2, p=1: hash=54.05 ms, verify=51.09 ms +m=32768 KiB, t=2, p=1: hash=102.60 ms, verify=108.26 ms +m=65536 KiB, t=3, p=1: hash=310.11 ms, verify=334.57 ms +m=65536 KiB, t=3, p=4: hash=113.41 ms, verify=114.69 ms +PASS: all configurations verified successfully diff --git a/evidence/grade3-certificates.txt b/evidence/grade3-certificates.txt new file mode 100644 index 00000000..e43c86b1 --- /dev/null +++ b/evidence/grade3-certificates.txt @@ -0,0 +1,149 @@ +Certificate: certs/services/api-1/tls.crt +subject=CN = api-1 +notBefore=Dec 6 14:05:51 2026 GMT +notAfter=Mar 6 14:05:51 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:api-1, DNS:api.internal +certs/services/api-1/tls.crt: OK + +Certificate: certs/services/api-2/tls.crt +subject=CN = api-2 +notBefore=Dec 6 14:05:51 2026 GMT +notAfter=Mar 6 14:05:51 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:api-2, DNS:api.internal +certs/services/api-2/tls.crt: OK + +Certificate: certs/services/grafana/tls.crt +subject=CN = grafana +notBefore=Dec 6 14:01:27 2026 GMT +notAfter=Mar 6 14:01:27 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:grafana, DNS:localhost, IP Address:127.0.0.1 +certs/services/grafana/tls.crt: OK + +Certificate: certs/services/lb-client/tls.crt +subject=CN = lb-client +notBefore=Dec 6 14:01:19 2026 GMT +notAfter=Mar 6 14:01:19 2027 GMT +X509v3 Extended Key Usage: + TLS Web Client Authentication +X509v3 Subject Alternative Name: + DNS:lb-client +certs/services/lb-client/tls.crt: OK + +Certificate: certs/services/loki/tls.crt +subject=CN = loki +notBefore=Dec 6 14:01:25 2026 GMT +notAfter=Mar 6 14:01:25 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:loki +certs/services/loki/tls.crt: OK + +Certificate: certs/services/nginx/tls.crt +subject=CN = nginx +notBefore=Dec 6 14:01:18 2026 GMT +notAfter=Mar 6 14:01:18 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:localhost, DNS:nginx, IP Address:127.0.0.1 +certs/services/nginx/tls.crt: OK + +Certificate: certs/services/openbao/tls.crt +subject=CN = openbao +notBefore=Dec 6 14:01:26 2026 GMT +notAfter=Mar 6 14:01:26 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:openbao +certs/services/openbao/tls.crt: OK + +Certificate: certs/services/otel-collector/tls.crt +subject=CN = otel-collector +notBefore=Dec 6 14:01:23 2026 GMT +notAfter=Mar 6 14:01:23 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:otel-collector +certs/services/otel-collector/tls.crt: OK + +Certificate: certs/services/postgres/tls.crt +subject=CN = postgres +notBefore=Dec 6 14:01:21 2026 GMT +notAfter=Mar 6 14:01:21 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:postgres +certs/services/postgres/tls.crt: OK + +Certificate: certs/services/prometheus/tls.crt +subject=CN = prometheus +notBefore=Dec 6 14:01:24 2026 GMT +notAfter=Mar 6 14:01:24 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:prometheus +certs/services/prometheus/tls.crt: OK + +Certificate: certs/services/rabbitmq/tls.crt +subject=CN = rabbitmq +notBefore=Dec 6 14:01:22 2026 GMT +notAfter=Mar 6 14:01:22 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:rabbitmq +certs/services/rabbitmq/tls.crt: OK + +Certificate: certs/services/redis/tls.crt +subject=CN = redis +notBefore=Dec 6 14:01:21 2026 GMT +notAfter=Mar 6 14:01:21 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:redis +certs/services/redis/tls.crt: OK + +Certificate: certs/services/s3/tls.crt +subject=CN = s3 +notBefore=Dec 6 14:01:22 2026 GMT +notAfter=Mar 6 14:01:22 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:s3 +certs/services/s3/tls.crt: OK + +Certificate: certs/services/tempo/tls.crt +subject=CN = tempo +notBefore=Dec 6 14:01:26 2026 GMT +notAfter=Mar 6 14:01:26 2027 GMT +X509v3 Extended Key Usage: + TLS Web Server Authentication +X509v3 Subject Alternative Name: + DNS:tempo +certs/services/tempo/tls.crt: OK + +Certificate: certs/services/unauthorized-client/tls.crt +subject=CN = unauthorized-client +notBefore=Dec 6 14:01:28 2026 GMT +notAfter=Mar 6 14:01:28 2027 GMT +X509v3 Extended Key Usage: + TLS Web Client Authentication +X509v3 Subject Alternative Name: + DNS:unauthorized-client +certs/services/unauthorized-client/tls.crt: OK diff --git a/evidence/grade3-clean-bootstrap.txt b/evidence/grade3-clean-bootstrap.txt new file mode 100644 index 00000000..4bf5d0cd --- /dev/null +++ b/evidence/grade3-clean-bootstrap.txt @@ -0,0 +1,127 @@ +...+.+.....+....+...+............+...+.....+............+....+......+.....+.+...+.....+.......+.....+...+....+......+.....+......+...+............+...+...+.......+...+........+.+........+.+............+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.............+.........+...+...+............+.....+...+.+......+..+...+..........+...+...........+.+.........+.....+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+.+.........+.....+............+....+...+........+...+.......+...+..+............+.+......+........................+..+..................+.+.........+..+...............+....+.....+......+.......+...+...+..+.......+..+...+.+..+...+.+......+........+....+...+..+............+.+..+.............+..+............+.+...+.................+.........+....+.....+....+...+..+.+.....+.+...+..+.+........+..........+..+...+.+........+.............+.....+.........+......+.......+..+.............+............+...............+.........+..............+.......+...+......+..............+.....................+....+...........+........................+...+..........+..+................+..+.........+..................................+......+.........+............+..+......+.......+..+...+....+...+..+.........+....+........+...............+............+.+.....+......+..........+.....................+............+..+....+...........+.............+..+...+..........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.......+..+.+.....+.+........+..........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..........+......+...+......+......+......+.....+..................+.......+.....+....+...........+....+...+...+.................+.......+...+.....+......+...............+.+...+......+.....+.......+..+......+.......+............+..+.............+...+....................+..........+.....+............+......+.+........+...+...+.......+.........+...+...+.....+.......+.................+......+.............+..+.......+...+...+...........+.........+......+.+...............+............+.....+..........+..+...+...+.......+...+........+.+......+........+............+.......+...........+......+.+..................+.........+.....+.+......+......+..............................+..+...+...+...........................+...+................+........+.+......+......+...............+...............+...+..+.........+.+........+.+...+........+.............+..+.......+........+....+...+.................+...+.+...........+.+..+.......+........+...+....+......+...+.....+.......+.................+.+.....+....+............+........+......+......+....+.........+........+...+.+..................+........+............+...+...+.......+..+............+...+......+............+...+...................+...+........+..........+...............+............+...+.....+......+..........+.........+.....+.+...+..+...+.......+......+........+......+....+...............+..............+..........+...+........................+......+.....+....+.....+...................+..+............+.+......+...+...+........+.....................+....+...........+..........+.....+.+.....+.................................+.......+..............+.+..+......+.........+.+...........+...+......+....+...+........................+...+..+...................+..+....+....................+...+.+.....+.+.....+...+...+..........+...+.........+..+....+..............+......+.+..............+.......+........+.......+..+............+...+............+.+...+.........+...+..+.................................+............+.......+.........+..+.........+.........+.......+....................+...............+..........+...+..+.........+....+...............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +..+.+..+...+.+...............+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+..........+...........+.+.....+.+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..........+.......+...+..+........................+.........+.........+...+............+.......+..............+.+..............................+...+..+.+...............+...+.........+..+...+...+.........+.....................+...+....+......+.....+......+...+.......+.....+......+....+.........+.........+.....+.......+........+.+.....+....+.....+...+.......+...+...+............+.........+...........+...+.+...........+...+....+..+.+..+..........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +......+...+...............+......+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+............+..............+....+.....+......+.+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = nginx +certs/services/nginx/tls.crt: OK +.+.....+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+.+........+.........+.............+...+...........+...+...+....+.....+.............+......+......+...............+..................+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...........+.+..+..................+.+...........+...+....+.....................+.........+..+.+..+...+....+.....+....+..+..........+...+.........+......+.....+.........+.............+.....+....+.........+.....+......+....+......+...........+....+...+...+..+......+.+...+...+..+......+.......+...+..+..................+.......+.....+.......+..+.+...+..............+......+..........+......+...+...+.........+.....+...+...+.......+...+..+...+....+.....+......+...+....+...+.........+.....+...+.+............+...+.........+..+....+.....+......+...+..........+...........+.+.........+..+.........+...+..........+......+.....+.......+............+...+..+......+.+...........+...+......+.+..................+.........+......+.........+.....+.+......+...........+....+........................+..+...+....+........+.........+....+.....+......+........................+....+...+..+..........+...+..............+.+...+..+...+....+............+...+...+...+.....+..........+..+....+.....+......+...+....+......+..+...+......+..........+.....+...+...+............+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.......+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.+.....+......+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.....+....+...+..+.+............+...+.....+.........+...+.........+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = lb-client +certs/services/lb-client/tls.crt: OK +.....+.+...+..............+..........+...........+......+......+....+.........+.........+........+....+...+.....+.+......+......+...+..+...+.......+.....+....+...+...+........+....+..+......+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+.........+.+.........+...+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+..+............+...+.......+.....+.+...+..+....+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +..........+.....+....+..+....+......+...+.....+.........+.+...........+...+...+....+...+..+.+........+.+..............+.......+..+...+....+..............+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+...+.+.....+.......+...+......+........+...+....+...+......+.........+.....+.+........................+...+........+.+......+........+.......+.....+.......+.....+...........................+...+.+......+.....+...+.+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = api-1 +certs/services/api-1/tls.crt: OK +.........+.+..+.......+......+......+...+...............+..+...+......+......+.+.....+.........+.+.....+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+.....+.+........+......+.......+........+............+..........+..+.......+.........+.........+......+..+....+.....+...+.+.....+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+....+........+.+.....+.......+............+..................+..+.+.........+..+.+............+..+....+.....+.......+..+..........+.....+.+..+..........+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.....+...+......+.+...+..+...+.......+...+......+...+........+...+.+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.....+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...........+.............+..+.............+.....+..........+..+.+..+......+......+..........+...+...........+..........+..............+.+......+........+.......+........+...............+......................+...+...+.....+.......+......+.....................+.....+...+..........+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = api-2 +certs/services/api-2/tls.crt: OK +....+....+...+..+.+..+.......+..+....+.....+....+............+...............+.....+.+.................+...+...+....+...+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+..+.+........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+..................+.+.........+..+.........+.........+.+.....+................+..+..........+...+............+..+....+..+....+...+..+...+......+.+......+.....+............+.............+...+.........+..+..........+...+..+......+...+....+...+...+......+.........+......+........................+...............+..+....+...+........+....+.....+......+............+.+......+...+..+...+......+....+...+.....+...+...............+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +......+...+...........+....+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*......+......+...+.....+.+.....+.+.....+.+.....+..........+..+.......+.........+............+...+.........+......+..+...+....+............+......+...+............+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+..........+...+............+..+.........+.......+..+.......+..............+............+.......+..+...+...+.........+..........+......+...+.....+....+......+.....+.+.....+......+...+.+........+...+..........+...+..+...+....+..+...+..........+..+...+.+.....+....+...+.....+...+.+......+...+......+......+...+..+...+...............+.+...+..+......+.........+.+..+.+......+...+.....+.+..+...+.......+...+...........+....+.....+.+.....+....+..+.........+...+...+...............+...+.......+...+..............+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = postgres +certs/services/postgres/tls.crt: OK +....+..+.+...+.....+......+...............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+......+.....+.......+..+............+...+.+..+............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+.........+............+.......+...+..+.+...........+..........+...+...+..+.+..+...................+......+...+..+...+...............+.+.....+...............+.............+......+.....+.......+...+...............+...........+.+.....+....+...+.....+...+...+..........+...........+......+....+...........+..........+..+...+....+..............+.+.....+......+...................+......+...+..+............+.+..............+.+..+.......+...........+.+.....+.........+.+.....+.........+................+......+.....+...........................+.+.....+.......+..+.+......+.....+...................+......+......+.....+...+.+...+..+.........+......+...+..........+..+...+.......+...+...........+.........+.......+......+.....+..........+........+......+...............+...+.+......+.....+....+......+...........+...+......+...+.+......+......+.........+...........+...+..........+..+...+....+......+......+.....+......+.............+..+..........+..+.......+........+.+..+...+.+.....+................+.....+............+.+..+....+.....+......+....+...+.....+...+.......+...+..+.......+......+.....+.......+..+.+........+....+..+.........+.....................+......+...+.+...........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +..+........................+...+.+..+............................+..+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+.......+...+.....+.+.....+.+...+......+...........+...+......+.............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+................+...+...+...+...........+..........+...+............+.....+.+............+...+....................+...+.+........+...+...+.......+..+......+.+......+............+..+...+.......+..............+............+.........+....+.........+.....+................+......+.....+.+..+...+.......+...........+....+......+..+...............+....+.........+..+....+...+.................+.+..............+.+.....+...+.........+.......+......+..............+.+..+...+.......+.....+.......+........+......+....+..+.+..+...............+.............+.....+....+...+..+.............+............+.....+......+...+....+......+.....+....+...+..+.............+............+.....+..........+...........+....+............+.....+......+....+......+...+...............+.....+...................+..+.+........+..........+...........+...............+.............+.....+.......+...+..+.........+.........+..........+..+.........+.+.........+..+.........+.+...+...........+....+......+...+...+...+..+...+.......+...+.....+......+..........+...........+.......+...+...+..+...+......+.............+......+.....+.+...+...........+....+.....+......................+......+........+.+.....+......+...+....+..+....+...............+..+...+.+......+..+...+....+...+......+......+.....+...+...+.........+...............+.+........+.......+...+.........+......+.....+.......+.........+...+..+.+..................+.....+......+.+........+.+.....+.+...............+.....+............+......+....+...+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = redis +certs/services/redis/tls.crt: OK +.+.......+........+.+..+...............+.............+...........+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...................+..+....+.........+.....+...+............+.......+...+...+.........+........+.+..+............+...+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+...+....+...+........+...+....+...+...+...........+..........+...+..+.+..+.............+...+...........+.+.....+....+..................+.....+.......+.....+.........+.+.........+..+..........+..+...+...+....+...+..............+....+..+.........+..........+......+...+.....+.........+.+..............+.+..+...+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.....+...+................+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+......+..+...+....+..+.+..+...+..................+.......+........+.+........+.......+......+..+...+.......+........+....+.................................+.....+.+.....+.+...+...............+..+..........+.....+...+...+.......+...+.........+......+...+.....+.......+..+.+..+...................+...+...............+...+........+............+..................+.+.....+......+.......+....................+.+.....+..........+.....+.+.........+.....+.+....................+.+.....+.......+........+...+......+.............+..+..........+...+...+..+.+..+........................+.+...+..+...............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = rabbitmq +certs/services/rabbitmq/tls.crt: OK +...+...+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.....+...+..........+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+.......+..............+....+...........................+........+.+..+....+...........+...+.+...+............+.........+..+...+......+.........+.+.....+.+...+..........................+..........+...+...............+...+..+......+.+...........+.......+.................+.........+....+..+.+...+......+...+..+....+.........+............+.....+.+........+............+....+...+........+...+.+...........+.........+....+.............................+......+....+.....+......+.......+........+.+.....+.........+....+......+.........+..+.+..+.+..............+.+..+.............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.....+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.........+...+.+...............+..+.........+.............+..+.+...+..+..........+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.........+...+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = otel-collector +certs/services/otel-collector/tls.crt: OK +.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.....+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.....+.......+..+....+.....+......+...+.+......+...+......+..+...+....+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+...........+.+.....+.......+..+.+........+.+...+...........+....+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+...+....+...+.....+.......+......+..+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = prometheus +certs/services/prometheus/tls.crt: OK +......+.....+......+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+......+....+.........+..+..........+...+..+......+............+.+.........+......+..+.......+...........+....+..+.+..............+...+.+......+...+...+..+...+..........+...+..+.......+..+.+.....+.......+..+...+...+.......+...+...+.........+..+..........+...........+....+........+......+....+..................+...+..+.........+...+.+.....+.........+...+...+.+.....+.+...+............+...+.....................+...+..+......+.......+..+..........+...+.....+.+..+...+....+...........+..........+.....+.+......+...+.........+...+..+......+......+...............+.+...+......+...+.....+..........+........+....+......+..+............+...+...+....+...........+....+.........+..+.......+...+.........+...+..+.........+....+...........+...............+...................+...+.............................+.+............+..+...+......+.+.........+.....+.+......+........+.+.....+.+.........+......+..+.............+...+.........+........+....+.....+..................+..........+......+............+..+...+....+.....+.+..+..........+...+........+......+....+..+.........................+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +........+.+...+.....+...............+......+....+..+.......+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..........+..+....+.....+.......+...+.........+.....+..........+......+......+...+...........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*............+....................+....+......+........+.........+.+.........+.....+.............+...+..+.......+...+..+.+...........+...+......+.+...+...............+..+.+.....+..........+..+.+..+...................+......+.....+....+...+...+..+......+......+.+..+......+........................................+..+.......+..+....+..+...+.......+........+.+...+.......................+....+......+....................+.........+.+..+..........+...............+...+...+..+...+.+.....+...+............+....+..+...+....+.....+...+....+.....+....+.....+.........+..........+.....+.+.....+....+.....+.+.....+.+...+..................+..+...+...+....+...+..+............+......+.........+...+.......+...+......+..+...+.........+.+......+...+.................+......+....+...+...+..+...+.......+..+......+...+......+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = loki +certs/services/loki/tls.crt: OK +.....+.....+......+.+..+......+.+......+...+............+..+..........+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+.....................+......+........+.+......+...+..+...............+...+.+..+...+.......+.....+...............+.......+.....+.+..+....+...+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+....+..+.......+..+...+...+....+...+..+......+.........+.+..+.+.........+.....+...+...+...............+.......+........+......+.+.........+......+.....+.........+.........+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.+...+.........+...+...+.............+.....+......+...+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+...+.+......+.....+.+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+...+.+...+............+.....+...+...+...+....+..+.+..+................+..+.........+....+..+....+.....+....+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = tempo +certs/services/tempo/tls.crt: OK +.......+.........+......+..+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+.......+..+....+......+...+...............+......+..+...+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+...+...........+....+..+....+...+.....+.+......+...+...+.................+......+.......+........+.+.....+......+...+.+...+...+.....+.........+.....................+...+.+....................+..........+.....+....+..+.......+.....+...+.......+..+.+............+......+....................+.+..................+...........+.........+.......+...+..+......+....+......+...+.........+..+.+..+.+..+.........+......+....+...+......+..+...+....+...+........+.........+...+.......+..+.+.........+.........+............+..+...+.......+.....+......+.+...+...........+........................+.+.........+........+...+......+.............+..+.+.....+.......+.....+.+............+...+............+........+.......+........+.....................+......+..........+.....+.............+.....+..........+.........+...+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +....+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.......+...+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+......................+...........+...+.+...........+...+.........+...+.........+....+......+.........+..+.........+.+...+......+.........+.....+......+......+..........+........+.......+..+......................+...+.....+...+.......+..+.+...............+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = openbao +certs/services/openbao/tls.crt: OK +.+......+....+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+........+...+...+.+..............+.+...+..+....+...........+.+...+..+...+....+...........+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+.+......+...+.....+.+......+.....+......+.......+.....+......+.+.........+.........+...+..+.+..+.......+.....+.......+........+.......+...+..................+........+....+.....................+.....+................+...........+.......+......+......+..............+...................+..+.........+.......+.....+.........+.+.....+....+.....+....+.....+.+......+............+...+.................+.+.....+.+.....+...+...+.......+.....................+..+.........+......+...+....+........+...+....+......+............+...+..+....+...........+...+......+.+........+......+...............+......+......................+...........+......+......+....+......+.........+...+........+...+.......+..+.+..+.........+.........+.+.........+..............+......+.......+..+......+....+...+.........+..................+..+...+............+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +........+....+..+.............+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+...+.+......+.....+......+.........+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+.+.....+.+.....+...+............+.......+.....+.......+...+.....+.+......+.....+...............+....+.....+.+........+...+....+..............+......+......+....+...+......+..+.............+.....+..........+...............+.....+....+.....+..........+...+...............+.....+....+.....+...+.......+...+........+...+...............+.+......+.........+..................+........+.........+...............+....+.........+...+..................+......+......+...+............+..+......+..........+.....+.......+...+.........+..+...+...+..........+...+............+..+.............+.....+...+......+...............+.+...+..............+.+..+...........................+.......+...+..+...+.+.....+.......+..+............+.+..+................+............+..+................+..+....+........+......+......+.+.........+.....+.+.....+....+......+.........+...+...+.....+.......+..+......+....+.....+...+..................+....+...+...+..+.+.....+..........+.....+.+.....+.........+...............+.......+............+.....+.+..+..........+...+..+.......+..+.+..+............+....+.........+..+......+...........................+.......+.....+......+...+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = s3 +certs/services/s3/tls.crt: OK +....+.+......+.....+...+....+...........+.+...+..+......+.........+.+..+.+...............+.....+.+.........+...........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+.....+.+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+..+......+...+.........+.......+...+..+.+........+..........+..+...+....+.....+...+...............+.......+..+.+..............+.........+....+...+.....+..........+..............+......+...............+.......+......+...........+......+............+.......+......+..+......+.+...+..+.+...+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +...+...+..............+..................+.+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+...+..+...+..........+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.....+......+.........+..+......+...............+...+.+...+......+.....+.+...+..+.+.........+......+.....+...+.......+..+...+.......+...+............+.................+..........+......+...+.....+.........+.+.....+......+.+...+..+.......+..+...+...+...+.+......+..................+..+....+...+..+....+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = grafana +certs/services/grafana/tls.crt: OK +.......+..+.+..+...+....+.....+...+...+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.+.......+...+..+......+.........+.+.................+...+...+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+......+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+.........+..+....+.....+...+......+....+..+.+.....+.......+..+......+....+........+......+.........+.+...............+............+.....+.......+...+..+.......+......+...............+.....+....+...+.....+.+..+...+..........+......+........+.+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = unauthorized-client +certs/services/unauthorized-client/tls.crt: OK +.+......+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..........+.....+...+....+......+..+.+...........+...+......+......+................+..+............+.+........+....+........+............+.+......+...+...+.................+.+.....+.........+...+...+.+.....+...................+..+...+....+...............+........+..........+..+.+..+...+......+.....................+..........+..+...+....+......+...+...........+..................+.+..+..........+.....+...+.+...+.....+......+.......+...+......+...+..+.............+...+...+.....+......+.+...+..............+......+.........+.......+.....+...+......+.+.....+....+.....+.+......+..+...+..................+.......+..+.+.........+.....+.......+...+......+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +..+..........+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*......+..+.......+..+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+..........+...+.....+.+...+......+.....+......+.........+......................+.....+.......+......+......+.....+......+.......+.....+...+..................+.+...........+...+....+.....+...+.........+.+........+.......+..+...............+..........+......+............+...............+.....+....+...+.....+......+....+..+.........................+...+.....+.+......+......+........+....+.................+.+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = bao-api-1 +certs/services/bao-api-1/tls.crt: OK +.+...........+...+.+...+..+....+..+...+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+...+.+..............+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.........+..+.+............+..+.+............+........+.+.....+................+............+...+..+.......+........+...+............+.+.........+......+...........+......+...+......+...+...+....+...+...+........+....+..+..........+...+..+....+..+....+........+.+...........+...+......................+.....+..........+......+............+............+........+...+...+....+.....+..........+......+......+......+.....+.......+...+............+..+....+.....+......+.............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.....+....+...+........+..................+.......+........+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+........+...+...+.+.....+...+.+.....+.+........+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.......+.........+.+.....+...+............+.+........+......+......+....+.........+..+...+.+.........+..+...+...............+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = bao-api-2 +certs/services/bao-api-2/tls.crt: OK +...+......+.......+...+.....+.......+..+......................+...+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+.......+......+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.....+....+........+.+..............+.......+......+..+.......+.....+...............+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.+.+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..............+......+....+..+.......+.....+...+.......+......+..+...+.+...+......+......+..............+.+......+.....+..........+.....+...+......+.+..................+.........+.....+.............+...+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = bao-worker +certs/services/bao-worker/tls.crt: OK +.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+.....+...+.+....................+......+.+...............+.....+.............+......+...+.....+.+..+.......+..+.+..+......+.+......+..+......+.+..............+.+...+..+.........+....+...............+..+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...........+..........+.....+....+.................+..........+.........+......+..+.+..+....+...+.................+.+.....+.......+..+....+..............+.+.....+.+........+.+..+...+.........+.............+.....+...+......+...+......+.+.....+.............+..+......+....+...+...........+.+......+...+..+....+...+............+......+..+.+..+.........+.+........+.+..............+.........+.+..+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +............+.....+...+......+.+............+..+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+...............+.....+.......+.....+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+....+.....+.+...........+....+.....+.+...........+....+.....+.+........+....+........+..........+..+...+............+......+.+......+............+..+.+..+......+.+..........................+...+....+.................+.+..+.+..+.............+......+...+........+.............+..............+.+..+...+.+.....................+............+..+.+.........+...+...........+....+...+...+..+...+...............+.......+...+......+.....+.+..+..................+...+......+...+.......+...+...........+.+........+...+....+...+.....+.+......+.....+...+.+...........+.+..............+.+...+...........+.+..+.......+........+.+..+...+.........+.+..+....+........+......+......+...+.+............+.....+....+...+..+......+..........+...+......+...+........+...+.+......+...+..+.............+...............+.....+....+..+.........+.+.....+.............+.....+.+..+....+...+........+...+...............+.+......+.........+........+.+......+........+...+.........+.+.....+...+...................+.....+.+............+.....+...+......+.+...+......+........+.......+...........+...+.+.....+......+..........+.....+....+.........+.....+....+...+...+..+.......+...+.........+......+...+.........+..+...................+..+.............+......+........+...+...+....+.....+...+....+...+..+...+.......+......+..+...+...+.+...+...+.......................+......+....+..............+.....................+.+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +Certificate request self-signature ok +subject=CN = bao-dispatcher +certs/services/bao-dispatcher/tls.crt: OK +PASS: local PKI generated +PASS: mTLS identity configuration generated +PASS: postgres TLS permissions configured +PASS: redis TLS permissions configured +PASS: rabbitmq TLS permissions configured +PASS: otel-collector TLS permissions configured +PASS: loki TLS permissions configured +PASS: tempo TLS permissions configured +PASS: grafana TLS permissions configured +PASS: prometheus TLS permissions configured +PASS: bao-api-1 TLS permissions configured +PASS: bao-api-2 TLS permissions configured +PASS: bao-worker TLS permissions configured +PASS: bao-dispatcher TLS permissions configured +PASS: openbao TLS permissions configured +PASS: runtime TLS permissions prepared +PASS: PostgreSQL and Redis credentials generated +PASS: separate S3 and RabbitMQ credentials generated +PASS: otel_api_password prepared +PASS: otel_worker_password prepared +PASS: otel_dispatcher_password prepared +PASS: prometheus_scrape_password prepared +PASS: grafana_datasource_password prepared +PASS: otel_backend_password prepared +PASS: Collector authentication file prepared +PASS: backend authentication files prepared +PASS: Collector backend authorization prepared +PASS: Prometheus scrape authentication prepared +PASS: Prometheus HTTPS web configuration prepared +PASS: Grafana HTTPS datasources prepared diff --git a/evidence/grade3-clean-build.txt b/evidence/grade3-clean-build.txt new file mode 100644 index 00000000..047e79fa --- /dev/null +++ b/evidence/grade3-clean-build.txt @@ -0,0 +1,375 @@ + Image lab7verify-api-1 Building + Image lab7verify-migrate Building + Image lab7verify-worker Building + Image lab7verify-api-2 Building + Image lab7verify-dispatcher Building +#1 [internal] load local bake definitions +#1 reading from stdin 2.50kB done +#1 DONE 0.0s + +#2 [migrate internal] load build definition from Dockerfile +#2 transferring dockerfile: 660B 0.0s done +#2 DONE 0.1s + +#3 [dispatcher internal] load metadata for docker.io/library/python:3.13.15-slim +#3 DONE 2.5s + +#4 [api-2 internal] load .dockerignore +#4 transferring context: 293B 0.0s done +#4 DONE 0.1s + +#5 [api-2 1/10] FROM docker.io/library/python:3.13.15-slim@sha256:7c61056e61ac89e852de05f3dc6fa51a6dd2181797bceed46aa725dd7cb2cd3b +#5 resolve docker.io/library/python:3.13.15-slim@sha256:7c61056e61ac89e852de05f3dc6fa51a6dd2181797bceed46aa725dd7cb2cd3b 0.1s done +#5 DONE 0.1s + +#6 [migrate internal] load build context +#6 transferring context: 316.48kB 0.0s done +#6 DONE 0.1s + +#7 [migrate 2/10] WORKDIR /app +#7 CACHED + +#8 [dispatcher 3/10] COPY requirements.txt . +#8 DONE 0.1s + +#9 [dispatcher 4/10] RUN pip install --no-cache-dir -r requirements.txt +#9 6.204 Collecting annotated-doc==0.0.5 (from -r requirements.txt (line 1)) +#9 6.718 Downloading annotated_doc-0.0.5-py3-none-any.whl.metadata (6.5 kB) +#9 6.880 Collecting annotated-types==0.8.0 (from -r requirements.txt (line 2)) +#9 6.988 Downloading annotated_types-0.8.0-py3-none-any.whl.metadata (15 kB) +#9 7.150 Collecting anyio==4.15.1 (from -r requirements.txt (line 3)) +#9 7.249 Downloading anyio-4.15.1-py3-none-any.whl.metadata (4.7 kB) +#9 7.391 Collecting click==8.5.0 (from -r requirements.txt (line 4)) +#9 7.489 Downloading click-8.5.0-py3-none-any.whl.metadata (2.6 kB) +#9 7.770 Collecting fastapi==0.141.1 (from -r requirements.txt (line 5)) +#9 7.867 Downloading fastapi-0.141.1-py3-none-any.whl.metadata (27 kB) +#9 8.018 Collecting h11==0.16.0 (from -r requirements.txt (line 6)) +#9 8.118 Downloading h11-0.16.0-py3-none-any.whl.metadata (8.3 kB) +#9 8.242 Collecting idna==3.20 (from -r requirements.txt (line 7)) +#9 8.349 Downloading idna-3.20-py3-none-any.whl.metadata (7.2 kB) +#9 8.806 Collecting pydantic==2.13.5 (from -r requirements.txt (line 8)) +#9 8.911 Downloading pydantic-2.13.5-py3-none-any.whl.metadata (110 kB) +#9 11.02 Collecting pydantic_core==2.46.5 (from -r requirements.txt (line 9)) +#9 11.14 Downloading pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.6 kB) +#9 11.32 Collecting starlette==1.7.0 (from -r requirements.txt (line 10)) +#9 11.42 Downloading starlette-1.7.0-py3-none-any.whl.metadata (6.6 kB) +#9 11.53 Collecting typing-inspection==0.4.4 (from -r requirements.txt (line 11)) +#9 11.62 Downloading typing_inspection-0.4.4-py3-none-any.whl.metadata (2.6 kB) +#9 11.74 Collecting typing_extensions==4.16.0 (from -r requirements.txt (line 12)) +#9 11.84 Downloading typing_extensions-4.16.0-py3-none-any.whl.metadata (3.3 kB) +#9 12.00 Collecting uvicorn==0.53.0 (from -r requirements.txt (line 13)) +#9 12.11 Downloading uvicorn-0.53.0-py3-none-any.whl.metadata (6.6 kB) +#9 13.15 Collecting SQLAlchemy==2.1.4 (from -r requirements.txt (line 14)) +#9 13.25 Downloading sqlalchemy-2.1.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (9.7 kB) +#9 13.57 Collecting asyncpg==0.32.0 (from -r requirements.txt (line 15)) +#9 13.67 Downloading asyncpg-0.32.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (4.4 kB) +#9 13.82 Collecting alembic==1.20.0 (from -r requirements.txt (line 16)) +#9 13.93 Downloading alembic-1.20.0-py3-none-any.whl.metadata (7.3 kB) +#9 14.58 Collecting greenlet==3.5.6 (from -r requirements.txt (line 17)) +#9 14.68 Downloading greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.metadata (3.8 kB) +#9 14.82 Collecting argon2-cffi==25.1.0 (from -r requirements.txt (line 18)) +#9 14.92 Downloading argon2_cffi-25.1.0-py3-none-any.whl.metadata (4.1 kB) +#9 15.10 Collecting redis==7.0.1 (from -r requirements.txt (line 19)) +#9 15.22 Downloading redis-7.0.1-py3-none-any.whl.metadata (12 kB) +#9 15.93 Collecting boto3==1.43.120 (from -r requirements.txt (line 20)) +#9 16.03 Downloading boto3-1.43.120-py3-none-any.whl.metadata (6.6 kB) +#9 16.66 Collecting Pillow==13.0.0 (from -r requirements.txt (line 21)) +#9 16.76 Downloading pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (9.1 kB) +#9 16.90 Collecting python-multipart==0.0.32 (from -r requirements.txt (line 22)) +#9 17.01 Downloading python_multipart-0.0.32-py3-none-any.whl.metadata (2.1 kB) +#9 17.12 Collecting pika==1.3.2 (from -r requirements.txt (line 23)) +#9 17.22 Downloading pika-1.3.2-py3-none-any.whl.metadata (13 kB) +#9 17.38 Collecting opentelemetry-api==1.45.2 (from -r requirements.txt (line 24)) +#9 17.49 Downloading opentelemetry_api-1.45.2-py3-none-any.whl.metadata (1.4 kB) +#9 17.62 Collecting opentelemetry-sdk==1.45.2 (from -r requirements.txt (line 25)) +#9 17.72 Downloading opentelemetry_sdk-1.45.2-py3-none-any.whl.metadata (1.6 kB) +#9 17.85 Collecting opentelemetry-exporter-otlp-proto-http==1.45.2 (from -r requirements.txt (line 26)) +#9 17.95 Downloading opentelemetry_exporter_otlp_proto_http-1.45.2-py3-none-any.whl.metadata (3.0 kB) +#9 18.12 Collecting opentelemetry-instrumentation-fastapi==0.66b2 (from -r requirements.txt (line 27)) +#9 18.22 Downloading opentelemetry_instrumentation_fastapi-0.66b2-py3-none-any.whl.metadata (2.2 kB) +#9 18.35 Collecting opentelemetry-instrumentation-asgi==0.66b2 (from -r requirements.txt (line 28)) +#9 18.45 Downloading opentelemetry_instrumentation_asgi-0.66b2-py3-none-any.whl.metadata (2.0 kB) +#9 18.65 Collecting opentelemetry-instrumentation-logging==0.66b2 (from -r requirements.txt (line 29)) +#9 18.75 Downloading opentelemetry_instrumentation_logging-0.66b2-py3-none-any.whl.metadata (1.9 kB) +#9 18.93 Collecting opentelemetry-instrumentation-botocore==0.66b2 (from -r requirements.txt (line 30)) +#9 19.02 Downloading opentelemetry_instrumentation_botocore-0.66b2-py3-none-any.whl.metadata (3.3 kB) +#9 19.14 Collecting opentelemetry-instrumentation-pika==0.66b2 (from -r requirements.txt (line 31)) +#9 19.24 Downloading opentelemetry_instrumentation_pika-0.66b2-py3-none-any.whl.metadata (1.9 kB) +#9 19.36 Collecting opentelemetry-semantic-conventions==0.66b2 (from -r requirements.txt (line 32)) +#9 19.57 Downloading opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl.metadata (2.4 kB) +#9 19.70 Collecting openapi-spec-validator==0.7.2 (from -r requirements.txt (line 34)) +#9 19.80 Downloading openapi_spec_validator-0.7.2-py3-none-any.whl.metadata (5.7 kB) +#9 20.01 Collecting Mako (from alembic==1.20.0->-r requirements.txt (line 16)) +#9 20.10 Downloading mako-1.4.3-py3-none-any.whl.metadata (2.9 kB) +#9 20.23 Collecting argon2-cffi-bindings (from argon2-cffi==25.1.0->-r requirements.txt (line 18)) +#9 20.33 Downloading argon2_cffi_bindings-26.2.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl.metadata (7.6 kB) +#9 21.06 Collecting botocore<1.44.0,>=1.43.120 (from boto3==1.43.120->-r requirements.txt (line 20)) +#9 21.18 Downloading botocore-1.43.127-py3-none-any.whl.metadata (5.6 kB) +#9 21.32 Collecting jmespath<2.0.0,>=0.7.1 (from boto3==1.43.120->-r requirements.txt (line 20)) +#9 21.41 Downloading jmespath-1.1.0-py3-none-any.whl.metadata (7.6 kB) +#9 21.54 Collecting s3transfer<0.20.0,>=0.19.0 (from boto3==1.43.120->-r requirements.txt (line 20)) +#9 21.63 Downloading s3transfer-0.19.3-py3-none-any.whl.metadata (1.7 kB) +#9 21.78 Collecting googleapis-common-protos~=1.52 (from opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 21.88 Downloading googleapis_common_protos-1.76.0-py3-none-any.whl.metadata (8.5 kB) +#9 22.00 Collecting opentelemetry-exporter-http-transport==0.66b2 (from opentelemetry-exporter-http-transport[requests]==0.66b2->opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 22.11 Downloading opentelemetry_exporter_http_transport-0.66b2-py3-none-any.whl.metadata (2.3 kB) +#9 22.22 Collecting opentelemetry-exporter-otlp-common==0.66b2 (from opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 22.31 Downloading opentelemetry_exporter_otlp_common-0.66b2-py3-none-any.whl.metadata (1.9 kB) +#9 22.43 Collecting opentelemetry-exporter-otlp-proto-common==1.45.2 (from opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 22.53 Downloading opentelemetry_exporter_otlp_proto_common-1.45.2-py3-none-any.whl.metadata (1.8 kB) +#9 22.68 Collecting opentelemetry-proto==1.45.2 (from opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 22.79 Downloading opentelemetry_proto-1.45.2-py3-none-any.whl.metadata (2.3 kB) +#9 22.93 Collecting requests~=2.7 (from opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 23.02 Downloading requests-2.34.2-py3-none-any.whl.metadata (4.8 kB) +#9 23.16 Collecting opentelemetry-instrumentation==0.66b2 (from opentelemetry-instrumentation-fastapi==0.66b2->-r requirements.txt (line 27)) +#9 23.26 Downloading opentelemetry_instrumentation-0.66b2-py3-none-any.whl.metadata (7.2 kB) +#9 23.41 Collecting opentelemetry-util-http==0.66b2 (from opentelemetry-instrumentation-fastapi==0.66b2->-r requirements.txt (line 27)) +#9 23.51 Downloading opentelemetry_util_http-0.66b2-py3-none-any.whl.metadata (2.6 kB) +#9 23.63 Collecting asgiref~=3.0 (from opentelemetry-instrumentation-asgi==0.66b2->-r requirements.txt (line 28)) +#9 23.73 Downloading asgiref-3.13.0-py3-none-any.whl.metadata (12 kB) +#9 23.85 Collecting opentelemetry-propagator-aws-xray~=1.0 (from opentelemetry-instrumentation-botocore==0.66b2->-r requirements.txt (line 30)) +#9 23.98 Downloading opentelemetry_propagator_aws_xray-1.0.2-py3-none-any.whl.metadata (2.5 kB) +#9 25.39 Collecting wrapt<3.0.0,>=1.0.0 (from opentelemetry-instrumentation-botocore==0.66b2->-r requirements.txt (line 30)) +#9 25.50 Downloading wrapt-2.5.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl.metadata (7.6 kB) +#9 25.64 Collecting packaging>=20.0 (from opentelemetry-instrumentation-pika==0.66b2->-r requirements.txt (line 31)) +#9 25.74 Downloading packaging-26.4-py3-none-any.whl.metadata (3.5 kB) +#9 25.93 Collecting jsonschema<5.0.0,>=4.18.0 (from openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 26.04 Downloading jsonschema-4.26.0-py3-none-any.whl.metadata (7.6 kB) +#9 26.17 Collecting jsonschema-path<0.4.0,>=0.3.1 (from openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 26.30 Downloading jsonschema_path-0.3.4-py3-none-any.whl.metadata (4.3 kB) +#9 26.59 Collecting lazy-object-proxy<2.0.0,>=1.7.1 (from openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 26.69 Downloading lazy_object_proxy-1.13.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl.metadata (5.1 kB) +#9 26.81 Collecting openapi-schema-validator<0.7.0,>=0.6.0 (from openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 26.93 Downloading openapi_schema_validator-0.6.3-py3-none-any.whl.metadata (5.4 kB) +#9 27.52 Collecting protobuf<8.0,>=5.0 (from opentelemetry-proto==1.45.2->opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 27.62 Downloading protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl.metadata (595 bytes) +#9 27.76 Collecting python-dateutil<3.0.0,>=2.1 (from botocore<1.44.0,>=1.43.120->boto3==1.43.120->-r requirements.txt (line 20)) +#9 27.86 Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl.metadata (8.4 kB) +#9 28.02 Collecting urllib3!=2.2.0,<3,>=1.25.4 (from botocore<1.44.0,>=1.43.120->boto3==1.43.120->-r requirements.txt (line 20)) +#9 28.13 Downloading urllib3-2.8.0-py3-none-any.whl.metadata (7.4 kB) +#9 28.30 Collecting attrs>=22.2.0 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 28.40 Downloading attrs-26.1.0-py3-none-any.whl.metadata (8.8 kB) +#9 28.62 Collecting jsonschema-specifications>=2023.03.6 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 28.71 Downloading jsonschema_specifications-2025.9.1-py3-none-any.whl.metadata (2.9 kB) +#9 28.87 Collecting referencing>=0.28.4 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 28.97 Downloading referencing-0.37.0-py3-none-any.whl.metadata (2.8 kB) +#9 29.93 Collecting rpds-py>=0.25.0 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 30.05 Downloading rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.1 kB) +#9 30.31 Collecting PyYAML>=5.1 (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 30.41 Downloading pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (2.3 kB) +#9 30.52 Collecting pathable<0.5.0,>=0.4.1 (from jsonschema-path<0.4.0,>=0.3.1->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 30.63 Downloading pathable-0.4.4-py3-none-any.whl.metadata (1.8 kB) +#9 30.66 Collecting referencing>=0.28.4 (from jsonschema<5.0.0,>=4.18.0->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 30.76 Downloading referencing-0.36.2-py3-none-any.whl.metadata (2.8 kB) +#9 30.89 Collecting rfc3339-validator (from openapi-schema-validator<0.7.0,>=0.6.0->openapi-spec-validator==0.7.2->-r requirements.txt (line 34)) +#9 30.99 Downloading rfc3339_validator-0.1.4-py2.py3-none-any.whl.metadata (1.5 kB) +#9 31.13 Collecting six>=1.5 (from python-dateutil<3.0.0,>=2.1->botocore<1.44.0,>=1.43.120->boto3==1.43.120->-r requirements.txt (line 20)) +#9 31.23 Downloading six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB) +#9 31.78 Collecting charset_normalizer<4,>=2 (from requests~=2.7->opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 31.88 Downloading charset_normalizer-3.5.3-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl.metadata (43 kB) +#9 32.06 Collecting certifi>=2023.5.7 (from requests~=2.7->opentelemetry-exporter-otlp-proto-http==1.45.2->-r requirements.txt (line 26)) +#9 32.19 Downloading certifi-2026.11.20-py3-none-any.whl.metadata (2.5 kB) +#9 32.72 Collecting cffi>=1.0.1 (from argon2-cffi-bindings->argon2-cffi==25.1.0->-r requirements.txt (line 18)) +#9 32.90 Downloading cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (2.5 kB) +#9 33.10 Collecting pycparser (from cffi>=1.0.1->argon2-cffi-bindings->argon2-cffi==25.1.0->-r requirements.txt (line 18)) +#9 33.29 Downloading pycparser-3.12-py3-none-any.whl.metadata (9.7 kB) +#9 33.68 Collecting MarkupSafe>=2.0 (from Mako->alembic==1.20.0->-r requirements.txt (line 16)) +#9 33.82 Downloading markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (2.7 kB) +#9 34.01 Downloading annotated_doc-0.0.5-py3-none-any.whl (5.3 kB) +#9 34.11 Downloading annotated_types-0.8.0-py3-none-any.whl (13 kB) +#9 34.31 Downloading anyio-4.15.1-py3-none-any.whl (132 kB) +#9 34.52 Downloading click-8.5.0-py3-none-any.whl (125 kB) +#9 34.86 Downloading fastapi-0.141.1-py3-none-any.whl (131 kB) +#9 35.06 Downloading h11-0.16.0-py3-none-any.whl (37 kB) +#9 35.26 Downloading idna-3.20-py3-none-any.whl (69 kB) +#9 35.48 Downloading pydantic-2.13.5-py3-none-any.whl (472 kB) +#9 36.03 Downloading pydantic_core-2.46.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB) +#9 36.27 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 11.4 MB/s 0:00:00 +#9 36.36 Downloading starlette-1.7.0-py3-none-any.whl (78 kB) +#9 36.47 Downloading typing_inspection-0.4.4-py3-none-any.whl (14 kB) +#9 36.56 Downloading typing_extensions-4.16.0-py3-none-any.whl (45 kB) +#9 36.71 Downloading uvicorn-0.53.0-py3-none-any.whl (87 kB) +#9 36.82 Downloading sqlalchemy-2.1.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (4.6 MB) +#9 37.24 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.6/4.6 MB 13.7 MB/s 0:00:00 +#9 37.34 Downloading asyncpg-0.32.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (3.8 MB) +#9 37.71 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.8/3.8 MB 13.0 MB/s 0:00:00 +#9 37.81 Downloading alembic-1.20.0-py3-none-any.whl (268 kB) +#9 37.92 Downloading greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (623 kB) +#9 38.00 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 623.8/623.8 kB 12.3 MB/s 0:00:00 +#9 38.09 Downloading argon2_cffi-25.1.0-py3-none-any.whl (14 kB) +#9 38.18 Downloading redis-7.0.1-py3-none-any.whl (339 kB) +#9 38.33 Downloading boto3-1.43.120-py3-none-any.whl (140 kB) +#9 38.51 Downloading pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (7.1 MB) +#9 39.05 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 7.1/7.1 MB 15.9 MB/s 0:00:00 +#9 39.14 Downloading python_multipart-0.0.32-py3-none-any.whl (30 kB) +#9 39.23 Downloading pika-1.3.2-py3-none-any.whl (155 kB) +#9 39.35 Downloading opentelemetry_api-1.45.2-py3-none-any.whl (60 kB) +#9 39.47 Downloading opentelemetry_sdk-1.45.2-py3-none-any.whl (141 kB) +#9 39.62 Downloading opentelemetry_exporter_otlp_proto_http-1.45.2-py3-none-any.whl (22 kB) +#9 39.72 Downloading opentelemetry_instrumentation_fastapi-0.66b2-py3-none-any.whl (14 kB) +#9 39.82 Downloading opentelemetry_instrumentation_asgi-0.66b2-py3-none-any.whl (15 kB) +#9 39.91 Downloading opentelemetry_instrumentation_logging-0.66b2-py3-none-any.whl (15 kB) +#9 40.01 Downloading opentelemetry_instrumentation_botocore-0.66b2-py3-none-any.whl (36 kB) +#9 40.13 Downloading opentelemetry_instrumentation_pika-0.66b2-py3-none-any.whl (12 kB) +#9 40.22 Downloading opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl (206 kB) +#9 40.37 Downloading openapi_spec_validator-0.7.2-py3-none-any.whl (39 kB) +#9 40.49 Downloading opentelemetry_exporter_http_transport-0.66b2-py3-none-any.whl (12 kB) +#9 40.59 Downloading opentelemetry_exporter_otlp_common-0.66b2-py3-none-any.whl (12 kB) +#9 40.71 Downloading opentelemetry_exporter_otlp_proto_common-1.45.2-py3-none-any.whl (15 kB) +#9 40.82 Downloading opentelemetry_instrumentation-0.66b2-py3-none-any.whl (36 kB) +#9 40.92 Downloading opentelemetry_proto-1.45.2-py3-none-any.whl (72 kB) +#9 41.03 Downloading opentelemetry_util_http-0.66b2-py3-none-any.whl (8.4 kB) +#9 41.12 Downloading asgiref-3.13.0-py3-none-any.whl (27 kB) +#9 41.23 Downloading botocore-1.43.127-py3-none-any.whl (16.3 MB) +#9 42.29 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 16.3/16.3 MB 16.6 MB/s 0:00:01 +#9 42.38 Downloading googleapis_common_protos-1.76.0-py3-none-any.whl (307 kB) +#9 42.52 Downloading jmespath-1.1.0-py3-none-any.whl (20 kB) +#9 42.62 Downloading jsonschema-4.26.0-py3-none-any.whl (90 kB) +#9 42.73 Downloading jsonschema_path-0.3.4-py3-none-any.whl (14 kB) +#9 42.83 Downloading lazy_object_proxy-1.13.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl (71 kB) +#9 42.93 Downloading openapi_schema_validator-0.6.3-py3-none-any.whl (8.8 kB) +#9 43.02 Downloading opentelemetry_propagator_aws_xray-1.0.2-py3-none-any.whl (10 kB) +#9 43.12 Downloading pathable-0.4.4-py3-none-any.whl (9.6 kB) +#9 43.22 Downloading protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl (343 kB) +#9 43.37 Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB) +#9 43.53 Downloading referencing-0.36.2-py3-none-any.whl (26 kB) +#9 43.64 Downloading requests-2.34.2-py3-none-any.whl (73 kB) +#9 43.79 Downloading charset_normalizer-3.5.3-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl (256 kB) +#9 43.94 Downloading s3transfer-0.19.3-py3-none-any.whl (90 kB) +#9 44.06 Downloading urllib3-2.8.0-py3-none-any.whl (135 kB) +#9 44.21 Downloading wrapt-2.5.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl (248 kB) +#9 44.33 Downloading attrs-26.1.0-py3-none-any.whl (67 kB) +#9 44.45 Downloading certifi-2026.11.20-py3-none-any.whl (127 kB) +#9 44.61 Downloading jsonschema_specifications-2025.9.1-py3-none-any.whl (18 kB) +#9 44.71 Downloading packaging-26.4-py3-none-any.whl (140 kB) +#9 44.83 Downloading pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (838 kB) +#9 44.95 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 838.5/838.5 kB 19.7 MB/s 0:00:00 +#9 45.05 Downloading rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (370 kB) +#9 45.19 Downloading six-1.17.0-py2.py3-none-any.whl (11 kB) +#9 45.28 Downloading argon2_cffi_bindings-26.2.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl (26 kB) +#9 45.38 Downloading cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (221 kB) +#9 45.50 Downloading mako-1.4.3-py3-none-any.whl (80 kB) +#9 45.61 Downloading markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (23 kB) +#9 45.70 Downloading pycparser-3.12-py3-none-any.whl (62 kB) +#9 45.81 Downloading rfc3339_validator-0.1.4-py2.py3-none-any.whl (3.5 kB) +#9 46.99 Installing collected packages: wrapt, urllib3, typing_extensions, six, rpds-py, redis, PyYAML, python-multipart, pycparser, protobuf, Pillow, pika, pathable, packaging, opentelemetry-util-http, MarkupSafe, lazy-object-proxy, jmespath, idna, h11, greenlet, click, charset_normalizer, certifi, attrs, asyncpg, asgiref, annotated-types, annotated-doc, uvicorn, typing-inspection, SQLAlchemy, rfc3339-validator, requests, referencing, python-dateutil, pydantic_core, opentelemetry-proto, opentelemetry-api, Mako, googleapis-common-protos, cffi, anyio, starlette, pydantic, opentelemetry-semantic-conventions, opentelemetry-propagator-aws-xray, opentelemetry-exporter-otlp-proto-common, opentelemetry-exporter-http-transport, jsonschema-specifications, jsonschema-path, botocore, argon2-cffi-bindings, alembic, s3transfer, opentelemetry-sdk, opentelemetry-instrumentation, jsonschema, fastapi, argon2-cffi, opentelemetry-instrumentation-pika, opentelemetry-instrumentation-logging, opentelemetry-instrumentation-botocore, opentelemetry-instrumentation-asgi, opentelemetry-exporter-otlp-common, openapi-schema-validator, boto3, opentelemetry-instrumentation-fastapi, opentelemetry-exporter-otlp-proto-http, openapi-spec-validator +#9 64.71 +#9 64.73 Successfully installed Mako-1.4.3 MarkupSafe-3.0.4 Pillow-13.0.0 PyYAML-6.0.4 SQLAlchemy-2.1.4 alembic-1.20.0 annotated-doc-0.0.5 annotated-types-0.8.0 anyio-4.15.1 argon2-cffi-25.1.0 argon2-cffi-bindings-26.2.0 asgiref-3.13.0 asyncpg-0.32.0 attrs-26.1.0 boto3-1.43.120 botocore-1.43.127 certifi-2026.11.20 cffi-2.1.1 charset_normalizer-3.5.3 click-8.5.0 fastapi-0.141.1 googleapis-common-protos-1.76.0 greenlet-3.5.6 h11-0.16.0 idna-3.20 jmespath-1.1.0 jsonschema-4.26.0 jsonschema-path-0.3.4 jsonschema-specifications-2025.9.1 lazy-object-proxy-1.13.0 openapi-schema-validator-0.6.3 openapi-spec-validator-0.7.2 opentelemetry-api-1.45.2 opentelemetry-exporter-http-transport-0.66b2 opentelemetry-exporter-otlp-common-0.66b2 opentelemetry-exporter-otlp-proto-common-1.45.2 opentelemetry-exporter-otlp-proto-http-1.45.2 opentelemetry-instrumentation-0.66b2 opentelemetry-instrumentation-asgi-0.66b2 opentelemetry-instrumentation-botocore-0.66b2 opentelemetry-instrumentation-fastapi-0.66b2 opentelemetry-instrumentation-logging-0.66b2 opentelemetry-instrumentation-pika-0.66b2 opentelemetry-propagator-aws-xray-1.0.2 opentelemetry-proto-1.45.2 opentelemetry-sdk-1.45.2 opentelemetry-semantic-conventions-0.66b2 opentelemetry-util-http-0.66b2 packaging-26.4 pathable-0.4.4 pika-1.3.2 protobuf-7.36.2 pycparser-3.12 pydantic-2.13.5 pydantic_core-2.46.5 python-dateutil-2.9.0.post0 python-multipart-0.0.32 redis-7.0.1 referencing-0.36.2 requests-2.34.2 rfc3339-validator-0.1.4 rpds-py-2026.9.1 s3transfer-0.19.3 six-1.17.0 starlette-1.7.0 typing-inspection-0.4.4 typing_extensions-4.16.0 urllib3-2.8.0 uvicorn-0.53.0 wrapt-2.5.2 +#9 64.74 WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning. +#9 64.74 +#9 64.74 [notice] A new release of pip is available: 26.2.1 -> 26.3 +#9 64.74 [notice] To update, run: pip install --upgrade pip +#9 DONE 66.1s + +#10 [api-2 5/10] COPY alembic.ini . +#10 DONE 0.2s + +#11 [api-1 6/10] COPY migrations ./migrations +#11 DONE 0.1s + +#12 [worker 7/10] COPY src ./src +#12 DONE 0.1s + +#13 [dispatcher 8/10] COPY scripts ./scripts +#13 DONE 0.1s + +#14 [worker 9/10] COPY tests ./tests +#14 DONE 0.1s + +#15 [api-1 10/10] RUN useradd --create-home --uid 10001 appuser +#15 DONE 0.8s + +#16 [worker] exporting to image +#16 exporting layers +#16 ... + +#17 [dispatcher] exporting to image +#17 ... + +#18 [api-1] exporting to image +#18 ... + +#19 [api-2] exporting to image +#19 ... + +#20 [migrate] exporting to image +#20 exporting layers 14.9s done +#20 exporting manifest sha256:b870d3abe0ff87c4a4639426d69f99095bb997c196884b893346e4f335585cf7 +#20 ... + +#19 [api-2] exporting to image +#19 exporting layers 14.9s done +#19 exporting manifest sha256:25246a42bdf82c2cee5347d9d666cdaa5d20ad4b1eb2220c22ba57f029c6e008 0.1s done +#19 exporting config sha256:d9cb8b3c1a4d16ac9f842d43f250a464fcd9c5eebd63999447c2eb6c3e17bff5 +#19 exporting config sha256:d9cb8b3c1a4d16ac9f842d43f250a464fcd9c5eebd63999447c2eb6c3e17bff5 0.2s done +#19 exporting attestation manifest sha256:24263ad79eb207fcb70f83cfcf7419b379213b1006b5db40f6063484c3dcf2f2 +#19 exporting attestation manifest sha256:24263ad79eb207fcb70f83cfcf7419b379213b1006b5db40f6063484c3dcf2f2 0.2s done +#19 exporting manifest list sha256:b07eea0a5811831be3e3bf808830128563e5feb10720774037d4a5e05c1b1eea +#19 exporting manifest list sha256:b07eea0a5811831be3e3bf808830128563e5feb10720774037d4a5e05c1b1eea 0.1s done +#19 naming to docker.io/library/lab7verify-api-2:latest +#19 naming to docker.io/library/lab7verify-api-2:latest 0.1s done +#19 unpacking to docker.io/library/lab7verify-api-2:latest +#19 ... + +#16 [worker] exporting to image +#16 exporting layers 14.9s done +#16 exporting manifest sha256:98886f9408e8ea321f7813272159e5910c1db240801dcd7555e82173041c7abb 0.1s done +#16 exporting config sha256:24148c650d2c66fc230434cc524431d265a23e1011c88cf6c234db040dad5204 0.1s done +#16 exporting attestation manifest sha256:7f7d28ed4657840746ade23927e9c451897da502ee6c1b82163785a0dee6f013 0.2s done +#16 exporting manifest list sha256:5ead8356a8000a7b18d1b38910a702495583e5e3490d2c359cc0d2036293a5b1 0.2s done +#16 naming to docker.io/library/lab7verify-worker:latest 0.1s done +#16 unpacking to docker.io/library/lab7verify-worker:latest 5.5s done +#16 DONE 21.4s + +#19 [api-2] exporting to image +#19 unpacking to docker.io/library/lab7verify-api-2:latest 5.6s done +#19 DONE 21.6s + +#17 [dispatcher] exporting to image +#17 exporting layers 14.9s done +#17 exporting manifest sha256:442039502e8ee06b3c05af0b2b0e8feae034d686ba95c95c965b914e7f5de8dd 0.2s done +#17 exporting config sha256:3fe7c3a5aa173c6e96d161c4f90fef5648837fc70445239d812085474dbbbd35 0.1s done +#17 exporting attestation manifest sha256:42c859bfd841f162b22b620e4e7f6310b192e085b674d1f7d2d6ca5e660cb472 0.2s done +#17 exporting manifest list sha256:3c009e7b83b801248bc5754478575f9ff70afed10afb1e8de2f49ce818b64468 0.2s done +#17 naming to docker.io/library/lab7verify-dispatcher:latest 0.0s done +#17 unpacking to docker.io/library/lab7verify-dispatcher:latest 5.6s done +#17 DONE 21.6s + +#20 [migrate] exporting to image +#20 exporting manifest sha256:b870d3abe0ff87c4a4639426d69f99095bb997c196884b893346e4f335585cf7 0.2s done +#20 exporting config sha256:15d555a9bc5bd69581c323b28e217d0554853c4d683ad62e4e080ede953cb161 0.1s done +#20 exporting attestation manifest sha256:7cde4c3f456b7d399c9e7b5acee9382c729dc95b071cb28ff31f3e8c61dbbdf0 0.2s done +#20 exporting manifest list sha256:bd75f0e1d60a6fc07506aa1bd062858c499b28d9bb5915ef6fadca40019d260d 0.2s done +#20 naming to docker.io/library/lab7verify-migrate:latest 0.0s done +#20 unpacking to docker.io/library/lab7verify-migrate:latest 5.6s done +#20 DONE 21.6s + +#18 [api-1] exporting to image +#18 exporting layers 15.0s done +#18 exporting manifest sha256:18c7dd6e4a8fb08478e467ac7d04be47f41ad3000df3b40fed029f370193a913 0.1s done +#18 exporting config sha256:a80043bebb98b316c8a42982c432b309e9b0198cf3aad7bbd2cbcd93864244e9 0.1s done +#18 exporting attestation manifest sha256:cec676bac213ab0b43f11e621a028162f668e0f5fac9458ea2016d51cd8f0dbe 0.2s done +#18 exporting manifest list sha256:c653ea2315dc31ab9bfe0826070df2feead16a1042d0f73fe39aff18e30884a2 0.2s done +#18 naming to docker.io/library/lab7verify-api-1:latest 0.1s done +#18 unpacking to docker.io/library/lab7verify-api-1:latest 5.6s done +#18 DONE 21.7s + +#21 [worker] resolving provenance for metadata file +#21 DONE 0.6s + +#22 [api-2] resolving provenance for metadata file +#22 DONE 0.6s + +#23 [migrate] resolving provenance for metadata file +#23 DONE 0.2s + +#24 [dispatcher] resolving provenance for metadata file +#24 DONE 0.4s + +#25 [api-1] resolving provenance for metadata file +#25 DONE 0.0s + Image lab7verify-api-2 Built + Image lab7verify-api-1 Built + Image lab7verify-dispatcher Built + Image lab7verify-worker Built + Image lab7verify-migrate Built diff --git a/evidence/grade3-clean-ca-isolation.txt b/evidence/grade3-clean-ca-isolation.txt new file mode 100644 index 00000000..b0088f43 --- /dev/null +++ b/evidence/grade3-clean-ca-isolation.txt @@ -0,0 +1,5 @@ +PASS: port 18443, correct CA accepted +PASS: port 8443, correct CA accepted +PASS: port 18443, foreign CA rejected +PASS: port 8443, foreign CA rejected +PASS: independent TLS trust domains diff --git a/evidence/grade3-clean-container-audit.txt b/evidence/grade3-clean-container-audit.txt new file mode 100644 index 00000000..56e2b8b3 --- /dev/null +++ b/evidence/grade3-clean-container-audit.txt @@ -0,0 +1,302 @@ + +=== api-1 === +User: appuser +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== api-1-proxy === +User: image default +Privileged: False +Network mode: container:436feedde6980f5b4e97aae6689984d79209eac390151cc749ef543bdbe89737 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 128 +CPU: 0.25 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== api-2 === +User: appuser +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== api-2-proxy === +User: image default +Privileged: False +Network mode: container:ae9aa22a578d06d81b5a345ef234c1e2ba7e5388598ffa1906365fe72f4984b4 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 128 +CPU: 0.25 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== dispatcher === +User: appuser +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== grafana === +User: 472 +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 384 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {'3000/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '13000'}]} +PASS: basic isolation + +=== loki === +User: 10001 +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== loki-proxy === +User: image default +Privileged: False +Network mode: container:f9e7e3f837292f93b07808d1622aeaac76a7c866a2bcb354fcb9e312a7174c29 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 128 +CPU: 0.25 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== nginx === +User: image default +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 256 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {'8443/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '18443'}]} +PASS: basic isolation + +=== openbao === +User: 100:1000 +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 256 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== otel-collector === +User: 10001 +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 256 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== otel-collector-proxy === +User: image default +Privileged: False +Network mode: container:c485081388e5abf54869e32bb9e49b06054b1af6994dca5112724adddfa756b4 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 128 +CPU: 0.25 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== postgres === +User: image default +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 768 +CPU: 1.0 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== prometheus === +User: nobody +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== rabbitmq === +User: image default +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== redis === +User: image default +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 256 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== s3 === +User: image default +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {'9001/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '19001'}]} +PASS: basic isolation + +=== tempo === +User: 10001:10001 +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 0.5 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== tempo-proxy === +User: image default +Privileged: False +Network mode: container:880c12640248dfdbdb34c919b13c8e408d6658355851a0c2d5b353e2d98cc334 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 128 +CPU: 0.25 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== worker === +User: appuser +Privileged: False +Network mode: lab7verify_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: 256 +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +PASS: BASIC CONTAINER ISOLATION diff --git a/evidence/grade3-clean-containers-initial.txt b/evidence/grade3-clean-containers-initial.txt new file mode 100644 index 00000000..796bb86d --- /dev/null +++ b/evidence/grade3-clean-containers-initial.txt @@ -0,0 +1,23 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +lab7verify-api-1-1 lab7verify-api-1 "python /app/scripts…" api-1 3 minutes ago Up 2 minutes (healthy) 8080/tcp +lab7verify-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 3 minutes ago Up 2 minutes +lab7verify-api-2-1 lab7verify-api-2 "python /app/scripts…" api-2 3 minutes ago Up 2 minutes (healthy) 8080/tcp +lab7verify-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 3 minutes ago Up 2 minutes +lab7verify-dispatcher-1 lab7verify-dispatcher "python /app/scripts…" dispatcher 3 minutes ago Created +lab7verify-grafana-1 grafana/grafana:11.5.2 "/run.sh" grafana 3 minutes ago Up 2 minutes 127.0.0.1:13000->3000/tcp +lab7verify-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 3 minutes ago Up 3 minutes 3100/tcp +lab7verify-loki-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" loki-proxy 3 minutes ago Up 3 minutes +lab7verify-migrate-1 lab7verify-migrate "alembic upgrade head" migrate 3 minutes ago Exited (0) 2 minutes ago +lab7verify-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 3 minutes ago Created +lab7verify-openbao-1 openbao/openbao:2.3.2 "bao server -config=…" openbao 4 minutes ago Up 4 minutes 8200/tcp +lab7verify-otel-collector-1 otel/opentelemetry-collector-contrib:0.120.0 "/otelcol-contrib --…" otel-collector 3 minutes ago Up 2 minutes 4317-4318/tcp, 55678-55679/tcp +lab7verify-otel-collector-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" otel-collector-proxy 3 minutes ago Up 2 minutes +lab7verify-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 3 minutes ago Up 3 minutes (healthy) 5432/tcp +lab7verify-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 3 minutes ago Up 2 minutes 9090/tcp +lab7verify-rabbitmq-1 rabbitmq:4.1.4-management-alpine "docker-entrypoint.s…" rabbitmq 3 minutes ago Up 2 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15671-15672/tcp, 15691-15692/tcp, 25672/tcp +lab7verify-redis-1 redis:8.2.2 "docker-entrypoint.s…" redis 3 minutes ago Up 3 minutes (healthy) 6379/tcp +lab7verify-s3-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/usr/bin/docker-ent…" s3 3 minutes ago Up 3 minutes (healthy) 127.0.0.1:19001->9001/tcp +lab7verify-s3-init-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/bin/sh /config/ini…" s3-init 3 minutes ago Exited (0) 2 minutes ago +lab7verify-tempo-1 grafana/tempo:2.7.1 "/tempo -config.file…" tempo 3 minutes ago Up 3 minutes +lab7verify-tempo-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" tempo-proxy 3 minutes ago Up 3 minutes +lab7verify-worker-1 lab7verify-worker "python /app/scripts…" worker 3 minutes ago Up About a minute 8080/tcp diff --git a/evidence/grade3-clean-containers.txt b/evidence/grade3-clean-containers.txt new file mode 100644 index 00000000..603475b8 --- /dev/null +++ b/evidence/grade3-clean-containers.txt @@ -0,0 +1,23 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +lab7verify-api-1-1 lab7verify-api-1 "python /app/scripts…" api-1 5 minutes ago Up 4 minutes (healthy) 8080/tcp +lab7verify-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 5 minutes ago Up 4 minutes +lab7verify-api-2-1 lab7verify-api-2 "python /app/scripts…" api-2 5 minutes ago Up 4 minutes (healthy) 8080/tcp +lab7verify-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 5 minutes ago Up 4 minutes +lab7verify-dispatcher-1 lab7verify-dispatcher "python /app/scripts…" dispatcher 5 minutes ago Up 20 seconds 8080/tcp +lab7verify-grafana-1 grafana/grafana:11.5.2 "/run.sh" grafana 5 minutes ago Up 5 minutes 127.0.0.1:13000->3000/tcp +lab7verify-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 5 minutes ago Up 5 minutes 3100/tcp +lab7verify-loki-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" loki-proxy 5 minutes ago Up 5 minutes +lab7verify-migrate-1 lab7verify-migrate "alembic upgrade head" migrate 5 minutes ago Exited (0) 25 seconds ago +lab7verify-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 5 minutes ago Up 20 seconds 127.0.0.1:18443->8443/tcp +lab7verify-openbao-1 openbao/openbao:2.3.2 "bao server -config=…" openbao 6 minutes ago Up 6 minutes 8200/tcp +lab7verify-otel-collector-1 otel/opentelemetry-collector-contrib:0.120.0 "/otelcol-contrib --…" otel-collector 5 minutes ago Up 5 minutes 4317-4318/tcp, 55678-55679/tcp +lab7verify-otel-collector-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" otel-collector-proxy 5 minutes ago Up 5 minutes +lab7verify-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 5 minutes ago Up 5 minutes (healthy) 5432/tcp +lab7verify-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 5 minutes ago Up 5 minutes 9090/tcp +lab7verify-rabbitmq-1 rabbitmq:4.1.4-management-alpine "docker-entrypoint.s…" rabbitmq 5 minutes ago Up 4 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15671-15672/tcp, 15691-15692/tcp, 25672/tcp +lab7verify-redis-1 redis:8.2.2 "docker-entrypoint.s…" redis 5 minutes ago Up 5 minutes (healthy) 6379/tcp +lab7verify-s3-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/usr/bin/docker-ent…" s3 5 minutes ago Up 5 minutes (healthy) 127.0.0.1:19001->9001/tcp +lab7verify-s3-init-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/bin/sh /config/ini…" s3-init 5 minutes ago Exited (0) 21 seconds ago +lab7verify-tempo-1 grafana/tempo:2.7.1 "/tempo -config.file…" tempo 5 minutes ago Up 5 minutes +lab7verify-tempo-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" tempo-proxy 5 minutes ago Up 5 minutes +lab7verify-worker-1 lab7verify-worker "python /app/scripts…" worker 5 minutes ago Up 3 minutes 8080/tcp diff --git a/evidence/grade3-clean-dependency-audit.txt b/evidence/grade3-clean-dependency-audit.txt new file mode 100644 index 00000000..5c418afc --- /dev/null +++ b/evidence/grade3-clean-dependency-audit.txt @@ -0,0 +1 @@ +No known vulnerabilities found diff --git a/evidence/grade3-clean-final-containers.txt b/evidence/grade3-clean-final-containers.txt new file mode 100644 index 00000000..d8271ffa --- /dev/null +++ b/evidence/grade3-clean-final-containers.txt @@ -0,0 +1,23 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +lab7verify-api-1-1 lab7verify-api-1 "python /app/scripts…" api-1 19 minutes ago Up 18 minutes (healthy) 8080/tcp +lab7verify-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 19 minutes ago Up 18 minutes +lab7verify-api-2-1 lab7verify-api-2 "python /app/scripts…" api-2 19 minutes ago Up 18 minutes (healthy) 8080/tcp +lab7verify-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 19 minutes ago Up 18 minutes +lab7verify-dispatcher-1 lab7verify-dispatcher "python /app/scripts…" dispatcher 19 minutes ago Up 3 minutes 8080/tcp +lab7verify-grafana-1 grafana/grafana:11.5.2 "/run.sh" grafana 19 minutes ago Up 19 minutes 127.0.0.1:13000->3000/tcp +lab7verify-loki-1 grafana/loki:3.4.2 "/usr/bin/loki -conf…" loki 19 minutes ago Up 19 minutes 3100/tcp +lab7verify-loki-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" loki-proxy 19 minutes ago Up 19 minutes +lab7verify-migrate-1 lab7verify-migrate "alembic upgrade head" migrate 19 minutes ago Exited (0) 3 minutes ago +lab7verify-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 19 minutes ago Up 14 minutes 127.0.0.1:18443->8443/tcp +lab7verify-openbao-1 openbao/openbao:2.3.2 "bao server -config=…" openbao 20 minutes ago Up 20 minutes 8200/tcp +lab7verify-otel-collector-1 otel/opentelemetry-collector-contrib:0.120.0 "/otelcol-contrib --…" otel-collector 19 minutes ago Up 19 minutes 4317-4318/tcp, 55678-55679/tcp +lab7verify-otel-collector-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" otel-collector-proxy 19 minutes ago Up 19 minutes +lab7verify-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 19 minutes ago Up 19 minutes (healthy) 5432/tcp +lab7verify-prometheus-1 prom/prometheus:v3.2.1 "/bin/prometheus --c…" prometheus 19 minutes ago Up 19 minutes 9090/tcp +lab7verify-rabbitmq-1 rabbitmq:4.1.4-management-alpine "docker-entrypoint.s…" rabbitmq 4 minutes ago Up 4 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15671-15672/tcp, 15691-15692/tcp, 25672/tcp +lab7verify-redis-1 redis:8.2.2 "docker-entrypoint.s…" redis 19 minutes ago Up 19 minutes (healthy) 6379/tcp +lab7verify-s3-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/usr/bin/docker-ent…" s3 19 minutes ago Up 19 minutes (healthy) 127.0.0.1:19001->9001/tcp +lab7verify-s3-init-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/bin/sh /config/ini…" s3-init 19 minutes ago Exited (0) 3 minutes ago +lab7verify-tempo-1 grafana/tempo:2.7.1 "/tempo -config.file…" tempo 19 minutes ago Up 19 minutes +lab7verify-tempo-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" tempo-proxy 19 minutes ago Up 19 minutes +lab7verify-worker-1 lab7verify-worker "python /app/scripts…" worker 19 minutes ago Up 3 minutes 8080/tcp diff --git a/evidence/grade3-clean-final-security.txt b/evidence/grade3-clean-final-security.txt new file mode 100644 index 00000000..d17e7bd9 --- /dev/null +++ b/evidence/grade3-clean-final-security.txt @@ -0,0 +1,2 @@ +python3 tests/security.py --base-url "https://localhost:18443" --ca-file "/home/casablanca/mtuci/high_load_apps/lab7verify.LJ40hS/certs/ca/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/grade3-clean-final-smoke.txt b/evidence/grade3-clean-final-smoke.txt new file mode 100644 index 00000000..0e711e93 --- /dev/null +++ b/evidence/grade3-clean-final-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:18443" --ca-file "/home/casablanca/mtuci/high_load_apps/lab7verify.LJ40hS/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-clean-hardening.txt b/evidence/grade3-clean-hardening.txt new file mode 100644 index 00000000..278fff00 --- /dev/null +++ b/evidence/grade3-clean-hardening.txt @@ -0,0 +1,24 @@ +PASS: api-1, pids_limit=256, no-new-privileges=true, state=running +PASS: api-1-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: api-2, pids_limit=256, no-new-privileges=true, state=running +PASS: api-2-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: dispatcher, pids_limit=256, no-new-privileges=true, state=running +PASS: grafana, pids_limit=256, no-new-privileges=true, state=running +PASS: loki, pids_limit=256, no-new-privileges=true, state=running +PASS: loki-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: migrate, pids_limit=256, no-new-privileges=true, state=exited +PASS: nginx, pids_limit=256, no-new-privileges=true, state=running +PASS: openbao, pids_limit=256, no-new-privileges=true, state=running +PASS: otel-collector, pids_limit=256, no-new-privileges=true, state=running +PASS: otel-collector-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: postgres, pids_limit=256, no-new-privileges=true, state=running +PASS: prometheus, pids_limit=256, no-new-privileges=true, state=running +PASS: rabbitmq, pids_limit=256, no-new-privileges=true, state=running +PASS: redis, pids_limit=256, no-new-privileges=true, state=running +PASS: s3, pids_limit=256, no-new-privileges=true, state=running +PASS: s3-init, pids_limit=256, no-new-privileges=true, state=exited +PASS: tempo, pids_limit=256, no-new-privileges=true, state=running +PASS: tempo-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: worker, pids_limit=256, no-new-privileges=true, state=running + +PASS: ALL 22 CONTAINERS HARDENED diff --git a/evidence/grade3-clean-image-audit.txt b/evidence/grade3-clean-image-audit.txt new file mode 100644 index 00000000..b24feb99 --- /dev/null +++ b/evidence/grade3-clean-image-audit.txt @@ -0,0 +1,46 @@ +Selected: api-1: lab7verify-api-1: sha256:c653ea2315dc31ab9bfe0826070df2feead16a1042d0f73fe39aff18e30884a2 +Selected: api-2: lab7verify-api-2: sha256:b07eea0a5811831be3e3bf808830128563e5feb10720774037d4a5e05c1b1eea +Selected: worker: lab7verify-worker: sha256:5ead8356a8000a7b18d1b38910a702495583e5e3490d2c359cc0d2036293a5b1 +Selected: dispatcher: lab7verify-dispatcher: sha256:3c009e7b83b801248bc5754478575f9ff70afed10afb1e8de2f49ce818b64468 +Selected: migrate: lab7verify-migrate: sha256:bd75f0e1d60a6fc07506aa1bd062858c499b28d9bb5915ef6fadca40019d260d +=== DOCKER IMAGE SECRET AUDIT === +Services: 5 +Unique images: 5 +Credential patterns: 41 + +Inspecting: api-1 +Layers checked: 1 | Files checked: 2677 +Layers checked: 2 | Files checked: 2881 +Layers checked: 3 | Files checked: 4474 +Layers checked: 4 | Files checked: 4474 +Layers checked: 5 | Files checked: 4474 +Layers checked: 6 | Files checked: 4475 +Layers checked: 7 | Files checked: 11159 +Layers checked: 8 | Files checked: 11160 +Layers checked: 9 | Files checked: 11174 +Layers checked: 10 | Files checked: 11191 +Layers checked: 11 | Files checked: 11213 +Layers checked: 12 | Files checked: 11222 +Layers checked: 13 | Files checked: 11237 +Completed: api-1 + +Inspecting: api-2 +Completed: api-2 + +Inspecting: worker +Completed: worker + +Inspecting: dispatcher +Completed: dispatcher + +Inspecting: migrate +Completed: migrate + +=== SUMMARY === +Services inspected: 5 +Unique images inspected: 5 +Unique layers inspected: 13 +Layer files inspected: 11237 +Credential patterns: 41 +Failures: 0 +PASS: DOCKER IMAGE SECRET AUDIT diff --git a/evidence/grade3-clean-isolation.txt b/evidence/grade3-clean-isolation.txt new file mode 100644 index 00000000..6ed9b480 --- /dev/null +++ b/evidence/grade3-clean-isolation.txt @@ -0,0 +1,13 @@ +grafana published port: 13000 +nginx published port: 18443 +s3 published port: 19001 +Independent volume: lab7verify_grafana_data +Independent volume: lab7verify_loki_data +Independent volume: lab7verify_postgres_data +Independent volume: lab7verify_prometheus_data +Independent volume: lab7verify_rabbitmq_data +Independent volume: lab7verify_redis_data +Independent volume: lab7verify_s3_data +Independent volume: lab7verify_tempo_data +Independent network: lab7verify_default +PASS: verification stack isolation diff --git a/evidence/grade3-clean-network-audit.txt b/evidence/grade3-clean-network-audit.txt new file mode 100644 index 00000000..610f8c4e --- /dev/null +++ b/evidence/grade3-clean-network-audit.txt @@ -0,0 +1,79 @@ + Container lab7verify-migrate-run-3a0a4e9e248b Creating + Container lab7verify-migrate-run-3a0a4e9e248b Created + +=== nginx === +80: CLOSED +443: CLOSED +8080: CLOSED +8443: OPEN + +=== api-1 === +8080: CLOSED +8443: OPEN + +=== api-2 === +8080: CLOSED +8443: OPEN + +=== worker === +8080: CLOSED + +=== dispatcher === +8080: CLOSED + +=== postgres === +5432: OPEN + +=== redis === +6379: OPEN + +=== rabbitmq === +4369: CLOSED +5671: OPEN +5672: CLOSED +15671: OPEN +15672: CLOSED +15691: CLOSED +15692: CLOSED +25672: CLOSED + +=== s3 === +9000: OPEN +9001: OPEN + +=== openbao === +8200: OPEN +8201: CLOSED + +=== otel-collector === +4317: CLOSED +4318: OPEN +8888: OPEN +8889: OPEN +18888: CLOSED +18889: CLOSED +55678: CLOSED +55679: CLOSED + +=== prometheus === +9090: OPEN + +=== loki === +3100: OPEN +7946: CLOSED +9095: CLOSED +13100: CLOSED + +=== tempo === +3200: OPEN +4317: CLOSED +4318: CLOSED +7946: CLOSED +9095: CLOSED +13200: CLOSED +14318: CLOSED + +=== grafana === +3000: OPEN + +NETWORK AUDIT COMPLETE diff --git a/evidence/grade3-clean-openbao-config.txt b/evidence/grade3-clean-openbao-config.txt new file mode 100644 index 00000000..3e2a79a1 --- /dev/null +++ b/evidence/grade3-clean-openbao-config.txt @@ -0,0 +1,13 @@ + Container lab7verify-migrate-run-4c8e2e28759c Creating + Container lab7verify-migrate-run-4c8e2e28759c Created +PASS: KV v2 enabled +PASS: certificate authentication enabled +PASS: messenger-api policy configured +PASS: messenger-worker policy configured +PASS: messenger-dispatcher policy configured +PASS: bao-api-1 -> messenger-api, TTL=15m, max TTL=1h +PASS: bao-api-2 -> messenger-api, TTL=15m, max TTL=1h +PASS: bao-worker -> messenger-worker, TTL=15m, max TTL=1h +PASS: bao-dispatcher -> messenger-dispatcher, TTL=15m, max TTL=1h + +PASS: OPENBAO CONFIGURATION diff --git a/evidence/grade3-clean-openbao-init.txt b/evidence/grade3-clean-openbao-init.txt new file mode 100644 index 00000000..3fe7ae78 --- /dev/null +++ b/evidence/grade3-clean-openbao-init.txt @@ -0,0 +1 @@ +PASS: OpenBao initialized; operator material saved outside Git diff --git a/evidence/grade3-clean-openbao-integration.txt b/evidence/grade3-clean-openbao-integration.txt new file mode 100644 index 00000000..05790e67 --- /dev/null +++ b/evidence/grade3-clean-openbao-integration.txt @@ -0,0 +1,4 @@ +api-1-1 | PASS: OpenBao identity=bao-api-1, role=api, secrets=5 +dispatcher-1 | PASS: OpenBao identity=bao-dispatcher, role=dispatcher, secrets=3 +api-2-1 | PASS: OpenBao identity=bao-api-2, role=api, secrets=5 +worker-1 | PASS: OpenBao identity=bao-worker, role=worker, secrets=5 diff --git a/evidence/grade3-clean-openbao-seed.txt b/evidence/grade3-clean-openbao-seed.txt new file mode 100644 index 00000000..ab3784e7 --- /dev/null +++ b/evidence/grade3-clean-openbao-seed.txt @@ -0,0 +1,7 @@ + Container lab7verify-migrate-run-14ec748ca897 Creating + Container lab7verify-migrate-run-14ec748ca897 Created +PASS: messenger/api: 5 secrets stored, version=1 +PASS: messenger/worker: 5 secrets stored, version=1 +PASS: messenger/dispatcher: 3 secrets stored, version=1 + +PASS: OPENBAO SECRETS SEEDED diff --git a/evidence/grade3-clean-openbao-status.txt b/evidence/grade3-clean-openbao-status.txt new file mode 100644 index 00000000..e528aa44 --- /dev/null +++ b/evidence/grade3-clean-openbao-status.txt @@ -0,0 +1,13 @@ +Key Value +--- ----- +Seal Type shamir +Initialized true +Sealed false +Total Shares 3 +Threshold 2 +Version 2.3.2 +Build Date 2025-08-08T04:05:27Z +Storage Type file +Cluster Name vault-cluster-4fc9f8d0 +Cluster ID 6e53e285-787a-8182-d78d-f5150b26a3e9 +HA Enabled false diff --git a/evidence/grade3-clean-openbao-unseal.txt b/evidence/grade3-clean-openbao-unseal.txt new file mode 100644 index 00000000..0b81fa00 --- /dev/null +++ b/evidence/grade3-clean-openbao-unseal.txt @@ -0,0 +1,9 @@ + Volume lab7verify_postgres_data Creating + Volume lab7verify_postgres_data Creating + Volume lab7verify_postgres_data Created + Volume lab7verify_postgres_data Created + Container lab7verify-migrate-run-eeba069fafa6 Creating + Container lab7verify-migrate-run-eeba069fafa6 Created +Sealed: True | Progress: 1 | Threshold: 2 +Sealed: False | Progress: 0 | Threshold: 2 +PASS: OpenBao successfully unsealed diff --git a/evidence/grade3-clean-rabbitmq-cold-start-details.txt b/evidence/grade3-clean-rabbitmq-cold-start-details.txt new file mode 100644 index 00000000..afd32e8b --- /dev/null +++ b/evidence/grade3-clean-rabbitmq-cold-start-details.txt @@ -0,0 +1,7 @@ +rabbitmq-1 | 2026-12-06 21:25:16.335991+00:00 [info] <0.584.0> Importing concurrently 3 users... +rabbitmq-1 | 2026-12-06 21:25:16.353126+00:00 [info] <0.584.0> Importing concurrently 1 vhosts... +rabbitmq-1 | 2026-12-06 21:25:16.530842+00:00 [info] <0.584.0> Importing concurrently 3 permissions... +rabbitmq-1 | 2026-12-06 21:25:16.540754+00:00 [info] <0.584.0> Importing concurrently 2 queues... +rabbitmq-1 | 2026-12-06 21:25:16.574452+00:00 [info] <0.758.0> started TLS (SSL) listener on [::]:5671 +rabbitmq-1 | 2026-12-06 21:25:17.344934+00:00 [info] <0.584.0> Server startup complete; 3 plugins started. +rabbitmq-1 | 2026-12-06 21:25:17.355695+00:00 [info] <0.10.0> Time to start RabbitMQ: 67392 ms diff --git a/evidence/grade3-clean-rabbitmq-cold-start.txt b/evidence/grade3-clean-rabbitmq-cold-start.txt new file mode 100644 index 00000000..e03f2c6a --- /dev/null +++ b/evidence/grade3-clean-rabbitmq-cold-start.txt @@ -0,0 +1,10 @@ + Volume lab7verify_rabbitmq_cold_test Creating + Volume lab7verify_rabbitmq_cold_test Creating + Volume lab7verify_rabbitmq_cold_test Created + Volume lab7verify_rabbitmq_cold_test Created + Container lab7verify-rabbitmq-1 Recreate + Container lab7verify-rabbitmq-1 Recreated + Container lab7verify-rabbitmq-1 Starting + Container lab7verify-rabbitmq-1 Started + Container lab7verify-rabbitmq-1 Waiting + Container lab7verify-rabbitmq-1 Healthy diff --git a/evidence/grade3-clean-rabbitmq-healthcheck.txt b/evidence/grade3-clean-rabbitmq-healthcheck.txt new file mode 100644 index 00000000..c92f5b7a --- /dev/null +++ b/evidence/grade3-clean-rabbitmq-healthcheck.txt @@ -0,0 +1,6 @@ + Container lab7verify-rabbitmq-1 Recreate + Container lab7verify-rabbitmq-1 Recreated + Container lab7verify-rabbitmq-1 Starting + Container lab7verify-rabbitmq-1 Started + Container lab7verify-rabbitmq-1 Waiting + Container lab7verify-rabbitmq-1 Healthy diff --git a/evidence/grade3-clean-rabbitmq-startup.txt b/evidence/grade3-clean-rabbitmq-startup.txt new file mode 100644 index 00000000..5309b773 --- /dev/null +++ b/evidence/grade3-clean-rabbitmq-startup.txt @@ -0,0 +1,150 @@ +rabbitmq-1 | 2026-12-06 21:13:27.509422+00:00 [info] <0.209.0> Running boot step rabbit_core_metrics defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:27.513082+00:00 [info] <0.209.0> Running boot step rabbit_alarm defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:27.825318+00:00 [info] <0.280.0> Memory high watermark set to 7177 MiB (7526060851 bytes) of 11962 MiB (12543434752 bytes) total +rabbitmq-1 | 2026-12-06 21:13:27.921912+00:00 [info] <0.282.0> Enabling free disk space monitoring (disk free space: 1016069079040, total memory: 12543434752) +rabbitmq-1 | 2026-12-06 21:13:27.922098+00:00 [info] <0.282.0> Disk free limit set to 50MB +rabbitmq-1 | 2026-12-06 21:13:27.929563+00:00 [info] <0.209.0> Running boot step code_server_cache defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:27.929868+00:00 [info] <0.209.0> Running boot step file_handle_cache defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:28.218484+00:00 [info] <0.285.0> Limiting to approx 1048479 file handles (943629 sockets) +rabbitmq-1 | 2026-12-06 21:13:28.219469+00:00 [info] <0.286.0> FHC read buffering: OFF +rabbitmq-1 | 2026-12-06 21:13:28.219632+00:00 [info] <0.286.0> FHC write buffering: ON +rabbitmq-1 | 2026-12-06 21:13:28.224871+00:00 [info] <0.209.0> Running boot step worker_pool defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:28.225062+00:00 [info] <0.267.0> Will use 20 processes for default worker pool +rabbitmq-1 | 2026-12-06 21:13:28.225155+00:00 [info] <0.267.0> Starting worker pool 'worker_pool' with 20 processes in it +rabbitmq-1 | 2026-12-06 21:13:28.308551+00:00 [info] <0.209.0> Running boot step rabbit_registry defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:28.308779+00:00 [info] <0.209.0> Running boot step database defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:28.311167+00:00 [info] <0.209.0> Peer discovery: configured backend: rabbit_peer_discovery_classic_config +rabbitmq-1 | 2026-12-06 21:13:28.319188+00:00 [notice] <0.268.0> Feature flags: attempt to enable `detailed_queues_endpoint`... +rabbitmq-1 | 2026-12-06 21:13:28.513375+00:00 [notice] <0.268.0> Feature flags: `detailed_queues_endpoint` enabled +rabbitmq-1 | 2026-12-06 21:13:28.513577+00:00 [notice] <0.268.0> Feature flags: attempt to enable `rabbit_exchange_type_local_random`... +rabbitmq-1 | 2026-12-06 21:13:28.812268+00:00 [notice] <0.268.0> Feature flags: `rabbit_exchange_type_local_random` enabled +rabbitmq-1 | 2026-12-06 21:13:28.812456+00:00 [notice] <0.268.0> Feature flags: attempt to enable `rabbitmq_4.0.0`... +rabbitmq-1 | 2026-12-06 21:13:29.122060+00:00 [notice] <0.268.0> Feature flags: `rabbitmq_4.0.0` enabled +rabbitmq-1 | 2026-12-06 21:13:29.122237+00:00 [notice] <0.268.0> Feature flags: attempt to enable `message_containers_deaths_v2`... +rabbitmq-1 | 2026-12-06 21:13:29.321555+00:00 [notice] <0.268.0> Feature flags: `message_containers_deaths_v2` enabled +rabbitmq-1 | 2026-12-06 21:13:29.321891+00:00 [notice] <0.268.0> Feature flags: attempt to enable `rabbitmq_4.1.0`... +rabbitmq-1 | 2026-12-06 21:13:29.533006+00:00 [notice] <0.268.0> Feature flags: `rabbitmq_4.1.0` enabled +rabbitmq-1 | 2026-12-06 21:13:29.533169+00:00 [notice] <0.268.0> Feature flags: attempt to enable `quorum_queue_non_voters`... +rabbitmq-1 | 2026-12-06 21:13:29.811925+00:00 [notice] <0.268.0> Feature flags: `quorum_queue_non_voters` enabled +rabbitmq-1 | 2026-12-06 21:13:29.814778+00:00 [info] <0.209.0> DB: virgin node -> run peer discovery +rabbitmq-1 | 2026-12-06 21:13:29.814957+00:00 [warning] <0.209.0> Classic peer discovery backend: list of nodes does not contain the local node [] +rabbitmq-1 | 2026-12-06 21:13:30.113407+00:00 [notice] <0.45.0> Application mnesia exited with reason: stopped +rabbitmq-1 | 2026-12-06 21:13:33.351328+00:00 [info] <0.209.0> Waiting for Mnesia tables for 30000 ms, 9 retries left +rabbitmq-1 | 2026-12-06 21:13:33.351849+00:00 [info] <0.209.0> Successfully synced tables from a peer +rabbitmq-1 | 2026-12-06 21:13:33.352165+00:00 [info] <0.209.0> Waiting for Mnesia tables for 30000 ms, 9 retries left +rabbitmq-1 | 2026-12-06 21:13:33.352727+00:00 [info] <0.209.0> Successfully synced tables from a peer +rabbitmq-1 | 2026-12-06 21:13:33.370596+00:00 [info] <0.209.0> Waiting for Mnesia tables for 30000 ms, 9 retries left +rabbitmq-1 | 2026-12-06 21:13:33.370907+00:00 [info] <0.209.0> Successfully synced tables from a peer +rabbitmq-1 | 2026-12-06 21:13:33.371369+00:00 [info] <0.209.0> Running boot step tracking_metadata_store defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.371577+00:00 [info] <0.503.0> Setting up a table for connection tracking on this node: tracked_connection +rabbitmq-1 | 2026-12-06 21:13:33.371708+00:00 [info] <0.503.0> Setting up a table for per-vhost connection counting on this node: tracked_connection_per_vhost +rabbitmq-1 | 2026-12-06 21:13:33.371825+00:00 [info] <0.503.0> Setting up a table for per-user connection counting on this node: tracked_connection_per_user +rabbitmq-1 | 2026-12-06 21:13:33.371982+00:00 [info] <0.503.0> Setting up a table for channel tracking on this node: tracked_channel +rabbitmq-1 | 2026-12-06 21:13:33.372091+00:00 [info] <0.503.0> Setting up a table for channel tracking on this node: tracked_channel_per_user +rabbitmq-1 | 2026-12-06 21:13:33.372352+00:00 [info] <0.209.0> Running boot step networking_metadata_store defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.372562+00:00 [info] <0.209.0> Running boot step feature_flags defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.372933+00:00 [info] <0.209.0> Running boot step auth_backend_plugins_check defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.373035+00:00 [info] <0.209.0> Running boot step codec_correctness_check defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.373192+00:00 [info] <0.209.0> Running boot step external_infrastructure defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.373305+00:00 [info] <0.209.0> Running boot step rabbit_event defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.373587+00:00 [info] <0.209.0> Running boot step rabbit_auth_mechanism_amqplain defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.373771+00:00 [info] <0.209.0> Running boot step rabbit_auth_mechanism_anonymous defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.373861+00:00 [info] <0.209.0> Running boot step rabbit_auth_mechanism_cr_demo defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374103+00:00 [info] <0.209.0> Running boot step rabbit_auth_mechanism_plain defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374308+00:00 [info] <0.209.0> Running boot step rabbit_exchange_type_direct defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374406+00:00 [info] <0.209.0> Running boot step rabbit_exchange_type_fanout defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374501+00:00 [info] <0.209.0> Running boot step rabbit_exchange_type_headers defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374595+00:00 [info] <0.209.0> Running boot step rabbit_exchange_type_local_random defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374761+00:00 [info] <0.209.0> Running boot step rabbit_exchange_type_topic defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374841+00:00 [info] <0.209.0> Running boot step rabbit_priority_queue defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.374878+00:00 [info] <0.209.0> Priority queues enabled, real BQ is rabbit_variable_queue +rabbitmq-1 | 2026-12-06 21:13:33.375049+00:00 [info] <0.209.0> Running boot step kernel_ready defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.375102+00:00 [info] <0.209.0> Running boot step pg_local_amqp_connection defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.423276+00:00 [info] <0.209.0> Running boot step pg_local_amqp_session defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.423746+00:00 [info] <0.209.0> Running boot step rabbit_sysmon_minder defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.424073+00:00 [info] <0.209.0> Running boot step rabbit_epmd_monitor defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.428264+00:00 [info] <0.512.0> epmd monitor knows us, inter-node communication (distribution) port: 25672 +rabbitmq-1 | 2026-12-06 21:13:33.428531+00:00 [info] <0.209.0> Running boot step guid_generator defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.437937+00:00 [info] <0.209.0> Running boot step rabbit_node_monitor defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.438634+00:00 [info] <0.516.0> Starting rabbit_node_monitor (in ignore mode) +rabbitmq-1 | 2026-12-06 21:13:33.439021+00:00 [info] <0.209.0> Running boot step delegate_sup defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440066+00:00 [info] <0.209.0> Running boot step rabbit_fifo_dlx_sup defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440200+00:00 [info] <0.209.0> Running boot step core_initialized defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440248+00:00 [info] <0.209.0> Running boot step rabbit_channel_tracking_handler defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440399+00:00 [info] <0.209.0> Running boot step rabbit_classic_queue defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440586+00:00 [info] <0.209.0> Running boot step rabbit_connection_tracking_handler defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440738+00:00 [info] <0.209.0> Running boot step rabbit_definitions_hashing defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:33.440847+00:00 [info] <0.209.0> Running boot step rabbit_exchange_parameters defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.122183+00:00 [info] <0.209.0> Running boot step rabbit_policies defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.124094+00:00 [info] <0.209.0> Running boot step rabbit_policy defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.124253+00:00 [info] <0.209.0> Running boot step rabbit_quorum_memory_manager defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.124397+00:00 [info] <0.209.0> Running boot step rabbit_quorum_queue defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.124898+00:00 [info] <0.209.0> Running boot step rabbit_stream_coordinator defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.125330+00:00 [info] <0.209.0> Running boot step rabbit_vhost_limit defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.125687+00:00 [info] <0.209.0> Running boot step rabbit_mgmt_reset_handler defined by app rabbitmq_management +rabbitmq-1 | 2026-12-06 21:13:35.125795+00:00 [info] <0.209.0> Running boot step rabbit_mgmt_db_handler defined by app rabbitmq_management_agent +rabbitmq-1 | 2026-12-06 21:13:35.125958+00:00 [info] <0.209.0> Management plugin: using rates mode 'basic' +rabbitmq-1 | 2026-12-06 21:13:35.126759+00:00 [info] <0.209.0> Running boot step recovery defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.221171+00:00 [info] <0.209.0> Running boot step prevent_startup_if_node_was_reset defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.221356+00:00 [info] <0.209.0> Running boot step empty_db_check defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.221515+00:00 [info] <0.209.0> Will not seed default virtual host and user: have definitions to load... +rabbitmq-1 | 2026-12-06 21:13:35.222405+00:00 [info] <0.209.0> Running boot step rabbit_observer_cli defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.223133+00:00 [info] <0.209.0> Running boot step rabbit_core_metrics_gc defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.223538+00:00 [info] <0.209.0> Running boot step background_gc defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.224766+00:00 [info] <0.209.0> Running boot step routing_ready defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.225163+00:00 [info] <0.209.0> Running boot step pre_flight defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.225460+00:00 [info] <0.209.0> Running boot step notify_cluster defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.225594+00:00 [info] <0.209.0> Running boot step networking defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.226060+00:00 [info] <0.209.0> Running boot step rabbit_quorum_queue_periodic_membership_reconciliation defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.227208+00:00 [info] <0.209.0> Running boot step definition_import_worker_pool defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.227507+00:00 [info] <0.267.0> Starting worker pool 'definition_import_pool' with 20 processes in it +rabbitmq-1 | 2026-12-06 21:13:35.229506+00:00 [info] <0.209.0> Running boot step cluster_name defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.229679+00:00 [info] <0.209.0> Initialising internal cluster ID to 'rabbitmq-cluster-id-NEj1hfo8ITzoLIYTs1uuDA' +rabbitmq-1 | 2026-12-06 21:13:35.238535+00:00 [info] <0.209.0> Running boot step virtual_host_reconciliation defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.238974+00:00 [info] <0.209.0> Running boot step direct_client defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.239364+00:00 [info] <0.209.0> Running boot step cluster_tags defined by app rabbit +rabbitmq-1 | 2026-12-06 21:13:35.246789+00:00 [info] <0.209.0> Running boot step rabbit_management_load_definitions defined by app rabbitmq_management +rabbitmq-1 | 2026-12-06 21:13:35.247066+00:00 [info] <0.580.0> Resetting node maintenance status +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> Deprecated features: `management_metrics_collection`: Feature `management_metrics_collection` is deprecated. +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> By default, this feature can still be used for now. +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> Its use will not be permitted by default in a future minor RabbitMQ version and the feature will be removed from a future major RabbitMQ version; actual versions to be determined. +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> To continue using this feature when it is not permitted by default, set the following parameter in your configuration: +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> "deprecated_features.permit.management_metrics_collection = true" +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> To test RabbitMQ as if the feature was removed, set this in your configuration: +rabbitmq-1 | 2026-12-06 21:13:36.522993+00:00 [warning] <0.602.0> "deprecated_features.permit.management_metrics_collection = false" +rabbitmq-1 | 2026-12-06 21:13:37.556218+00:00 [info] <0.638.0> Management plugin: HTTPS listener started on port 15671 +rabbitmq-1 | 2026-12-06 21:13:37.556815+00:00 [info] <0.668.0> Statistics database started. +rabbitmq-1 | 2026-12-06 21:13:37.557074+00:00 [info] <0.667.0> Starting worker pool 'management_worker_pool' with 3 processes in it +rabbitmq-1 | 2026-12-06 21:13:37.600817+00:00 [info] <0.580.0> Applying definitions from file at '/run/secrets/rabbitmq_definitions' +rabbitmq-1 | 2026-12-06 21:13:37.601100+00:00 [info] <0.580.0> Asked to import definitions. Acting user: rmq-internal +rabbitmq-1 | 2026-12-06 21:13:37.622407+00:00 [info] <0.580.0> Importing concurrently 3 users... +rabbitmq-1 | 2026-12-06 21:13:37.632274+00:00 [info] <0.556.0> Created user 'messenger_admin' +rabbitmq-1 | 2026-12-06 21:13:37.632460+00:00 [info] <0.556.0> Successfully set user tags for user 'messenger_admin' to [administrator] +rabbitmq-1 | 2026-12-06 21:13:37.633800+00:00 [info] <0.557.0> Created user 'messenger_producer' +rabbitmq-1 | 2026-12-06 21:13:37.633965+00:00 [info] <0.558.0> Created user 'messenger_consumer' +rabbitmq-1 | 2026-12-06 21:13:37.635044+00:00 [info] <0.580.0> Importing concurrently 1 vhosts... +rabbitmq-1 | 2026-12-06 21:13:37.639220+00:00 [info] <0.556.0> Adding vhost 'messenger' (description: '', tags: []) +rabbitmq-1 | 2026-12-06 21:13:37.744749+00:00 [info] <0.681.0> Making sure data directory '/var/lib/rabbitmq/mnesia/rabbit@rabbitmq/msg_stores/vhosts/4N9FZBLSWU8D2DA5ZAXS6O06C' for vhost 'messenger' exists +rabbitmq-1 | 2026-12-06 21:13:37.751769+00:00 [info] <0.681.0> Setting segment_entry_count for vhost 'messenger' with 0 queues to '2048' +rabbitmq-1 | 2026-12-06 21:13:37.799287+00:00 [info] <0.681.0> Starting message stores for vhost 'messenger' +rabbitmq-1 | 2026-12-06 21:13:37.812161+00:00 [info] <0.681.0> Started message store of type transient for vhost 'messenger' +rabbitmq-1 | 2026-12-06 21:13:37.814729+00:00 [warning] <0.695.0> Message store "4N9FZBLSWU8D2DA5ZAXS6O06C/msg_store_persistent": rebuilding indices from scratch +rabbitmq-1 | 2026-12-06 21:13:37.817180+00:00 [info] <0.681.0> Started message store of type persistent for vhost 'messenger' +rabbitmq-1 | 2026-12-06 21:13:37.817620+00:00 [info] <0.681.0> Recovering 0 queues of type rabbit_classic_queue took 63ms +rabbitmq-1 | 2026-12-06 21:13:37.817785+00:00 [info] <0.681.0> Recovering 0 queues of type rabbit_quorum_queue took 0ms +rabbitmq-1 | 2026-12-06 21:13:37.817901+00:00 [info] <0.681.0> Recovering 0 queues of type rabbit_stream_queue took 0ms +rabbitmq-1 | 2026-12-06 21:13:37.820213+00:00 [info] <0.580.0> Importing concurrently 3 permissions... +rabbitmq-1 | 2026-12-06 21:13:37.835956+00:00 [info] <0.556.0> Successfully set permissions for user 'messenger_admin' in virtual host 'messenger' to '.*', '.*', '.*' +rabbitmq-1 | 2026-12-06 21:13:37.836990+00:00 [info] <0.558.0> Successfully set permissions for user 'messenger_consumer' in virtual host 'messenger' to '^$a', '^$a', '^attachment\.process\.v1$' +rabbitmq-1 | 2026-12-06 21:13:37.837187+00:00 [info] <0.557.0> Successfully set permissions for user 'messenger_producer' in virtual host 'messenger' to '^$a', '^amq\.default$', '^$a' +rabbitmq-1 | 2026-12-06 21:13:37.837850+00:00 [info] <0.580.0> Importing concurrently 2 queues... +rabbitmq-1 | 2026-12-06 21:13:37.912359+00:00 [info] <0.580.0> Ready to start client connection listeners +rabbitmq-1 | 2026-12-06 21:13:37.921642+00:00 [info] <0.754.0> started TLS (SSL) listener on [::]:5671 +rabbitmq-1 | completed with 3 plugins. +rabbitmq-1 | 2026-12-06 21:13:38.627544+00:00 [info] <0.580.0> Server startup complete; 3 plugins started. +rabbitmq-1 | 2026-12-06 21:13:38.627544+00:00 [info] <0.580.0> * rabbitmq_management +rabbitmq-1 | 2026-12-06 21:13:38.627544+00:00 [info] <0.580.0> * rabbitmq_management_agent +rabbitmq-1 | 2026-12-06 21:13:38.627544+00:00 [info] <0.580.0> * rabbitmq_web_dispatch +rabbitmq-1 | 2026-12-06 21:13:38.715549+00:00 [info] <0.10.0> Time to start RabbitMQ: 70800 ms +rabbitmq-1 | 2026-12-06 21:13:55.746681+00:00 [info] <0.767.0> accepting AMQP connection 172.22.0.14:43396 -> 172.22.0.4:5671 +rabbitmq-1 | 2026-12-06 21:13:55.815843+00:00 [info] <0.767.0> connection 172.22.0.14:43396 -> 172.22.0.4:5671: user 'messenger_consumer' authenticated and granted access to vhost 'messenger' diff --git a/evidence/grade3-clean-secret-audit.txt b/evidence/grade3-clean-secret-audit.txt new file mode 100644 index 00000000..c6caea75 --- /dev/null +++ b/evidence/grade3-clean-secret-audit.txt @@ -0,0 +1,5 @@ +Tracked files checked: 252 +Known credential patterns checked: 41 +PASS: no known local credentials in container logs +Failures: 0 +PASS: SECRET AUDIT diff --git a/evidence/grade3-clean-security.txt b/evidence/grade3-clean-security.txt new file mode 100644 index 00000000..d17e7bd9 --- /dev/null +++ b/evidence/grade3-clean-security.txt @@ -0,0 +1,2 @@ +python3 tests/security.py --base-url "https://localhost:18443" --ca-file "/home/casablanca/mtuci/high_load_apps/lab7verify.LJ40hS/certs/ca/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/grade3-clean-smoke.txt b/evidence/grade3-clean-smoke.txt new file mode 100644 index 00000000..0e711e93 --- /dev/null +++ b/evidence/grade3-clean-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:18443" --ca-file "/home/casablanca/mtuci/high_load_apps/lab7verify.LJ40hS/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-clean-startup-initial.txt b/evidence/grade3-clean-startup-initial.txt new file mode 100644 index 00000000..b87ab5cd --- /dev/null +++ b/evidence/grade3-clean-startup-initial.txt @@ -0,0 +1,142 @@ + Container lab7verify-openbao-1 Running + Volume lab7verify_tempo_data Creating + Volume lab7verify_tempo_data Creating + Container lab7verify-postgres-1 Creating + Volume lab7verify_prometheus_data Creating + Volume lab7verify_prometheus_data Creating + Volume lab7verify_grafana_data Creating + Volume lab7verify_grafana_data Creating + Volume lab7verify_loki_data Creating + Volume lab7verify_loki_data Creating + Volume lab7verify_rabbitmq_data Creating + Volume lab7verify_rabbitmq_data Creating + Volume lab7verify_redis_data Creating + Volume lab7verify_redis_data Creating + Volume lab7verify_s3_data Creating + Volume lab7verify_s3_data Creating + Volume lab7verify_redis_data Created + Volume lab7verify_redis_data Created + Container lab7verify-redis-1 Creating + Volume lab7verify_tempo_data Created + Volume lab7verify_tempo_data Created + Container lab7verify-tempo-1 Creating + Volume lab7verify_rabbitmq_data Created + Volume lab7verify_rabbitmq_data Created + Container lab7verify-rabbitmq-1 Creating + Volume lab7verify_loki_data Created + Volume lab7verify_loki_data Created + Container lab7verify-loki-1 Creating + Volume lab7verify_prometheus_data Created + Volume lab7verify_prometheus_data Created + Volume lab7verify_grafana_data Created + Volume lab7verify_grafana_data Created + Volume lab7verify_s3_data Created + Volume lab7verify_s3_data Created + Container lab7verify-s3-1 Creating + Container lab7verify-tempo-1 Created + Container lab7verify-tempo-proxy-1 Creating + Container lab7verify-loki-1 Created + Container lab7verify-loki-proxy-1 Creating + Container lab7verify-postgres-1 Created + Container lab7verify-migrate-1 Creating + Container lab7verify-redis-1 Created + Container lab7verify-s3-1 Created + Container lab7verify-s3-init-1 Creating + Container lab7verify-rabbitmq-1 Created + Container lab7verify-tempo-proxy-1 Created + Container lab7verify-loki-proxy-1 Created + Container lab7verify-otel-collector-1 Creating + Container lab7verify-migrate-1 Created + Container lab7verify-s3-init-1 Created + Container lab7verify-worker-1 Creating + Container lab7verify-api-2-1 Creating + Container lab7verify-api-1-1 Creating + Container lab7verify-dispatcher-1 Creating + Container lab7verify-api-1-1 Created + Container lab7verify-api-1-proxy-1 Creating + Container lab7verify-otel-collector-1 Created + Container lab7verify-otel-collector-proxy-1 Creating + Container lab7verify-worker-1 Created + Container lab7verify-api-2-1 Created + Container lab7verify-api-2-proxy-1 Creating + Container lab7verify-dispatcher-1 Created + Container lab7verify-api-1-proxy-1 Created + Container lab7verify-otel-collector-proxy-1 Created + Container lab7verify-prometheus-1 Creating + Container lab7verify-api-2-proxy-1 Created + Container lab7verify-nginx-1 Creating + Container lab7verify-prometheus-1 Created + Container lab7verify-grafana-1 Creating + Container lab7verify-nginx-1 Created + Container lab7verify-grafana-1 Created + Container lab7verify-loki-1 Starting + Container lab7verify-rabbitmq-1 Starting + Container lab7verify-postgres-1 Starting + Container lab7verify-redis-1 Starting + Container lab7verify-tempo-1 Starting + Container lab7verify-s3-1 Starting + Container lab7verify-loki-1 Started + Container lab7verify-loki-proxy-1 Starting + Container lab7verify-rabbitmq-1 Started + Container lab7verify-postgres-1 Started + Container lab7verify-postgres-1 Waiting + Container lab7verify-redis-1 Started + Container lab7verify-tempo-1 Started + Container lab7verify-tempo-proxy-1 Starting + Container lab7verify-s3-1 Started + Container lab7verify-s3-1 Waiting + Container lab7verify-loki-proxy-1 Started + Container lab7verify-tempo-proxy-1 Started + Container lab7verify-otel-collector-1 Starting + Container lab7verify-otel-collector-1 Started + Container lab7verify-otel-collector-proxy-1 Starting + Container lab7verify-otel-collector-proxy-1 Started + Container lab7verify-prometheus-1 Starting + Container lab7verify-prometheus-1 Started + Container lab7verify-grafana-1 Starting + Container lab7verify-grafana-1 Started + Container lab7verify-postgres-1 Healthy + Container lab7verify-migrate-1 Starting + Container lab7verify-migrate-1 Started + Container lab7verify-s3-1 Healthy + Container lab7verify-s3-init-1 Starting + Container lab7verify-s3-init-1 Started + Container lab7verify-s3-init-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-redis-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-redis-1 Waiting + Container lab7verify-rabbitmq-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-rabbitmq-1 Waiting + Container lab7verify-redis-1 Healthy + Container lab7verify-redis-1 Healthy + Container lab7verify-migrate-1 Exited + Container lab7verify-migrate-1 Exited + Container lab7verify-migrate-1 Exited + Container lab7verify-migrate-1 Exited + Container lab7verify-s3-init-1 Exited + Container lab7verify-s3-init-1 Exited + Container lab7verify-api-2-1 Starting + Container lab7verify-s3-init-1 Exited + Container lab7verify-api-1-1 Starting + Container lab7verify-s3-init-1 Exited + Container lab7verify-api-2-1 Started + Container lab7verify-api-2-1 Waiting + Container lab7verify-api-1-1 Started + Container lab7verify-api-1-1 Waiting + Container lab7verify-rabbitmq-1 Error dependency rabbitmq failed to start + Container lab7verify-api-2-1 Healthy + Container lab7verify-api-2-proxy-1 Starting + Container lab7verify-api-2-proxy-1 Started + Container lab7verify-api-1-1 Healthy + Container lab7verify-api-1-proxy-1 Starting + Container lab7verify-api-1-proxy-1 Started + Container lab7verify-rabbitmq-1 Healthy + Container lab7verify-worker-1 Starting + Container lab7verify-worker-1 Started +dependency failed to start: container lab7verify-rabbitmq-1 is unhealthy diff --git a/evidence/grade3-clean-startup-recovery.txt b/evidence/grade3-clean-startup-recovery.txt new file mode 100644 index 00000000..7b274605 --- /dev/null +++ b/evidence/grade3-clean-startup-recovery.txt @@ -0,0 +1,58 @@ + Container lab7verify-s3-1 Running + Container lab7verify-postgres-1 Running + Container lab7verify-worker-1 Running + Container lab7verify-api-1-1 Running + Container lab7verify-api-2-proxy-1 Running + Container lab7verify-grafana-1 Running + Container lab7verify-openbao-1 Running + Container lab7verify-loki-1 Running + Container lab7verify-otel-collector-1 Running + Container lab7verify-api-1-proxy-1 Running + Container lab7verify-rabbitmq-1 Running + Container lab7verify-tempo-proxy-1 Running + Container lab7verify-redis-1 Running + Container lab7verify-api-2-1 Running + Container lab7verify-loki-proxy-1 Running + Container lab7verify-prometheus-1 Running + Container lab7verify-otel-collector-proxy-1 Running + Container lab7verify-tempo-1 Running + Container lab7verify-postgres-1 Waiting + Container lab7verify-s3-1 Waiting + Container lab7verify-s3-1 Healthy + Container lab7verify-s3-init-1 Starting + Container lab7verify-postgres-1 Healthy + Container lab7verify-migrate-1 Starting + Container lab7verify-s3-init-1 Started + Container lab7verify-migrate-1 Started + Container lab7verify-rabbitmq-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-redis-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-rabbitmq-1 Waiting + Container lab7verify-migrate-1 Waiting + Container lab7verify-redis-1 Waiting + Container lab7verify-s3-init-1 Waiting + Container lab7verify-rabbitmq-1 Healthy + Container lab7verify-redis-1 Healthy + Container lab7verify-rabbitmq-1 Healthy + Container lab7verify-redis-1 Healthy + Container lab7verify-migrate-1 Exited + Container lab7verify-migrate-1 Exited + Container lab7verify-migrate-1 Exited + Container lab7verify-migrate-1 Exited + Container lab7verify-s3-init-1 Exited + Container lab7verify-dispatcher-1 Starting + Container lab7verify-s3-init-1 Exited + Container lab7verify-api-2-1 Waiting + Container lab7verify-s3-init-1 Exited + Container lab7verify-s3-init-1 Exited + Container lab7verify-api-1-1 Waiting + Container lab7verify-dispatcher-1 Started + Container lab7verify-api-2-1 Healthy + Container lab7verify-api-1-1 Healthy + Container lab7verify-nginx-1 Starting + Container lab7verify-nginx-1 Started diff --git a/evidence/grade3-collector-security.txt b/evidence/grade3-collector-security.txt new file mode 100644 index 00000000..219f175a --- /dev/null +++ b/evidence/grade3-collector-security.txt @@ -0,0 +1,35 @@ + Container mtusi2026lab7-migrate-run-d8c52b26da3c Creating + Container mtusi2026lab7-migrate-run-d8c52b26da3c Created +PASS: port 4318 verified TLS TLSv1.3 +PASS: port 4318 rejects untrusted CA +PASS: port 4318 rejects wrong hostname +PASS: port 8888 verified TLS TLSv1.3 +PASS: port 8888 rejects untrusted CA +PASS: port 8888 rejects wrong hostname +PASS: port 8889 verified TLS TLSv1.3 +PASS: port 8889 rejects untrusted CA +PASS: port 8889 rejects wrong hostname +PASS: direct port 4317 refused +PASS: direct port 18888 refused +PASS: direct port 18889 refused +PASS: anonymous ingestion denied: 401 +PASS: incorrect password denied: 401 +PASS: Prometheus cannot ingest telemetry: 401 +PASS: api can export logs: 200 +PASS: api can export traces: 200 +PASS: api can export metrics: 200 +PASS: worker can export logs: 200 +PASS: worker can export traces: 200 +PASS: worker can export metrics: 200 +PASS: dispatcher can export logs: 200 +PASS: dispatcher can export traces: 200 +PASS: dispatcher can export metrics: 200 +PASS: port 8888 anonymous scrape denied: 401 +PASS: port 8888 API scrape denied: 401 +PASS: port 8888 Prometheus scrape allowed: 200 +PASS: port 8889 anonymous scrape denied: 401 +PASS: port 8889 API scrape denied: 401 +PASS: port 8889 Prometheus scrape allowed: 200 +PASS: exported application metric found + +PASS: COLLECTOR SECURITY TESTS diff --git a/evidence/grade3-container-audit.txt b/evidence/grade3-container-audit.txt new file mode 100644 index 00000000..cdb542c7 --- /dev/null +++ b/evidence/grade3-container-audit.txt @@ -0,0 +1,302 @@ + +=== api-1 === +User: appuser +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== api-1-proxy === +User: image default +Privileged: False +Network mode: container:7f7103180cddd72011768505021c049347f502de1fda30f5ffde602de4779ec4 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 128 +CPU: 0.25 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== api-2 === +User: appuser +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== api-2-proxy === +User: image default +Privileged: False +Network mode: container:5e08fc73069e4eeb0fb548bb13fe41e7e81c18d0b380debe343f0f8281f36065 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 128 +CPU: 0.25 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== dispatcher === +User: appuser +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== grafana === +User: 472 +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 384 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {'3000/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '3000'}]} +PASS: basic isolation + +=== loki === +User: 10001 +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 512 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== loki-proxy === +User: image default +Privileged: False +Network mode: container:c087564403d5d41a46b15bec53b8e9222d725716357760efa59b9a2361cedf95 +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 128 +CPU: 0.25 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== nginx === +User: image default +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 256 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {'8443/tcp': [{'HostIp': '', 'HostPort': '8443'}]} +PASS: basic isolation + +=== openbao === +User: 100:1000 +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: None +Memory MiB: 256 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== otel-collector === +User: 10001 +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 256 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== otel-collector-proxy === +User: image default +Privileged: False +Network mode: container:0c53aa36c57ccc2aafab517e82254b0229bb7e16222c7806c8e5eca6181c53ef +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 128 +CPU: 0.25 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== postgres === +User: image default +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 768 +CPU: 1.0 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== prometheus === +User: nobody +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 512 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== rabbitmq === +User: image default +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 512 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== redis === +User: image default +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 256 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== s3 === +User: image default +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 512 +CPU: 1.0 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {'9001/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '9001'}]} +PASS: basic isolation + +=== tempo === +User: 10001:10001 +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 512 +CPU: 0.5 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== tempo-proxy === +User: image default +Privileged: False +Network mode: container:01a08214dbbf732856ec01ca21cf150116618aff376b6a283717e78a3c393d4b +PID mode: private +CapAdd: None +CapDrop: None +SecurityOpt: None +Memory MiB: 128 +CPU: 0.25 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +=== worker === +User: appuser +Privileged: False +Network mode: mtusi2026lab7_default +PID mode: private +CapAdd: None +CapDrop: ['ALL'] +SecurityOpt: ['no-new-privileges:true'] +Memory MiB: 512 +CPU: 1.0 +PidsLimit: None +ReadOnlyRootfs: False +Published ports: {} +PASS: basic isolation + +PASS: BASIC CONTAINER ISOLATION diff --git a/evidence/grade3-container-resources.txt b/evidence/grade3-container-resources.txt new file mode 100644 index 00000000..e9d41bab --- /dev/null +++ b/evidence/grade3-container-resources.txt @@ -0,0 +1,21 @@ +NAME CPU % MEM USAGE / LIMIT MEM % PIDS +mtusi2026lab7-api-1-1 0.24% 99.54MiB / 512MiB 19.44% 5 +mtusi2026lab7-api-1-proxy-1 0.00% 2.836MiB / 128MiB 2.22% 2 +mtusi2026lab7-api-2-1 0.27% 112.1MiB / 512MiB 21.89% 5 +mtusi2026lab7-api-2-proxy-1 0.00% 2.863MiB / 128MiB 2.24% 2 +mtusi2026lab7-dispatcher-1 2.26% 70.78MiB / 512MiB 13.82% 5 +mtusi2026lab7-grafana-1 2.02% 94.68MiB / 384MiB 24.66% 24 +mtusi2026lab7-loki-1 0.83% 87.53MiB / 512MiB 17.10% 24 +mtusi2026lab7-loki-proxy-1 0.00% 3MiB / 128MiB 2.34% 2 +mtusi2026lab7-nginx-1 0.00% 5.281MiB / 256MiB 2.06% 2 +mtusi2026lab7-openbao-1 0.78% 24.82MiB / 256MiB 9.69% 22 +mtusi2026lab7-otel-collector-1 1.75% 66.88MiB / 256MiB 26.12% 25 +mtusi2026lab7-otel-collector-proxy-1 0.54% 2.973MiB / 128MiB 2.32% 2 +mtusi2026lab7-postgres-1 12.53% 63.57MiB / 768MiB 8.28% 10 +mtusi2026lab7-prometheus-1 0.62% 51.3MiB / 512MiB 10.02% 11 +mtusi2026lab7-rabbitmq-1 0.31% 110.5MiB / 512MiB 21.58% 62 +mtusi2026lab7-redis-1 0.48% 18.25MiB / 256MiB 7.13% 6 +mtusi2026lab7-s3-1 0.11% 126.8MiB / 512MiB 24.76% 24 +mtusi2026lab7-tempo-1 0.07% 266.4MiB / 512MiB 52.03% 25 +mtusi2026lab7-tempo-proxy-1 0.00% 3.133MiB / 128MiB 2.45% 2 +mtusi2026lab7-worker-1 0.00% 82.73MiB / 512MiB 16.16% 5 diff --git a/evidence/grade3-data-security.txt b/evidence/grade3-data-security.txt new file mode 100644 index 00000000..54bbf16f --- /dev/null +++ b/evidence/grade3-data-security.txt @@ -0,0 +1,30 @@ + Container mtusi2026lab7-migrate-run-0b87b5e051c6 Creating + Container mtusi2026lab7-migrate-run-0b87b5e051c6 Created + +========== POSTGRESQL ========== +PASS: api: messenger_api, TLSv1.3 +PASS: api cannot create tables: InsufficientPrivilegeError +PASS: api: plaintext rejected: InvalidAuthorizationSpecificationError +PASS: api: untrusted CA rejected: SSLCertVerificationError +PASS: api: wrong hostname rejected: SSLCertVerificationError +PASS: worker: messenger_worker, TLSv1.3 +PASS: worker cannot read users: InsufficientPrivilegeError +PASS: worker cannot create tables: InsufficientPrivilegeError +PASS: worker: plaintext rejected: InvalidAuthorizationSpecificationError +PASS: worker: untrusted CA rejected: SSLCertVerificationError +PASS: worker: wrong hostname rejected: SSLCertVerificationError +PASS: dispatcher: messenger_dispatcher, TLSv1.3 +PASS: dispatcher cannot read users: InsufficientPrivilegeError +PASS: dispatcher cannot create tables: InsufficientPrivilegeError +PASS: dispatcher: plaintext rejected: InvalidAuthorizationSpecificationError +PASS: dispatcher: untrusted CA rejected: SSLCertVerificationError +PASS: dispatcher: wrong hostname rejected: SSLCertVerificationError + +========== REDIS ========== +PASS: verified Redis TLS +PASS: session operations +PASS: rate limiter Lua and TTL +PASS: forbidden Redis key: NoPermissionError +PASS: forbidden Redis admin command: NoPermissionError + +PASS: DATA SECURITY TESTS diff --git a/evidence/grade3-dependency-audit.txt b/evidence/grade3-dependency-audit.txt new file mode 100644 index 00000000..5c418afc --- /dev/null +++ b/evidence/grade3-dependency-audit.txt @@ -0,0 +1 @@ +No known vulnerabilities found diff --git a/evidence/grade3-failover-first-containers.txt b/evidence/grade3-failover-first-containers.txt new file mode 100644 index 00000000..d8d7a594 --- /dev/null +++ b/evidence/grade3-failover-first-containers.txt @@ -0,0 +1,6 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api-1-1 mtusi2026lab7-api-1 "python /app/scripts…" api-1 2 hours ago Exited (0) 18 seconds ago +mtusi2026lab7-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 2 hours ago Exited (0) 19 seconds ago +mtusi2026lab7-api-2-1 mtusi2026lab7-api-2 "python /app/scripts…" api-2 2 hours ago Up 2 minutes (healthy) 8080/tcp +mtusi2026lab7-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 2 hours ago Up About a minute +mtusi2026lab7-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 2 hours ago Up About a minute 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp diff --git a/evidence/grade3-failover-first-health.txt b/evidence/grade3-failover-first-health.txt new file mode 100644 index 00000000..01290adb --- /dev/null +++ b/evidence/grade3-failover-first-health.txt @@ -0,0 +1,10 @@ +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-2 diff --git a/evidence/grade3-failover-first-recovered-containers.txt b/evidence/grade3-failover-first-recovered-containers.txt new file mode 100644 index 00000000..bb2db2b3 --- /dev/null +++ b/evidence/grade3-failover-first-recovered-containers.txt @@ -0,0 +1,6 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api-1-1 mtusi2026lab7-api-1 "python /app/scripts…" api-1 2 hours ago Up About a minute (healthy) 8080/tcp +mtusi2026lab7-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 2 hours ago Up About a minute +mtusi2026lab7-api-2-1 mtusi2026lab7-api-2 "python /app/scripts…" api-2 2 hours ago Up 3 minutes (healthy) 8080/tcp +mtusi2026lab7-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 2 hours ago Up 3 minutes +mtusi2026lab7-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 2 hours ago Up 3 minutes 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp diff --git a/evidence/grade3-failover-first-recovery.txt b/evidence/grade3-failover-first-recovery.txt new file mode 100644 index 00000000..b1af39ee --- /dev/null +++ b/evidence/grade3-failover-first-recovery.txt @@ -0,0 +1,10 @@ +x-instance-id: api-2 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 diff --git a/evidence/grade3-failover-first.txt b/evidence/grade3-failover-first.txt new file mode 100644 index 00000000..c8d6ee9b --- /dev/null +++ b/evidence/grade3-failover-first.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 91, "failed_attempts": 2, "first_recovery_seconds": 2.157} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/grade3-failover-openbao-recovery.txt b/evidence/grade3-failover-openbao-recovery.txt new file mode 100644 index 00000000..97873994 --- /dev/null +++ b/evidence/grade3-failover-openbao-recovery.txt @@ -0,0 +1,2 @@ +api-1-1 | PASS: OpenBao identity=bao-api-1, role=api, secrets=5 +api-1-1 | PASS: OpenBao identity=bao-api-1, role=api, secrets=5 diff --git a/evidence/grade3-failover-second-containers.txt b/evidence/grade3-failover-second-containers.txt new file mode 100644 index 00000000..3e0f994e --- /dev/null +++ b/evidence/grade3-failover-second-containers.txt @@ -0,0 +1,6 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api-1-1 mtusi2026lab7-api-1 "python /app/scripts…" api-1 2 hours ago Up 2 minutes (healthy) 8080/tcp +mtusi2026lab7-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 2 hours ago Up 2 minutes +mtusi2026lab7-api-2-1 mtusi2026lab7-api-2 "python /app/scripts…" api-2 2 hours ago Exited (0) 23 seconds ago +mtusi2026lab7-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 2 hours ago Exited (0) 24 seconds ago +mtusi2026lab7-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 2 hours ago Up 4 minutes 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp diff --git a/evidence/grade3-failover-second-health.txt b/evidence/grade3-failover-second-health.txt new file mode 100644 index 00000000..6e9c9e77 --- /dev/null +++ b/evidence/grade3-failover-second-health.txt @@ -0,0 +1,10 @@ +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-1 diff --git a/evidence/grade3-failover-second-recovered-containers.txt b/evidence/grade3-failover-second-recovered-containers.txt new file mode 100644 index 00000000..d98bd107 --- /dev/null +++ b/evidence/grade3-failover-second-recovered-containers.txt @@ -0,0 +1,6 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api-1-1 mtusi2026lab7-api-1 "python /app/scripts…" api-1 2 hours ago Up 2 minutes (healthy) 8080/tcp +mtusi2026lab7-api-1-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-1-proxy 2 hours ago Up 2 minutes +mtusi2026lab7-api-2-1 mtusi2026lab7-api-2 "python /app/scripts…" api-2 2 hours ago Up 17 seconds (healthy) 8080/tcp +mtusi2026lab7-api-2-proxy-1 nginx:1.29-alpine "nginx -g 'daemon of…" api-2-proxy 2 hours ago Up 10 seconds +mtusi2026lab7-nginx-1 nginx:1.29-alpine "/docker-entrypoint.…" nginx 2 hours ago Up 4 minutes 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp diff --git a/evidence/grade3-failover-second-recovery.txt b/evidence/grade3-failover-second-recovery.txt new file mode 100644 index 00000000..14f8b475 --- /dev/null +++ b/evidence/grade3-failover-second-recovery.txt @@ -0,0 +1,10 @@ +x-instance-id: api-1 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 +x-instance-id: api-2 +x-instance-id: api-1 diff --git a/evidence/grade3-failover-second.txt b/evidence/grade3-failover-second.txt new file mode 100644 index 00000000..e3b686fc --- /dev/null +++ b/evidence/grade3-failover-second.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 93, "failed_attempts": 2, "first_recovery_seconds": 2.12} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/grade3-final-build.txt b/evidence/grade3-final-build.txt new file mode 100644 index 00000000..3b5d31d6 --- /dev/null +++ b/evidence/grade3-final-build.txt @@ -0,0 +1,129 @@ + Image mtusi2026lab7-api-1 Building + Image mtusi2026lab7-migrate Building + Image mtusi2026lab7-api-2 Building + Image mtusi2026lab7-worker Building + Image mtusi2026lab7-dispatcher Building +#1 [internal] load local bake definitions +#1 reading from stdin 2.49kB done +#1 DONE 0.0s + +#2 [worker internal] load build definition from Dockerfile +#2 transferring dockerfile: 660B 0.0s done +#2 DONE 0.0s + +#3 [migrate internal] load metadata for docker.io/library/python:3.13.15-slim +#3 DONE 2.0s + +#4 [dispatcher internal] load .dockerignore +#4 transferring context: 293B done +#4 DONE 0.0s + +#5 [dispatcher 1/10] FROM docker.io/library/python:3.13.15-slim@sha256:7c61056e61ac89e852de05f3dc6fa51a6dd2181797bceed46aa725dd7cb2cd3b +#5 resolve docker.io/library/python:3.13.15-slim@sha256:7c61056e61ac89e852de05f3dc6fa51a6dd2181797bceed46aa725dd7cb2cd3b 0.0s done +#5 DONE 0.1s + +#6 [worker internal] load build context +#6 transferring context: 9.61kB 0.0s done +#6 DONE 0.0s + +#7 [api-1 2/10] WORKDIR /app +#7 CACHED + +#8 [api-1 3/10] COPY requirements.txt . +#8 CACHED + +#9 [api-1 4/10] RUN pip install --no-cache-dir -r requirements.txt +#9 CACHED + +#10 [api-1 5/10] COPY alembic.ini . +#10 CACHED + +#11 [api-1 6/10] COPY migrations ./migrations +#11 CACHED + +#12 [api-2 7/10] COPY src ./src +#12 CACHED + +#13 [worker 8/10] COPY scripts ./scripts +#13 DONE 0.1s + +#14 [api-1 9/10] COPY tests ./tests +#14 DONE 0.1s + +#15 [api-1 10/10] RUN useradd --create-home --uid 10001 appuser +#15 DONE 0.8s + +#16 [worker] exporting to image +#16 exporting layers +#16 exporting layers 0.3s done +#16 exporting manifest sha256:57da61227e1ecf4d805a0c19c68dfbba70117edbb1bc2b5b3d1ceca06916ff0e 0.1s done +#16 exporting config sha256:c084e3743dd65e261c52ee1e37b51bd256556388a0340ed99606c4ae1e179376 +#16 exporting config sha256:c084e3743dd65e261c52ee1e37b51bd256556388a0340ed99606c4ae1e179376 0.2s done +#16 exporting attestation manifest sha256:f13637e52f102f32a07a12a571de167a5f3831d7795a123168c972d681b79e17 +#16 exporting attestation manifest sha256:f13637e52f102f32a07a12a571de167a5f3831d7795a123168c972d681b79e17 0.1s done +#16 exporting manifest list sha256:346f8a438f8e84965609945d458547b59258d7ac307ad1083d769385fe73130c +#16 exporting manifest list sha256:346f8a438f8e84965609945d458547b59258d7ac307ad1083d769385fe73130c 0.1s done +#16 naming to docker.io/library/mtusi2026lab7-worker:latest 0.0s done +#16 unpacking to docker.io/library/mtusi2026lab7-worker:latest +#16 unpacking to docker.io/library/mtusi2026lab7-worker:latest 0.3s done +#16 DONE 1.4s + +#17 [api-2] exporting to image +#17 exporting layers 0.4s done +#17 exporting manifest sha256:86bcc5087408adf700ddbcccf6a0cec58cd7210ba498b587ba837f97ca3af7dd 0.2s done +#17 exporting config sha256:680f3dd42c308cb4826e24574c8e12fee39538852d2ffe941c57dc8cc6303c88 0.1s done +#17 exporting attestation manifest sha256:778406fff97507614641e8b28305ad86037f3534f294e8b950ddc0edbe6e279d 0.1s done +#17 exporting manifest list sha256:192e88c2b5631ff56a1774005fc5e8e2c650a01908c4d9e0bbdb8152b25fa95c 0.1s done +#17 naming to docker.io/library/mtusi2026lab7-api-2:latest 0.0s done +#17 unpacking to docker.io/library/mtusi2026lab7-api-2:latest 0.3s done +#17 DONE 1.5s + +#18 [api-1] exporting to image +#18 exporting layers 0.3s done +#18 exporting manifest sha256:074f02b0137e876caf153034c46ff3a54318878c828b27fae5acbc444efe16b9 0.1s done +#18 exporting config sha256:3405669c36ea67c951800f342978d2d4bd032e7a63efefcd974b019fb48a29c1 0.2s done +#18 exporting attestation manifest sha256:5b1ceffef34ca286f266a3cf6b7b3627d9cfb3a6209d63678ef85db5814a491d 0.1s done +#18 exporting manifest list sha256:42f8ebf96924ba41bad2097862a262b2620d12ec980efcba0ff84bfbd33f48d7 0.1s done +#18 naming to docker.io/library/mtusi2026lab7-api-1:latest 0.0s done +#18 unpacking to docker.io/library/mtusi2026lab7-api-1:latest 0.3s done +#18 DONE 1.4s + +#19 [migrate] exporting to image +#19 exporting layers 0.4s done +#19 exporting manifest sha256:3475d2b3d1bdcb55bb3635f58353022e1209c00ea9a2d940d0911a8ae7904cb1 0.1s done +#19 exporting config sha256:1fbd8585173ea8bf85eda2afe131100632aa9a289e5a358db1918223498d3103 0.1s done +#19 exporting attestation manifest sha256:d9cfa255dbdb9fe47e228771e5675c56c6ecd7f0b3f4c0e1c5fc44b934c63a8f 0.2s done +#19 exporting manifest list sha256:69cbf10042e8cc50e02942d130847c9530441d21b6f38a3ec58b2725e006a161 0.1s done +#19 naming to docker.io/library/mtusi2026lab7-migrate:latest 0.0s done +#19 unpacking to docker.io/library/mtusi2026lab7-migrate:latest 0.3s done +#19 DONE 1.5s + +#20 [dispatcher] exporting to image +#20 exporting layers 0.4s done +#20 exporting manifest sha256:77328d4ee1e68831cd0b1d36b6153deb9065a23d4eda667ba9199e6ffd82d357 0.1s done +#20 exporting config sha256:0ea05504378dce397bca797f9201b1032eb9663b449e8050aa40ef85398f81f6 0.2s done +#20 exporting attestation manifest sha256:fea160c4b6cc06187f11acaba9f52e1e4d550d60b61a7f099d7cb35514eb2d2f 0.1s done +#20 exporting manifest list sha256:8e07f366d108e6106eeb77937c8ba4014012230c363fb76398b0b66f6df33c19 0.1s done +#20 naming to docker.io/library/mtusi2026lab7-dispatcher:latest 0.0s done +#20 unpacking to docker.io/library/mtusi2026lab7-dispatcher:latest 0.3s done +#20 DONE 1.5s + +#21 [worker] resolving provenance for metadata file +#21 DONE 0.4s + +#22 [api-1] resolving provenance for metadata file +#22 DONE 0.4s + +#23 [migrate] resolving provenance for metadata file +#23 DONE 0.3s + +#24 [dispatcher] resolving provenance for metadata file +#24 DONE 0.2s + +#25 [api-2] resolving provenance for metadata file +#25 DONE 0.0s + Image mtusi2026lab7-dispatcher Built + Image mtusi2026lab7-api-2 Built + Image mtusi2026lab7-migrate Built + Image mtusi2026lab7-api-1 Built + Image mtusi2026lab7-worker Built diff --git a/evidence/grade3-final-secret-audit.txt b/evidence/grade3-final-secret-audit.txt new file mode 100644 index 00000000..05549a45 --- /dev/null +++ b/evidence/grade3-final-secret-audit.txt @@ -0,0 +1,5 @@ +Tracked files checked: 253 +Known credential patterns checked: 44 +PASS: no known local credentials in container logs +Failures: 0 +PASS: SECRET AUDIT diff --git a/evidence/grade3-grafana-security.txt b/evidence/grade3-grafana-security.txt new file mode 100644 index 00000000..68d53a0c --- /dev/null +++ b/evidence/grade3-grafana-security.txt @@ -0,0 +1,17 @@ +PASS: Grafana HTTPS health +HTTP 401: /api/datasources +Response: {"extra":null,"message":"Unauthorized","messageId":"auth.unauthorized","statusCode":401,"traceID":""} + +PASS: anonymous datasource access denied +PASS: prometheus HTTPS and CA verification configured +Datasource prometheus: HTTP 200, status=OK, message=Successfully queried the Prometheus API. +PASS: Grafana -> prometheus connection +PASS: loki HTTPS and CA verification configured +Datasource loki: HTTP 200, status=OK, message=Data source successfully connected. +PASS: Grafana -> loki connection +PASS: tempo HTTPS and CA verification configured +PASS: Tempo returned 4 traces +PASS: trace ID: c83d351542b44438ff595fc6e782bec +PASS: Grafana -> tempo connection + +PASS: GRAFANA SECURITY TESTS diff --git a/evidence/grade3-hardening-config.txt b/evidence/grade3-hardening-config.txt new file mode 100644 index 00000000..0adcb27c --- /dev/null +++ b/evidence/grade3-hardening-config.txt @@ -0,0 +1,23 @@ +api-1: pids_limit=256, no-new-privileges=True, PASS +api-1-proxy: pids_limit=256, no-new-privileges=True, PASS +api-2: pids_limit=256, no-new-privileges=True, PASS +api-2-proxy: pids_limit=256, no-new-privileges=True, PASS +dispatcher: pids_limit=256, no-new-privileges=True, PASS +grafana: pids_limit=256, no-new-privileges=True, PASS +loki: pids_limit=256, no-new-privileges=True, PASS +loki-proxy: pids_limit=256, no-new-privileges=True, PASS +migrate: pids_limit=256, no-new-privileges=True, PASS +nginx: pids_limit=256, no-new-privileges=True, PASS +openbao: pids_limit=256, no-new-privileges=True, PASS +otel-collector: pids_limit=256, no-new-privileges=True, PASS +otel-collector-proxy: pids_limit=256, no-new-privileges=True, PASS +postgres: pids_limit=256, no-new-privileges=True, PASS +prometheus: pids_limit=256, no-new-privileges=True, PASS +rabbitmq: pids_limit=256, no-new-privileges=True, PASS +redis: pids_limit=256, no-new-privileges=True, PASS +s3: pids_limit=256, no-new-privileges=True, PASS +s3-init: pids_limit=256, no-new-privileges=True, PASS +tempo: pids_limit=256, no-new-privileges=True, PASS +tempo-proxy: pids_limit=256, no-new-privileges=True, PASS +worker: pids_limit=256, no-new-privileges=True, PASS +PASS: ALL SERVICES HARDENING CONFIGURATION diff --git a/evidence/grade3-hardening-runtime.txt b/evidence/grade3-hardening-runtime.txt new file mode 100644 index 00000000..278fff00 --- /dev/null +++ b/evidence/grade3-hardening-runtime.txt @@ -0,0 +1,24 @@ +PASS: api-1, pids_limit=256, no-new-privileges=true, state=running +PASS: api-1-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: api-2, pids_limit=256, no-new-privileges=true, state=running +PASS: api-2-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: dispatcher, pids_limit=256, no-new-privileges=true, state=running +PASS: grafana, pids_limit=256, no-new-privileges=true, state=running +PASS: loki, pids_limit=256, no-new-privileges=true, state=running +PASS: loki-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: migrate, pids_limit=256, no-new-privileges=true, state=exited +PASS: nginx, pids_limit=256, no-new-privileges=true, state=running +PASS: openbao, pids_limit=256, no-new-privileges=true, state=running +PASS: otel-collector, pids_limit=256, no-new-privileges=true, state=running +PASS: otel-collector-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: postgres, pids_limit=256, no-new-privileges=true, state=running +PASS: prometheus, pids_limit=256, no-new-privileges=true, state=running +PASS: rabbitmq, pids_limit=256, no-new-privileges=true, state=running +PASS: redis, pids_limit=256, no-new-privileges=true, state=running +PASS: s3, pids_limit=256, no-new-privileges=true, state=running +PASS: s3-init, pids_limit=256, no-new-privileges=true, state=exited +PASS: tempo, pids_limit=256, no-new-privileges=true, state=running +PASS: tempo-proxy, pids_limit=256, no-new-privileges=true, state=running +PASS: worker, pids_limit=256, no-new-privileges=true, state=running + +PASS: ALL 22 CONTAINERS HARDENED diff --git a/evidence/grade3-image-audit-initial-failure.txt b/evidence/grade3-image-audit-initial-failure.txt new file mode 100644 index 00000000..592652bd --- /dev/null +++ b/evidence/grade3-image-audit-initial-failure.txt @@ -0,0 +1,23 @@ +=== DOCKER IMAGE SECRET AUDIT === +Services: 5 +Unique images: 5 +Credential patterns: 44 + +Inspecting: api-1 +Error response from daemon: No such image: sha256:da38bc523597c5013a9fcc31fc59831737c97cb688035c0bc1b48fc46c81d4ab +Traceback (most recent call last): + File "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/student-tests/audit_images.py", line 101, in + command("docker", "image", "inspect", image), + ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/student-tests/audit_images.py", line 37, in command + return subprocess.check_output(args) + ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^ + File "/usr/lib/python3.13/subprocess.py", line 472, in check_output + return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, + ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + **kwargs).stdout + ^^^^^^^^^ + File "/usr/lib/python3.13/subprocess.py", line 577, in run + raise CalledProcessError(retcode, process.args, + output=stdout, stderr=stderr) +subprocess.CalledProcessError: Command '('docker', 'image', 'inspect', 'sha256:da38bc523597c5013a9fcc31fc59831737c97cb688035c0bc1b48fc46c81d4ab')' returned non-zero exit status 1. diff --git a/evidence/grade3-image-audit.txt b/evidence/grade3-image-audit.txt new file mode 100644 index 00000000..6c408f5d --- /dev/null +++ b/evidence/grade3-image-audit.txt @@ -0,0 +1,10 @@ +=== api-1 === +PASS: no local secret paths in application image +=== api-2 === +PASS: no local secret paths in application image +=== worker === +PASS: no local secret paths in application image +=== dispatcher === +PASS: no local secret paths in application image +=== migrate === +PASS: no local secret paths in application image diff --git a/evidence/grade3-image-content-audit.txt b/evidence/grade3-image-content-audit.txt new file mode 100644 index 00000000..a38e7dd9 --- /dev/null +++ b/evidence/grade3-image-content-audit.txt @@ -0,0 +1,46 @@ +Selected: api-1: mtusi2026lab7-api-1: sha256:42f8ebf96924ba41bad2097862a262b2620d12ec980efcba0ff84bfbd33f48d7 +Selected: api-2: mtusi2026lab7-api-2: sha256:192e88c2b5631ff56a1774005fc5e8e2c650a01908c4d9e0bbdb8152b25fa95c +Selected: worker: mtusi2026lab7-worker: sha256:346f8a438f8e84965609945d458547b59258d7ac307ad1083d769385fe73130c +Selected: dispatcher: mtusi2026lab7-dispatcher: sha256:8e07f366d108e6106eeb77937c8ba4014012230c363fb76398b0b66f6df33c19 +Selected: migrate: mtusi2026lab7-migrate: sha256:69cbf10042e8cc50e02942d130847c9530441d21b6f38a3ec58b2725e006a161 +=== DOCKER IMAGE SECRET AUDIT === +Services: 5 +Unique images: 5 +Credential patterns: 44 + +Inspecting: api-1 +Layers checked: 1 | Files checked: 2677 +Layers checked: 2 | Files checked: 2881 +Layers checked: 3 | Files checked: 4474 +Layers checked: 4 | Files checked: 4474 +Layers checked: 5 | Files checked: 4474 +Layers checked: 6 | Files checked: 4475 +Layers checked: 7 | Files checked: 10741 +Layers checked: 8 | Files checked: 10742 +Layers checked: 9 | Files checked: 10756 +Layers checked: 10 | Files checked: 10773 +Layers checked: 11 | Files checked: 10795 +Layers checked: 12 | Files checked: 10804 +Layers checked: 13 | Files checked: 10819 +Completed: api-1 + +Inspecting: api-2 +Completed: api-2 + +Inspecting: worker +Completed: worker + +Inspecting: dispatcher +Completed: dispatcher + +Inspecting: migrate +Completed: migrate + +=== SUMMARY === +Services inspected: 5 +Unique images inspected: 5 +Unique layers inspected: 13 +Layer files inspected: 10819 +Credential patterns: 44 +Failures: 0 +PASS: DOCKER IMAGE SECRET AUDIT diff --git a/evidence/grade3-loki-secret-audit-final.txt b/evidence/grade3-loki-secret-audit-final.txt new file mode 100644 index 00000000..ce17ab32 --- /dev/null +++ b/evidence/grade3-loki-secret-audit-final.txt @@ -0,0 +1,11 @@ +=== TELEMETRY SECRET AUDIT === +Audit window: 7 days +Credential patterns: 46 +TLS CA and hostname verification: enabled + +=== Loki === +Loki services inspected: 3 +Loki log records inspected: 3377 +PASS: Loki scan completed +Failures: 0 +PASS: TELEMETRY SECRET AUDIT: loki diff --git a/evidence/grade3-loki-secret-audit.txt b/evidence/grade3-loki-secret-audit.txt new file mode 100644 index 00000000..24e37f43 --- /dev/null +++ b/evidence/grade3-loki-secret-audit.txt @@ -0,0 +1,10 @@ +=== TELEMETRY SECRET AUDIT === +Audit window: 7 days +Credential patterns: 46 +TLS CA and hostname verification: enabled + +=== Loki === +Loki services inspected: 3 +Loki log records inspected: 3108 +PASS: Loki scan completed + diff --git a/evidence/grade3-messaging-storage-config.txt b/evidence/grade3-messaging-storage-config.txt new file mode 100644 index 00000000..1a04b282 --- /dev/null +++ b/evidence/grade3-messaging-storage-config.txt @@ -0,0 +1,33 @@ +========== RABBITMQ FINAL LISTENERS ========== +Interface: [::], port: 15671, protocol: https, purpose: HTTP API over TLS (HTTPS) +Interface: [::], port: 25672, protocol: clustering, purpose: inter-node and CLI tool communication +Interface: [::], port: 5671, protocol: amqp/ssl, purpose: AMQP 0-9-1 and AMQP 1.0 over TLS +========== MINIO CERTIFICATE ========== +subject=CN = s3 +notBefore=Dec 6 14:56:00 2026 GMT +notAfter=Mar 6 14:56:00 2027 GMT +X509v3 Subject Alternative Name: + DNS:s3, DNS:localhost, IP Address:127.0.0.1 +========== MINIO INITIALIZATION ========== +s3-init-1 | Added `local` successfully. +s3-init-1 | Bucket created successfully `local/messenger-attachments`. +s3-init-1 | Access permission for `local/messenger-attachments` is set to `private` +s3-init-1 | Created policy `messenger-api` successfully. +s3-init-1 | Added user `[REDACTED_S3_API_ACCESS_KEY_ID]` successfully. +s3-init-1 | Attached Policies: [messenger-api] +s3-init-1 | To User: [REDACTED_S3_API_ACCESS_KEY_ID] +s3-init-1 | PASS: MinIO api identity configured +s3-init-1 | Created policy `messenger-worker` successfully. +s3-init-1 | Added user `[REDACTED_S3_WORKER_ACCESS_KEY_ID]` successfully. +s3-init-1 | Attached Policies: [messenger-worker] +s3-init-1 | To User: [REDACTED_S3_WORKER_ACCESS_KEY_ID] +s3-init-1 | PASS: MinIO worker identity configured +s3-init-1 | PASS: MinIO HTTPS initialization complete +========== SERVICE STATUS ========== +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-migrate-1 mtusi2026lab7-migrate "alembic upgrade head" migrate 36 minutes ago Exited (0) 36 minutes ago +mtusi2026lab7-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 39 minutes ago Up 39 minutes (healthy) 5432/tcp +mtusi2026lab7-rabbitmq-1 rabbitmq:4.1.4-management-alpine "docker-entrypoint.s…" rabbitmq 5 minutes ago Up 5 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15671-15672/tcp, 15691-15692/tcp, 25672/tcp +mtusi2026lab7-redis-1 redis:8.2.2 "docker-entrypoint.s…" redis 39 minutes ago Up 39 minutes (healthy) 6379/tcp +mtusi2026lab7-s3-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/usr/bin/docker-ent…" s3 About a minute ago Up About a minute (healthy) 127.0.0.1:9001->9001/tcp +mtusi2026lab7-s3-init-1 dappros/minio:RELEASE.2025-09-07T16-13-09Z "/bin/sh /config/ini…" s3-init About a minute ago Exited (0) About a minute ago diff --git a/evidence/grade3-minio-init-sanitized.txt b/evidence/grade3-minio-init-sanitized.txt new file mode 100644 index 00000000..b18659a2 --- /dev/null +++ b/evidence/grade3-minio-init-sanitized.txt @@ -0,0 +1,8 @@ +s3-init-1 | Added `local` successfully. +s3-init-1 | Bucket created successfully `local/messenger-attachments`. +s3-init-1 | Access permission for `local/messenger-attachments` is set to `private` +s3-init-1 | Created policy `messenger-api` successfully. +s3-init-1 | PASS: MinIO api identity configured +s3-init-1 | Created policy `messenger-worker` successfully. +s3-init-1 | PASS: MinIO worker identity configured +s3-init-1 | PASS: MinIO HTTPS initialization complete diff --git a/evidence/grade3-minio-security.txt b/evidence/grade3-minio-security.txt new file mode 100644 index 00000000..553c0c1c --- /dev/null +++ b/evidence/grade3-minio-security.txt @@ -0,0 +1,33 @@ + Container mtusi2026lab7-migrate-run-b51d03364501 Creating + Container mtusi2026lab7-migrate-run-b51d03364501 Created +PASS: verified MinIO TLS: TLSv1.3 +PASS: untrusted CA rejected +PASS: wrong hostname rejected +PASS: API can access bucket +PASS: API can write staging +PASS: API can read staging +PASS: worker can read staging +PASS: worker can write attachments +PASS: worker can write variants +PASS: API can read attachments +PASS: API can read variants +PASS: API cannot write attachments: HTTP 403 +PASS: API cannot write variants: HTTP 403 +PASS: worker cannot write staging: HTTP 403 +PASS: worker cannot delete staging: HTTP 403 +PASS: worker cannot read attachments: HTTP 403 +PASS: worker cannot read variants: HTTP 403 +PASS: API cannot delete final object: HTTP 403 +PASS: API cannot delete final object: HTTP 403 +PASS: API cannot create bucket: HTTP 403 +PASS: API bucket listing restricted: ['messenger-attachments'] +PASS: worker cannot delete final object: HTTP 403 +PASS: worker cannot delete final object: HTTP 403 +PASS: worker cannot create bucket: HTTP 403 +PASS: worker bucket listing denied +PASS: API can delete staging +PASS: anonymous access denied +PASS: anonymous access denied +TEST_PREFIX=security-test-366b32bd9f664ed9ac429179e6b5578e + +PASS: MINIO SECURITY TESTS diff --git a/evidence/grade3-mtls-security.txt b/evidence/grade3-mtls-security.txt new file mode 100644 index 00000000..9bd55da2 --- /dev/null +++ b/evidence/grade3-mtls-security.txt @@ -0,0 +1,18 @@ + Container mtusi2026lab7-migrate-run-e25e06b1eb40 Creating + Container mtusi2026lab7-migrate-run-e25e06b1eb40 Created + +=== api-1 === +PASS: authorized LB certificate +PASS: missing client certificate: HTTP 400 +PASS: untrusted client certificate: HTTP 400 +PASS: wrong trusted identity: HTTP 403 +PASS: direct HTTP bypass rejected + +=== api-2 === +PASS: authorized LB certificate +PASS: missing client certificate: HTTP 400 +PASS: untrusted client certificate: HTTP 400 +PASS: wrong trusted identity: HTTP 403 +PASS: direct HTTP bypass rejected + +PASS: ALL MTLS SECURITY TESTS diff --git a/evidence/grade3-network-audit-final.txt b/evidence/grade3-network-audit-final.txt new file mode 100644 index 00000000..ee2d9fa9 --- /dev/null +++ b/evidence/grade3-network-audit-final.txt @@ -0,0 +1,79 @@ + Container mtusi2026lab7-migrate-run-fad02d630461 Creating + Container mtusi2026lab7-migrate-run-fad02d630461 Created + +=== nginx === +80: CLOSED +443: CLOSED +8080: CLOSED +8443: OPEN + +=== api-1 === +8080: CLOSED +8443: OPEN + +=== api-2 === +8080: CLOSED +8443: OPEN + +=== worker === +8080: CLOSED + +=== dispatcher === +8080: CLOSED + +=== postgres === +5432: OPEN + +=== redis === +6379: OPEN + +=== rabbitmq === +4369: CLOSED +5671: OPEN +5672: CLOSED +15671: OPEN +15672: CLOSED +15691: CLOSED +15692: CLOSED +25672: CLOSED + +=== s3 === +9000: OPEN +9001: OPEN + +=== openbao === +8200: OPEN +8201: CLOSED + +=== otel-collector === +4317: CLOSED +4318: OPEN +8888: OPEN +8889: OPEN +18888: CLOSED +18889: CLOSED +55678: CLOSED +55679: CLOSED + +=== prometheus === +9090: OPEN + +=== loki === +3100: OPEN +7946: CLOSED +9095: CLOSED +13100: CLOSED + +=== tempo === +3200: OPEN +4317: CLOSED +4318: CLOSED +7946: CLOSED +9095: CLOSED +13200: CLOSED +14318: CLOSED + +=== grafana === +3000: OPEN + +NETWORK AUDIT COMPLETE diff --git a/evidence/grade3-network-audit-hardened.txt b/evidence/grade3-network-audit-hardened.txt new file mode 100644 index 00000000..6717df66 --- /dev/null +++ b/evidence/grade3-network-audit-hardened.txt @@ -0,0 +1,79 @@ + Container mtusi2026lab7-migrate-run-ee5cc1812d9c Creating + Container mtusi2026lab7-migrate-run-ee5cc1812d9c Created + +=== nginx === +80: CLOSED +443: CLOSED +8080: CLOSED +8443: OPEN + +=== api-1 === +8080: CLOSED +8443: OPEN + +=== api-2 === +8080: CLOSED +8443: OPEN + +=== worker === +8080: CLOSED + +=== dispatcher === +8080: CLOSED + +=== postgres === +5432: OPEN + +=== redis === +6379: OPEN + +=== rabbitmq === +4369: CLOSED +5671: OPEN +5672: CLOSED +15671: OPEN +15672: CLOSED +15691: CLOSED +15692: CLOSED +25672: CLOSED + +=== s3 === +9000: OPEN +9001: OPEN + +=== openbao === +8200: OPEN +8201: CLOSED + +=== otel-collector === +4317: CLOSED +4318: OPEN +8888: OPEN +8889: OPEN +18888: CLOSED +18889: CLOSED +55678: CLOSED +55679: CLOSED + +=== prometheus === +9090: OPEN + +=== loki === +3100: OPEN +7946: CLOSED +9095: CLOSED +13100: CLOSED + +=== tempo === +3200: OPEN +4317: CLOSED +4318: CLOSED +7946: CLOSED +9095: CLOSED +13200: CLOSED +14318: CLOSED + +=== grafana === +3000: OPEN + +NETWORK AUDIT COMPLETE diff --git a/evidence/grade3-network-audit.txt b/evidence/grade3-network-audit.txt new file mode 100644 index 00000000..2cca6511 --- /dev/null +++ b/evidence/grade3-network-audit.txt @@ -0,0 +1,79 @@ + Container mtusi2026lab7-migrate-run-66b62738efbc Creating + Container mtusi2026lab7-migrate-run-66b62738efbc Created + +=== nginx === +80: CLOSED +443: CLOSED +8080: CLOSED +8443: OPEN + +=== api-1 === +8080: CLOSED +8443: OPEN + +=== api-2 === +8080: CLOSED +8443: OPEN + +=== worker === +8080: CLOSED + +=== dispatcher === +8080: CLOSED + +=== postgres === +5432: OPEN + +=== redis === +6379: OPEN + +=== rabbitmq === +4369: OPEN +5671: OPEN +5672: CLOSED +15671: OPEN +15672: CLOSED +15691: CLOSED +15692: CLOSED +25672: OPEN + +=== s3 === +9000: OPEN +9001: OPEN + +=== openbao === +8200: OPEN +8201: OPEN + +=== otel-collector === +4317: CLOSED +4318: OPEN +8888: OPEN +8889: OPEN +18888: CLOSED +18889: CLOSED +55678: CLOSED +55679: CLOSED + +=== prometheus === +9090: OPEN + +=== loki === +3100: OPEN +7946: CLOSED +9095: CLOSED +13100: CLOSED + +=== tempo === +3200: OPEN +4317: CLOSED +4318: CLOSED +7946: CLOSED +9095: CLOSED +13200: CLOSED +14318: CLOSED + +=== grafana === +3000: OPEN + +NETWORK AUDIT COMPLETE diff --git a/evidence/grade3-openbao-config.txt b/evidence/grade3-openbao-config.txt new file mode 100644 index 00000000..d36e83eb --- /dev/null +++ b/evidence/grade3-openbao-config.txt @@ -0,0 +1,13 @@ + Container mtusi2026lab7-migrate-run-c600bc596df3 Creating + Container mtusi2026lab7-migrate-run-c600bc596df3 Created +PASS: KV v2 enabled +PASS: certificate authentication enabled +PASS: messenger-api policy configured +PASS: messenger-worker policy configured +PASS: messenger-dispatcher policy configured +PASS: bao-api-1 -> messenger-api, TTL=15m, max TTL=1h +PASS: bao-api-2 -> messenger-api, TTL=15m, max TTL=1h +PASS: bao-worker -> messenger-worker, TTL=15m, max TTL=1h +PASS: bao-dispatcher -> messenger-dispatcher, TTL=15m, max TTL=1h + +PASS: OPENBAO CONFIGURATION diff --git a/evidence/grade3-openbao-fail-closed.txt b/evidence/grade3-openbao-fail-closed.txt new file mode 100644 index 00000000..8313ef47 --- /dev/null +++ b/evidence/grade3-openbao-fail-closed.txt @@ -0,0 +1,11 @@ + Container mtusi2026lab7-api-1-run-14715a00b459 Creating + Container mtusi2026lab7-api-1-run-14715a00b459 Created +OpenBao attempt 1/6 failed: HTTPError +OpenBao attempt 2/6 failed: HTTPError +OpenBao attempt 3/6 failed: HTTPError +OpenBao attempt 4/6 failed: HTTPError +OpenBao attempt 5/6 failed: HTTPError +OpenBao attempt 6/6 failed: HTTPError +ERROR: OpenBao unavailable + +PASS: startup rejected while OpenBao sealed diff --git a/evidence/grade3-openbao-integration.txt b/evidence/grade3-openbao-integration.txt new file mode 100644 index 00000000..53aa1bed --- /dev/null +++ b/evidence/grade3-openbao-integration.txt @@ -0,0 +1,44 @@ + +=== api-1 === +PASS: cache_url, mode=600 +PASS: database_url, mode=600 +PASS: otel_password, mode=600 +PASS: s3_access_key_id, mode=600 +PASS: s3_secret_access_key, mode=600 +PASS: non-root +PASS: tmpfs secret storage +PASS: no directly mounted database credentials +PASS: no token in environment + +=== api-2 === +PASS: cache_url, mode=600 +PASS: database_url, mode=600 +PASS: otel_password, mode=600 +PASS: s3_access_key_id, mode=600 +PASS: s3_secret_access_key, mode=600 +PASS: non-root +PASS: tmpfs secret storage +PASS: no directly mounted database credentials +PASS: no token in environment + +=== worker === +PASS: database_url, mode=600 +PASS: otel_password, mode=600 +PASS: rabbitmq_password, mode=600 +PASS: s3_access_key_id, mode=600 +PASS: s3_secret_access_key, mode=600 +PASS: non-root +PASS: tmpfs secret storage +PASS: no directly mounted database credentials +PASS: no token in environment + +=== dispatcher === +PASS: database_url, mode=600 +PASS: otel_password, mode=600 +PASS: rabbitmq_password, mode=600 +PASS: non-root +PASS: tmpfs secret storage +PASS: no directly mounted database credentials +PASS: no token in environment + +PASS: ALL APPLICATION SECRET STORAGE CHECKS diff --git a/evidence/grade3-openbao-persistence.txt b/evidence/grade3-openbao-persistence.txt new file mode 100644 index 00000000..768ba37e --- /dev/null +++ b/evidence/grade3-openbao-persistence.txt @@ -0,0 +1,70 @@ + +=== api-1 after OpenBao recreation === + Container mtusi2026lab7-migrate-run-893442158697 Creating + Container mtusi2026lab7-migrate-run-893442158697 Created +PASS: bao-api-1 certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-api +PASS: own secrets readable (5) +PASS: access to worker denied +PASS: access to dispatcher denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-2 denied +PASS: impersonation of bao-worker denied +PASS: impersonation of bao-dispatcher denied +PASS: OPENBAO SECURITY TESTS: bao-api-1 + +=== api-2 after OpenBao recreation === + Container mtusi2026lab7-migrate-run-fe9de8d1cce4 Creating + Container mtusi2026lab7-migrate-run-fe9de8d1cce4 Created +PASS: bao-api-2 certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-api +PASS: own secrets readable (5) +PASS: access to worker denied +PASS: access to dispatcher denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-1 denied +PASS: impersonation of bao-worker denied +PASS: impersonation of bao-dispatcher denied +PASS: OPENBAO SECURITY TESTS: bao-api-2 + +=== worker after OpenBao recreation === + Container mtusi2026lab7-migrate-run-00ae1d17af39 Creating + Container mtusi2026lab7-migrate-run-00ae1d17af39 Created +PASS: bao-worker certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-worker +PASS: own secrets readable (5) +PASS: access to api denied +PASS: access to dispatcher denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-1 denied +PASS: impersonation of bao-api-2 denied +PASS: impersonation of bao-dispatcher denied +PASS: OPENBAO SECURITY TESTS: bao-worker + +=== dispatcher after OpenBao recreation === + Container mtusi2026lab7-migrate-run-26d34268b683 Creating + Container mtusi2026lab7-migrate-run-26d34268b683 Created +PASS: bao-dispatcher certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-dispatcher +PASS: own secrets readable (3) +PASS: access to api denied +PASS: access to worker denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-1 denied +PASS: impersonation of bao-api-2 denied +PASS: impersonation of bao-worker denied +PASS: OPENBAO SECURITY TESTS: bao-dispatcher + +PASS: OPENBAO PERSISTENCE diff --git a/evidence/grade3-openbao-recovery.txt b/evidence/grade3-openbao-recovery.txt new file mode 100644 index 00000000..7f9a574c --- /dev/null +++ b/evidence/grade3-openbao-recovery.txt @@ -0,0 +1,4 @@ + Container mtusi2026lab7-api-1-run-f0b3a30db2a5 Creating + Container mtusi2026lab7-api-1-run-f0b3a30db2a5 Created +PASS: OpenBao identity=bao-api-1, role=api, secrets=5 +PASS: startup after OpenBao recovery diff --git a/evidence/grade3-openbao-restart.txt b/evidence/grade3-openbao-restart.txt new file mode 100644 index 00000000..9e42ab86 --- /dev/null +++ b/evidence/grade3-openbao-restart.txt @@ -0,0 +1,4 @@ +api-1-1 | PASS: OpenBao identity=bao-api-1, role=api, secrets=5 +api-2-1 | PASS: OpenBao identity=bao-api-2, role=api, secrets=5 +dispatcher-1 | PASS: OpenBao identity=bao-dispatcher, role=dispatcher, secrets=3 +worker-1 | PASS: OpenBao identity=bao-worker, role=worker, secrets=5 diff --git a/evidence/grade3-openbao-security.txt b/evidence/grade3-openbao-security.txt new file mode 100644 index 00000000..10821fec --- /dev/null +++ b/evidence/grade3-openbao-security.txt @@ -0,0 +1,70 @@ + +=== bao-api-1 === + Container mtusi2026lab7-migrate-run-e9736b78300a Creating + Container mtusi2026lab7-migrate-run-e9736b78300a Created +PASS: bao-api-1 certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-api +PASS: own secrets readable (5) +PASS: access to worker denied +PASS: access to dispatcher denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-2 denied +PASS: impersonation of bao-worker denied +PASS: impersonation of bao-dispatcher denied +PASS: OPENBAO SECURITY TESTS: bao-api-1 + +=== bao-api-2 === + Container mtusi2026lab7-migrate-run-93768ccb36f7 Creating + Container mtusi2026lab7-migrate-run-93768ccb36f7 Created +PASS: bao-api-2 certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-api +PASS: own secrets readable (5) +PASS: access to worker denied +PASS: access to dispatcher denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-1 denied +PASS: impersonation of bao-worker denied +PASS: impersonation of bao-dispatcher denied +PASS: OPENBAO SECURITY TESTS: bao-api-2 + +=== bao-worker === + Container mtusi2026lab7-migrate-run-f12075ab8656 Creating + Container mtusi2026lab7-migrate-run-f12075ab8656 Created +PASS: bao-worker certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-worker +PASS: own secrets readable (5) +PASS: access to api denied +PASS: access to dispatcher denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-1 denied +PASS: impersonation of bao-api-2 denied +PASS: impersonation of bao-dispatcher denied +PASS: OPENBAO SECURITY TESTS: bao-worker + +=== bao-dispatcher === + Container mtusi2026lab7-migrate-run-3241ee2b008f Creating + Container mtusi2026lab7-migrate-run-3241ee2b008f Created +PASS: bao-dispatcher certificate login +PASS: token TTL=900 seconds +PASS: scoped policy messenger-dispatcher +PASS: own secrets readable (3) +PASS: access to api denied +PASS: access to worker denied +PASS: administrative policy access denied +PASS: policy modification denied +PASS: unauthenticated secret access denied +PASS: impersonation of bao-api-1 denied +PASS: impersonation of bao-api-2 denied +PASS: impersonation of bao-worker denied +PASS: OPENBAO SECURITY TESTS: bao-dispatcher + +PASS: ALL OPENBAO SERVICE IDENTITIES diff --git a/evidence/grade3-openbao-seed.txt b/evidence/grade3-openbao-seed.txt new file mode 100644 index 00000000..26ccfc28 --- /dev/null +++ b/evidence/grade3-openbao-seed.txt @@ -0,0 +1,7 @@ + Container mtusi2026lab7-migrate-run-76199e2100e9 Creating + Container mtusi2026lab7-migrate-run-76199e2100e9 Created +PASS: messenger/api: 5 secrets stored, version=1 +PASS: messenger/worker: 5 secrets stored, version=1 +PASS: messenger/dispatcher: 3 secrets stored, version=1 + +PASS: OPENBAO SECRETS SEEDED diff --git a/evidence/grade3-openbao-status.txt b/evidence/grade3-openbao-status.txt new file mode 100644 index 00000000..3c9e0b85 --- /dev/null +++ b/evidence/grade3-openbao-status.txt @@ -0,0 +1,13 @@ +Key Value +--- ----- +Seal Type shamir +Initialized true +Sealed false +Total Shares 3 +Threshold 2 +Version 2.3.2 +Build Date 2025-08-08T04:05:27Z +Storage Type file +Cluster Name vault-cluster-9c62e62e +Cluster ID 570934d4-9b82-915b-b3ee-ff90f592210c +HA Enabled false diff --git a/evidence/grade3-openbao-tls.txt b/evidence/grade3-openbao-tls.txt new file mode 100644 index 00000000..22dec806 --- /dev/null +++ b/evidence/grade3-openbao-tls.txt @@ -0,0 +1,10 @@ + Container mtusi2026lab7-migrate-run-10d85fe631a5 Creating + Container mtusi2026lab7-migrate-run-10d85fe631a5 Created +PASS: trusted CA and hostname, TLSv1.3 +PASS: untrusted CA rejected +PASS: wrong hostname rejected +PASS: certificate login without client certificate denied +PASS: modification of own secrets denied +PASS: deletion of own secrets denied +PASS: secrets unchanged +PASS: ALL OPENBAO TLS AND WRITE RESTRICTION TESTS diff --git a/evidence/grade3-persistence-after.txt b/evidence/grade3-persistence-after.txt new file mode 100644 index 00000000..ba5d5e3e --- /dev/null +++ b/evidence/grade3-persistence-after.txt @@ -0,0 +1,20 @@ +/mtusi2026lab7-api-1-1 | started=2026-12-06T17:59:09.469723934Z | status=running +/mtusi2026lab7-api-1-proxy-1 | started=2026-12-06T17:59:50.76656555Z | status=running +/mtusi2026lab7-api-2-1 | started=2026-12-06T17:59:09.812233835Z | status=running +/mtusi2026lab7-api-2-proxy-1 | started=2026-12-06T17:59:50.482523532Z | status=running +/mtusi2026lab7-dispatcher-1 | started=2026-12-06T17:59:43.090491483Z | status=running +/mtusi2026lab7-grafana-1 | started=2026-12-06T17:58:52.641321394Z | status=running +/mtusi2026lab7-loki-1 | started=2026-12-06T17:58:54.058535965Z | status=running +/mtusi2026lab7-loki-proxy-1 | started=2026-12-06T17:58:59.987062332Z | status=running +/mtusi2026lab7-nginx-1 | started=2026-12-06T17:59:51.081971537Z | status=running +/mtusi2026lab7-openbao-1 | started=2026-12-06T17:58:52.301293841Z | status=running +/mtusi2026lab7-otel-collector-1 | started=2026-12-06T17:59:00.269197517Z | status=running +/mtusi2026lab7-otel-collector-proxy-1 | started=2026-12-06T17:59:00.9528413Z | status=running +/mtusi2026lab7-postgres-1 | started=2026-12-06T17:58:54.473707714Z | status=running +/mtusi2026lab7-prometheus-1 | started=2026-12-06T17:58:53.924223409Z | status=running +/mtusi2026lab7-rabbitmq-1 | started=2026-12-06T17:58:54.226659242Z | status=running +/mtusi2026lab7-redis-1 | started=2026-12-06T17:58:53.76207235Z | status=running +/mtusi2026lab7-s3-1 | started=2026-12-06T17:58:53.387468221Z | status=running +/mtusi2026lab7-tempo-1 | started=2026-12-06T17:58:54.636196691Z | status=running +/mtusi2026lab7-tempo-proxy-1 | started=2026-12-06T17:58:59.928426746Z | status=running +/mtusi2026lab7-worker-1 | started=2026-12-06T17:59:43.433257971Z | status=running diff --git a/evidence/grade3-persistence-before.txt b/evidence/grade3-persistence-before.txt new file mode 100644 index 00000000..f783e570 --- /dev/null +++ b/evidence/grade3-persistence-before.txt @@ -0,0 +1,20 @@ +/mtusi2026lab7-api-1-1 | started=2026-12-06T16:17:02.617672273Z | status=running +/mtusi2026lab7-api-1-proxy-1 | started=2026-12-06T16:17:08.465123035Z | status=running +/mtusi2026lab7-api-2-1 | started=2026-12-06T16:17:02.249195505Z | status=running +/mtusi2026lab7-api-2-proxy-1 | started=2026-12-06T16:17:08.133439841Z | status=running +/mtusi2026lab7-dispatcher-1 | started=2026-12-06T16:17:36.275748149Z | status=running +/mtusi2026lab7-grafana-1 | started=2026-12-06T16:16:50.860113789Z | status=running +/mtusi2026lab7-loki-1 | started=2026-12-06T16:16:47.678659316Z | status=running +/mtusi2026lab7-loki-proxy-1 | started=2026-12-06T16:16:48.022690693Z | status=running +/mtusi2026lab7-nginx-1 | started=2026-12-06T16:17:08.792721382Z | status=running +/mtusi2026lab7-openbao-1 | started=2026-12-06T16:14:52.309593536Z | status=running +/mtusi2026lab7-otel-collector-1 | started=2026-12-06T16:16:49.858159357Z | status=running +/mtusi2026lab7-otel-collector-proxy-1 | started=2026-12-06T16:16:50.206692162Z | status=running +/mtusi2026lab7-postgres-1 | started=2026-12-06T16:16:48.721168507Z | status=running +/mtusi2026lab7-prometheus-1 | started=2026-12-06T16:16:50.481817345Z | status=running +/mtusi2026lab7-rabbitmq-1 | started=2026-12-06T16:16:48.333401043Z | status=running +/mtusi2026lab7-redis-1 | started=2026-12-06T16:16:46.958337934Z | status=running +/mtusi2026lab7-s3-1 | started=2026-12-06T16:16:49.140808645Z | status=running +/mtusi2026lab7-tempo-1 | started=2026-12-06T16:16:47.339198315Z | status=running +/mtusi2026lab7-tempo-proxy-1 | started=2026-12-06T16:16:49.546403442Z | status=running +/mtusi2026lab7-worker-1 | started=2026-12-06T16:17:35.955623038Z | status=running diff --git a/evidence/grade3-persistence.txt b/evidence/grade3-persistence.txt new file mode 100644 index 00000000..2caa202b --- /dev/null +++ b/evidence/grade3-persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/grade3-postgres-roles.txt b/evidence/grade3-postgres-roles.txt new file mode 100644 index 00000000..caa82088 --- /dev/null +++ b/evidence/grade3-postgres-roles.txt @@ -0,0 +1,130 @@ + ssl +----- + on +(1 row) + + ssl_min_protocol_version +-------------------------- + TLSv1.2 +(1 row) + + rolname | rolsuper | rolcreatedb | rolcreaterole +----------------------+----------+-------------+--------------- + messenger_api | f | f | f + messenger_dispatcher | f | f | f + messenger_migrate | f | f | f + messenger_worker | f | f | f +(4 rows) + + grantee | table_name | privilege_type +----------------------+---------------------+---------------- + messenger_api | attachment_jobs | DELETE + messenger_api | attachment_jobs | INSERT + messenger_api | attachment_jobs | SELECT + messenger_api | attachment_jobs | UPDATE + messenger_api | attachments | DELETE + messenger_api | attachments | INSERT + messenger_api | attachments | SELECT + messenger_api | attachments | UPDATE + messenger_api | chat_members | DELETE + messenger_api | chat_members | INSERT + messenger_api | chat_members | SELECT + messenger_api | chat_members | UPDATE + messenger_api | chats | DELETE + messenger_api | chats | INSERT + messenger_api | chats | SELECT + messenger_api | chats | UPDATE + messenger_api | message_attachments | DELETE + messenger_api | message_attachments | INSERT + messenger_api | message_attachments | SELECT + messenger_api | message_attachments | UPDATE + messenger_api | message_idempotency | DELETE + messenger_api | message_idempotency | INSERT + messenger_api | message_idempotency | SELECT + messenger_api | message_idempotency | UPDATE + messenger_api | messages | DELETE + messenger_api | messages | INSERT + messenger_api | messages | SELECT + messenger_api | messages | UPDATE + messenger_api | users | DELETE + messenger_api | users | INSERT + messenger_api | users | SELECT + messenger_api | users | UPDATE + messenger_dispatcher | attachment_jobs | SELECT + messenger_dispatcher | attachment_jobs | UPDATE + messenger_dispatcher | attachments | SELECT + messenger_dispatcher | attachments | UPDATE + messenger_migrate | alembic_version | DELETE + messenger_migrate | alembic_version | INSERT + messenger_migrate | alembic_version | REFERENCES + messenger_migrate | alembic_version | SELECT + messenger_migrate | alembic_version | TRIGGER + messenger_migrate | alembic_version | TRUNCATE + messenger_migrate | alembic_version | UPDATE + messenger_migrate | attachment_jobs | DELETE + messenger_migrate | attachment_jobs | INSERT + messenger_migrate | attachment_jobs | REFERENCES + messenger_migrate | attachment_jobs | SELECT + messenger_migrate | attachment_jobs | TRIGGER + messenger_migrate | attachment_jobs | TRUNCATE + messenger_migrate | attachment_jobs | UPDATE + messenger_migrate | attachments | DELETE + messenger_migrate | attachments | INSERT + messenger_migrate | attachments | REFERENCES + messenger_migrate | attachments | SELECT + messenger_migrate | attachments | TRIGGER + messenger_migrate | attachments | TRUNCATE + messenger_migrate | attachments | UPDATE + messenger_migrate | chat_members | DELETE + messenger_migrate | chat_members | INSERT + messenger_migrate | chat_members | REFERENCES + messenger_migrate | chat_members | SELECT + messenger_migrate | chat_members | TRIGGER + messenger_migrate | chat_members | TRUNCATE + messenger_migrate | chat_members | UPDATE + messenger_migrate | chats | DELETE + messenger_migrate | chats | INSERT + messenger_migrate | chats | REFERENCES + messenger_migrate | chats | SELECT + messenger_migrate | chats | TRIGGER + messenger_migrate | chats | TRUNCATE + messenger_migrate | chats | UPDATE + messenger_migrate | message_attachments | DELETE + messenger_migrate | message_attachments | INSERT + messenger_migrate | message_attachments | REFERENCES + messenger_migrate | message_attachments | SELECT + messenger_migrate | message_attachments | TRIGGER + messenger_migrate | message_attachments | TRUNCATE + messenger_migrate | message_attachments | UPDATE + messenger_migrate | message_idempotency | DELETE + messenger_migrate | message_idempotency | INSERT + messenger_migrate | message_idempotency | REFERENCES + messenger_migrate | message_idempotency | SELECT + messenger_migrate | message_idempotency | TRIGGER + messenger_migrate | message_idempotency | TRUNCATE + messenger_migrate | message_idempotency | UPDATE + messenger_migrate | messages | DELETE + messenger_migrate | messages | INSERT + messenger_migrate | messages | REFERENCES + messenger_migrate | messages | SELECT + messenger_migrate | messages | TRIGGER + messenger_migrate | messages | TRUNCATE + messenger_migrate | messages | UPDATE + messenger_migrate | users | DELETE + messenger_migrate | users | INSERT + messenger_migrate | users | REFERENCES + messenger_migrate | users | SELECT + messenger_migrate | users | TRIGGER + messenger_migrate | users | TRUNCATE + messenger_migrate | users | UPDATE + messenger_worker | attachment_jobs | SELECT + messenger_worker | attachment_jobs | UPDATE + messenger_worker | attachments | SELECT + messenger_worker | attachments | UPDATE +(103 rows) + + version_num +-------------- + e7a12026a007 +(1 row) + diff --git a/evidence/grade3-process-privileges-final.txt b/evidence/grade3-process-privileges-final.txt new file mode 100644 index 00000000..f7e43934 --- /dev/null +++ b/evidence/grade3-process-privileges-final.txt @@ -0,0 +1,60 @@ + +=== api-1 === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: uvicorn +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== api-2 === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: uvicorn +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== worker === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: python +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== dispatcher === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: python +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== openbao === +uid=100(openbao) gid=1000(openbao) groups=1000(openbao) +Name: bao +Uid: 100 100 100 100 +Gid: 1000 1000 1000 1000 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 diff --git a/evidence/grade3-process-privileges.txt b/evidence/grade3-process-privileges.txt new file mode 100644 index 00000000..eb9f33b3 --- /dev/null +++ b/evidence/grade3-process-privileges.txt @@ -0,0 +1,60 @@ + +=== api-1 === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: uvicorn +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== api-2 === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: uvicorn +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== worker === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: python +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== dispatcher === +uid=10001(appuser) gid=10001(appuser) groups=10001(appuser) +Name: python +Uid: 10001 10001 10001 10001 +Gid: 10001 10001 10001 10001 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 1 +Seccomp: 2 + +=== openbao === +uid=100(openbao) gid=1000(openbao) groups=1000(openbao) +Name: bao +Uid: 100 100 100 100 +Gid: 1000 1000 1000 1000 +CapInh: 0000000000000000 +CapPrm: 0000000000000000 +CapEff: 0000000000000000 +CapBnd: 0000000000000000 +NoNewPrivs: 0 +Seccomp: 2 diff --git a/evidence/grade3-prometheus-secret-audit.txt b/evidence/grade3-prometheus-secret-audit.txt new file mode 100644 index 00000000..80cefd88 --- /dev/null +++ b/evidence/grade3-prometheus-secret-audit.txt @@ -0,0 +1,10 @@ +=== TELEMETRY SECRET AUDIT === +Audit window: 7 days +Credential patterns: 46 +TLS CA and hostname verification: enabled + +=== Prometheus === +Prometheus series inspected: 4121 +PASS: Prometheus scan completed +Failures: 0 +PASS: TELEMETRY SECRET AUDIT: prometheus diff --git a/evidence/grade3-prometheus-security.txt b/evidence/grade3-prometheus-security.txt new file mode 100644 index 00000000..36c08b40 --- /dev/null +++ b/evidence/grade3-prometheus-security.txt @@ -0,0 +1,14 @@ + Container mtusi2026lab7-migrate-run-9f34fcbfb92c Creating + Container mtusi2026lab7-migrate-run-9f34fcbfb92c Created +PASS: Prometheus verified TLS TLSv1.3 +PASS: Prometheus rejects untrusted CA +PASS: Prometheus rejects wrong hostname +PASS: anonymous access denied: 401 +PASS: API credentials denied: 401 +PASS: Grafana query allowed: 200 +PASS: Prometheus self-scrape allowed: 200 +PASS: target UP: otel-collector https://otel-collector:8889/metrics +PASS: target UP: otel-collector-internal https://otel-collector:8888/metrics +PASS: target UP: prometheus https://prometheus:9090/metrics + +PASS: PROMETHEUS SECURITY TESTS diff --git a/evidence/grade3-public-security.txt b/evidence/grade3-public-security.txt new file mode 100644 index 00000000..fbd1ed4f --- /dev/null +++ b/evidence/grade3-public-security.txt @@ -0,0 +1,2 @@ +python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/grade3-public-tls-negative.txt b/evidence/grade3-public-tls-negative.txt new file mode 100644 index 00000000..3420df03 --- /dev/null +++ b/evidence/grade3-public-tls-negative.txt @@ -0,0 +1,4 @@ +PASS: trusted CA and hostname: TLSv1.3 +PASS: wrong hostname: Hostname mismatch, certificate is not valid for 'wrong-host.invalid'. +PASS: empty trust store: unable to get local issuer certificate +PASS: public TLS verification diff --git a/evidence/grade3-public-tls.txt b/evidence/grade3-public-tls.txt new file mode 100644 index 00000000..fe86c4f4 --- /dev/null +++ b/evidence/grade3-public-tls.txt @@ -0,0 +1,10 @@ +CONNECTION ESTABLISHED +Protocol version: TLSv1.3 +Ciphersuite: TLS_AES_256_GCM_SHA384 +Peer certificate: CN = nginx +Hash used: SHA256 +Signature type: RSA-PSS +Verification: OK +Verified peername: localhost +Server Temp Key: X25519, 253 bits +DONE diff --git a/evidence/grade3-published-ports.txt b/evidence/grade3-published-ports.txt new file mode 100644 index 00000000..aabd25cb --- /dev/null +++ b/evidence/grade3-published-ports.txt @@ -0,0 +1,4 @@ +grafana 127.0.0.1 3000 -> 3000 tcp +nginx 0.0.0.0 8443 -> 8443 tcp +nginx :: 8443 -> 8443 tcp +s3 127.0.0.1 9001 -> 9001 tcp diff --git a/evidence/grade3-rabbitmq-config.txt b/evidence/grade3-rabbitmq-config.txt new file mode 100644 index 00000000..057ab97a --- /dev/null +++ b/evidence/grade3-rabbitmq-config.txt @@ -0,0 +1,27 @@ +========== RABBITMQ LISTENERS ========== +Interface: [::], port: 15671, protocol: https, purpose: HTTP API over TLS (HTTPS) +Interface: [::], port: 15692, protocol: http/prometheus, purpose: Prometheus exporter API over HTTP +Interface: [::], port: 25672, protocol: clustering, purpose: inter-node and CLI tool communication +Interface: [::], port: 5671, protocol: amqp/ssl, purpose: AMQP 0-9-1 and AMQP 1.0 over TLS +========== RABBITMQ USERS ========== +Listing users ... +user tags +messenger_admin [administrator] +messenger_consumer [] +messenger_producer [] +========== RABBITMQ VHOSTS ========== +Listing vhosts ... +name +messenger +========== RABBITMQ PERMISSIONS ========== +Listing permissions for vhost "messenger" ... +user configure write read +messenger_producer ^$a ^amq\.default$ ^$a +messenger_admin .* .* .* +messenger_consumer ^$a ^$a ^attachment\.process\.v1$ +========== RABBITMQ QUEUES ========== +Timeout: 60.0 seconds ... +Listing queues for vhost messenger ... +name durable messages consumers +attachment.process.v1 true 0 0 +attachment.failed.v1 true 0 0 diff --git a/evidence/grade3-rabbitmq-security.txt b/evidence/grade3-rabbitmq-security.txt new file mode 100644 index 00000000..b742603f --- /dev/null +++ b/evidence/grade3-rabbitmq-security.txt @@ -0,0 +1,17 @@ + Container mtusi2026lab7-migrate-run-83b74f963d76 Creating + Container mtusi2026lab7-migrate-run-83b74f963d76 Created +PASS: verified RabbitMQ TLS: TLSv1.3 +PASS: untrusted CA rejected +PASS: wrong hostname rejected +PASS: plaintext AMQP listener disabled +PASS: producer authenticated over AMQPS +PASS: producer published message +PASS: consumer authenticated over AMQPS +PASS: consumer received and acknowledged message +PASS: producer cannot consume: ACCESS_REFUSED +PASS: consumer cannot publish: ACCESS_REFUSED +PASS: consumer cannot create queues: ACCESS_REFUSED +PASS: consumer cannot read DLQ: ACCESS_REFUSED +PASS: producer cannot create queues: ACCESS_REFUSED + +PASS: RABBITMQ SECURITY TESTS diff --git a/evidence/grade3-rate-limit-ip.txt b/evidence/grade3-rate-limit-ip.txt new file mode 100644 index 00000000..fc5446f1 --- /dev/null +++ b/evidence/grade3-rate-limit-ip.txt @@ -0,0 +1,70 @@ +Attempt 1: HTTP 401, instance=api-1 +Attempt 2: HTTP 401, instance=api-2 +Attempt 3: HTTP 401, instance=api-1 +Attempt 4: HTTP 401, instance=api-2 +Attempt 5: HTTP 401, instance=api-1 +Attempt 6: HTTP 401, instance=api-2 +Attempt 7: HTTP 401, instance=api-1 +Attempt 8: HTTP 401, instance=api-2 +Attempt 9: HTTP 401, instance=api-1 +Attempt 10: HTTP 401, instance=api-2 +Attempt 11: HTTP 401, instance=api-1 +Attempt 12: HTTP 401, instance=api-2 +Attempt 13: HTTP 401, instance=api-1 +Attempt 14: HTTP 401, instance=api-2 +Attempt 15: HTTP 401, instance=api-1 +Attempt 16: HTTP 401, instance=api-2 +Attempt 17: HTTP 401, instance=api-1 +Attempt 18: HTTP 401, instance=api-2 +Attempt 19: HTTP 401, instance=api-1 +Attempt 20: HTTP 401, instance=api-2 +Attempt 21: HTTP 401, instance=api-1 +Attempt 22: HTTP 401, instance=api-2 +Attempt 23: HTTP 401, instance=api-1 +Attempt 24: HTTP 401, instance=api-2 +Attempt 25: HTTP 401, instance=api-1 +Attempt 26: HTTP 401, instance=api-2 +Attempt 27: HTTP 401, instance=api-1 +Attempt 28: HTTP 401, instance=api-2 +Attempt 29: HTTP 401, instance=api-1 +Attempt 30: HTTP 401, instance=api-2 +Attempt 31: HTTP 401, instance=api-1 +Attempt 32: HTTP 401, instance=api-2 +Attempt 33: HTTP 401, instance=api-1 +Attempt 34: HTTP 401, instance=api-2 +Attempt 35: HTTP 401, instance=api-1 +Attempt 36: HTTP 401, instance=api-2 +Attempt 37: HTTP 401, instance=api-1 +Attempt 38: HTTP 401, instance=api-2 +Attempt 39: HTTP 401, instance=api-1 +Attempt 40: HTTP 401, instance=api-2 +Attempt 41: HTTP 401, instance=api-1 +Attempt 42: HTTP 401, instance=api-2 +Attempt 43: HTTP 401, instance=api-1 +Attempt 44: HTTP 401, instance=api-2 +Attempt 45: HTTP 401, instance=api-1 +Attempt 46: HTTP 401, instance=api-2 +Attempt 47: HTTP 401, instance=api-1 +Attempt 48: HTTP 401, instance=api-2 +Attempt 49: HTTP 401, instance=api-1 +Attempt 50: HTTP 401, instance=api-2 +Attempt 51: HTTP 401, instance=api-1 +Attempt 52: HTTP 401, instance=api-2 +Attempt 53: HTTP 401, instance=api-1 +Attempt 54: HTTP 401, instance=api-2 +Attempt 55: HTTP 401, instance=api-1 +Attempt 56: HTTP 401, instance=api-2 +Attempt 57: HTTP 401, instance=api-1 +Attempt 58: HTTP 401, instance=api-2 +Attempt 59: HTTP 401, instance=api-1 +Attempt 60: HTTP 401, instance=api-2 +Attempt 61: HTTP 429, instance=api-1 +Retry-After: 59 +Error response: {'error': {'code': 'rate_limited', 'message': 'Too many login attempts', 'request_id': '7bca664d-5e9e-4a3e-ab5d-84e9dc34628f'}} +Elapsed: 1.38 seconds +PASS: IP rate limit +PASS: shared IP counter across API replicas +PASS: spoofed X-Forwarded-For cannot bypass limit +Waiting for rate limit expiration... +PASS: IP rate limit expires +PASS: ALL IP RATE LIMIT TESTS diff --git a/evidence/grade3-rate-limit-username.txt b/evidence/grade3-rate-limit-username.txt new file mode 100644 index 00000000..4bdd58d4 --- /dev/null +++ b/evidence/grade3-rate-limit-username.txt @@ -0,0 +1,14 @@ +Testing username rate limit +Attempt 1: HTTP 401, instance=api-1 +Attempt 2: HTTP 401, instance=api-2 +Attempt 3: HTTP 401, instance=api-1 +Attempt 4: HTTP 401, instance=api-2 +Attempt 5: HTTP 401, instance=api-1 +Attempt 6: HTTP 429, instance=api-2 +Retry-After: 60 +Error response: {'error': {'code': 'rate_limited', 'message': 'Too many login attempts', 'request_id': 'e24d1631-002e-413e-bbbb-13e416d6f23a'}} +PASS: shared rate limit across both API replicas +PASS: independent username counters +Waiting for rate limit expiration... +PASS: rate limit expires +PASS: USERNAME RATE LIMIT diff --git a/evidence/grade3-secret-audit.txt b/evidence/grade3-secret-audit.txt new file mode 100644 index 00000000..298bf0fa --- /dev/null +++ b/evidence/grade3-secret-audit.txt @@ -0,0 +1,5 @@ +Tracked files checked: 224 +Known credential patterns checked: 44 +PASS: no known local credentials in container logs +Failures: 0 +PASS: SECRET AUDIT diff --git a/evidence/grade3-session-expiry.txt b/evidence/grade3-session-expiry.txt new file mode 100644 index 00000000..002d26e1 --- /dev/null +++ b/evidence/grade3-session-expiry.txt @@ -0,0 +1,6 @@ +PASS: unknown Bearer token rejected +PASS: Redis session TTL configured +Session TTL: 10 +PASS: session accepted before expiry +PASS: expired session rejected +PASS: ALL SESSION EXPIRY TESTS diff --git a/evidence/grade3-smoke-after-failover.txt b/evidence/grade3-smoke-after-failover.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke-after-failover.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-smoke-after-hardening.txt b/evidence/grade3-smoke-after-hardening.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke-after-hardening.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-smoke-after-network-hardening.txt b/evidence/grade3-smoke-after-network-hardening.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke-after-network-hardening.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-smoke-after-rate-limit.txt b/evidence/grade3-smoke-after-rate-limit.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke-after-rate-limit.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-smoke-after-security.txt b/evidence/grade3-smoke-after-security.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke-after-security.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-smoke-final.txt b/evidence/grade3-smoke-final.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke-final.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-smoke.txt b/evidence/grade3-smoke.txt new file mode 100644 index 00000000..e4286de1 --- /dev/null +++ b/evidence/grade3-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/certs/ca/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/grade3-telemetry-audit-initial-failure.txt b/evidence/grade3-telemetry-audit-initial-failure.txt new file mode 100644 index 00000000..fc8bcca0 --- /dev/null +++ b/evidence/grade3-telemetry-audit-initial-failure.txt @@ -0,0 +1,48 @@ +=== TELEMETRY SECRET AUDIT === +Audit window: 7 days +Credential patterns: 46 +TLS CA and hostname verification: enabled + +=== Loki === +Loki services inspected: 3 +Loki log records inspected: 3108 +PASS: Loki scan completed + +=== Tempo === +Traceback (most recent call last): + File "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/student-tests/audit_telemetry.py", line 223, in + query( + ~~~~~^ + "tempo", + ^^^^^^^^ + f"/api/traces/{trace_id}", + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + ) + ^ + File "/home/casablanca/mtuci/high_load_apps/mtusi2026lab7/student-tests/audit_telemetry.py", line 74, in query + with urlopen( + ~~~~~~~^ + request, + ^^^^^^^^ + context=context, + ^^^^^^^^^^^^^^^^ + timeout=60, + ^^^^^^^^^^^ + ) as response: + ^ + File "/usr/lib/python3.13/urllib/request.py", line 189, in urlopen + return opener.open(url, data, timeout) + ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.13/urllib/request.py", line 495, in open + response = meth(req, response) + File "/usr/lib/python3.13/urllib/request.py", line 604, in http_response + response = self.parent.error( + 'http', request, response, code, msg, hdrs) + File "/usr/lib/python3.13/urllib/request.py", line 533, in error + return self._call_chain(*args) + ~~~~~~~~~~~~~~~~^^^^^^^ + File "/usr/lib/python3.13/urllib/request.py", line 466, in _call_chain + result = func(*args) + File "/usr/lib/python3.13/urllib/request.py", line 613, in http_error_default + raise HTTPError(req.full_url, code, msg, hdrs, fp) +urllib.error.HTTPError: HTTP Error 500: Internal Server Error diff --git a/evidence/grade3-telemetry-backends.txt b/evidence/grade3-telemetry-backends.txt new file mode 100644 index 00000000..d6b0ec54 --- /dev/null +++ b/evidence/grade3-telemetry-backends.txt @@ -0,0 +1,31 @@ + Container mtusi2026lab7-migrate-run-74a4c61a616b Creating + Container mtusi2026lab7-migrate-run-74a4c61a616b Created +PASS: loki verified TLS TLSv1.3 +PASS: loki rejects untrusted CA +PASS: loki rejects wrong hostname +PASS: loki authenticated readiness: 200 +PASS: loki anonymous query denied: 401 +PASS: loki collector query denied: 401 +PASS: loki anonymous ingestion denied: 401 +PASS: loki Grafana ingestion denied: 401 +PASS: loki collector ingestion allowed: 204 +PASS: loki administrative endpoint denied: 403 +PASS: loki:13100 direct access refused +PASS: loki:9095 direct access refused +PASS: tempo verified TLS TLSv1.3 +PASS: tempo rejects untrusted CA +PASS: tempo rejects wrong hostname +PASS: tempo authenticated readiness: 200 +PASS: tempo anonymous query denied: 401 +PASS: tempo collector query denied: 401 +PASS: tempo anonymous ingestion denied: 401 +PASS: tempo Grafana ingestion denied: 401 +PASS: tempo collector ingestion allowed: 200 +PASS: tempo administrative endpoint denied: 403 +PASS: tempo:13200 direct access refused +PASS: tempo:14318 direct access refused +PASS: tempo:4317 direct access refused +PASS: tempo:4318 direct access refused +PASS: tempo:9095 direct access refused + +PASS: TELEMETRY BACKEND SECURITY TESTS diff --git a/evidence/grade3-telemetry-queries.txt b/evidence/grade3-telemetry-queries.txt new file mode 100644 index 00000000..101d9a22 --- /dev/null +++ b/evidence/grade3-telemetry-queries.txt @@ -0,0 +1,6 @@ + Container mtusi2026lab7-migrate-run-1e3fcf24c3f2 Creating + Container mtusi2026lab7-migrate-run-1e3fcf24c3f2 Created +PASS: Loki stored log retrieved via HTTPS +PASS: Tempo stored trace found via HTTPS +Trace ID: 105ce9577790491ebae728ebc4270107 +PASS: TELEMETRY QUERY TESTS diff --git a/evidence/grade3-tempo-secret-audit.txt b/evidence/grade3-tempo-secret-audit.txt new file mode 100644 index 00000000..16aef8ea --- /dev/null +++ b/evidence/grade3-tempo-secret-audit.txt @@ -0,0 +1,23 @@ +=== TELEMETRY SECRET AUDIT === +Audit window: 7 days +Credential patterns: 46 +TLS CA and hostname verification: enabled + +=== Tempo === +Tempo audit window: last 10 minutes +Tempo traces discovered: 3259 +Tempo progress: 1/100 +Tempo progress: 10/100 +Tempo progress: 20/100 +Tempo progress: 30/100 +Tempo progress: 40/100 +Tempo progress: 50/100 +Tempo progress: 60/100 +Tempo progress: 70/100 +Tempo progress: 80/100 +Tempo progress: 90/100 +Tempo progress: 100/100 +Tempo trace bodies inspected: 100 +PASS: Tempo scan completed +Failures: 0 +PASS: TELEMETRY SECRET AUDIT: tempo diff --git a/evidence/grade3-upload-limits.txt b/evidence/grade3-upload-limits.txt new file mode 100644 index 00000000..b2c09efa --- /dev/null +++ b/evidence/grade3-upload-limits.txt @@ -0,0 +1,6 @@ +Response status: 413 +Response body: {"error":{"code":"payload_too_large","message":"Image exceeds maximum upload size","request_id":"8c55cc1b-6112-4493-8cdd-1810ad424db0"}} +PASS: application rejects upload above 10 MiB +PASS: Nginx rejects request above 12 MiB +PASS: unsupported media type rejected +PASS: ALL UPLOAD LIMIT TESTS diff --git a/infra/api-proxy/nginx.conf.template b/infra/api-proxy/nginx.conf.template new file mode 100644 index 00000000..78ae1c3e --- /dev/null +++ b/infra/api-proxy/nginx.conf.template @@ -0,0 +1,57 @@ +worker_processes 1; +pid /tmp/nginx.pid; + +error_log /dev/stderr warn; + +events { + worker_connections 512; +} + +http { + server_tokens off; + + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + + access_log /dev/stdout; + + map $ssl_client_fingerprint $lb_allowed { + default 0; + __LB_FINGERPRINT__ 1; + } + + server { + listen 8443 ssl; + + ssl_certificate /run/tls/tls.crt; + ssl_certificate_key /run/tls/tls.key; + + ssl_client_certificate /run/ca/ca.crt; + ssl_verify_client on; + ssl_verify_depth 2; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + ssl_session_cache off; + + client_max_body_size 12m; + + if ($lb_allowed = 0) { + return 403; + } + + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $http_x_real_ip; + proxy_set_header X-Forwarded-For $http_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + + proxy_connect_timeout 2s; + proxy_read_timeout 10s; + proxy_send_timeout 10s; + } + } +} diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 00000000..d3ed7be5 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,923 @@ +{ + "id": null, + "uid": "lab6-messenger", + "title": "Lab6 - Messenger Observability", + "tags": [ + "lab6", + "messenger", + "opentelemetry" + ], + "timezone": "browser", + "schemaVersion": 39, + "version": 2, + "editable": false, + "refresh": "10s", + "time": { + "from": "now-30m", + "to": "now" + }, + "panels": [ + { + "id": 1, + "title": "HTTP Request Rate", + "description": "HTTP requests per second by method and route", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 0, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (method, route) (rate(messenger_http_requests_total[$__rate_interval]))", + "legendFormat": "{{method}} {{route}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 2, + "title": "HTTP Errors (5xx)", + "description": "Server errors per second", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 0, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(messenger_http_requests_total{status_code=~\"5..\"}[$__rate_interval])) or (0 * sum(rate(messenger_http_requests_total[$__rate_interval])))", + "legendFormat": "5xx errors", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 3, + "title": "HTTP Request Duration", + "description": "Mean HTTP request duration", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 8, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(messenger_http_request_duration_seconds_sum[$__rate_interval])) / sum(rate(messenger_http_request_duration_seconds_count[$__rate_interval]))", + "legendFormat": "Mean duration", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 4, + "title": "Successful Jobs", + "description": "Successful job processing attempts over five minutes", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 8, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(messenger_jobs_total{outcome=\"success\"}[5m])) or (0 * sum(increase(messenger_jobs_total[5m])))", + "legendFormat": "Successful jobs", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 5, + "title": "Failed Jobs and Retries", + "description": "Failed and retried job attempts over five minutes", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 16, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(messenger_jobs_total{outcome=~\"failed|error\"}[5m])) or (0 * sum(increase(messenger_jobs_total[5m])))", + "legendFormat": "Failed attempts", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(messenger_jobs_total{outcome=\"retry\"}[5m])) or (0 * sum(increase(messenger_jobs_total[5m])))", + "legendFormat": "Retries", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 6, + "title": "Job Processing Duration", + "description": "Mean job processing duration by outcome", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 16, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (outcome) (rate(messenger_job_duration_seconds_sum[$__rate_interval])) / sum by (outcome) (rate(messenger_job_duration_seconds_count[$__rate_interval]))", + "legendFormat": "{{outcome}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 7, + "title": "HTTP Latency Percentiles", + "description": "Business request latency across both API replicas", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 24, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route=~\"/api/.*\"}[$__rate_interval])))", + "legendFormat": "p50", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route=~\"/api/.*\"}[$__rate_interval])))", + "legendFormat": "p95", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route=~\"/api/.*\"}[$__rate_interval])))", + "legendFormat": "p99", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 8, + "title": "HTTP Error Ratio", + "description": "5xx divided by all business API requests; health excluded", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 24, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "100 * (sum(rate(messenger_http_requests_total{route=~\"/api/.*\",status_code=~\"5..\"}[$__rate_interval])) or (0 * sum(rate(messenger_http_requests_total{route=~\"/api/.*\"}[$__rate_interval])))) / (sum(rate(messenger_http_requests_total{route=~\"/api/.*\"}[$__rate_interval])) > 0)", + "legendFormat": "5xx ratio", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "percent", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 9, + "title": "Queue Backlog", + "description": "Durable queued attachment jobs", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 32, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (queue_name) (messenger_queue_depth)", + "legendFormat": "{{queue_name}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 10, + "title": "Oldest Queued Job Age", + "description": "Age of oldest queued attachment job", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 32, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (queue_name) (messenger_queue_oldest_age_seconds)", + "legendFormat": "{{queue_name}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 11, + "title": "Database Pool Used / Capacity", + "description": "Checked-out connections and maximum capacity per process", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 40, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_db_pool_used", + "legendFormat": "Used {{service_name}} {{service_instance_id}}", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_db_pool_capacity", + "legendFormat": "Capacity {{service_name}} {{service_instance_id}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 12, + "title": "Database Pool Waiting", + "description": "Connection acquisitions waiting on the pool queue", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 40, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_db_pool_waiting", + "legendFormat": "{{service_name}} {{service_instance_id}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 13, + "title": "Worker Busy / Capacity", + "description": "Concurrent active processing attempts and worker capacity", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 48, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_worker_busy", + "legendFormat": "Busy", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_worker_capacity", + "legendFormat": "Capacity", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 14, + "title": "Process CPU", + "description": "CPU utilization per process; 100% equals one CPU core", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 48, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_process_cpu_percent", + "legendFormat": "{{service_name}} {{service_instance_id}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "percent", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 15, + "title": "Process RAM", + "description": "Resident memory per application process", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 56, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger_process_memory_bytes", + "legendFormat": "{{service_name}} {{service_instance_id}}", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + }, + { + "id": 16, + "title": "Attachment End-to-End Time", + "description": "Time from durable acceptance to committed ready state", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 56, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "p50", + "range": true + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "p95", + "range": true + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "p99", + "range": true + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0, + "custom": { + "drawStyle": "line", + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "auto" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + } + } + ] +} diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 00000000..5bc53981 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,12 @@ +apiVersion: 1 + +providers: + - name: Lab6 + orgId: 1 + folder: Lab6 + type: file + disableDeletion: false + editable: false + updateIntervalSeconds: 10 + options: + path: /var/lib/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 00000000..a7e7c0fa --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,40 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + derivedFields: + - name: TraceID + matcherRegex: '"trace_id"\s*:\s*"([a-f0-9]{32})"' + datasourceUid: tempo + url: '$${__value.raw}' + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: '-5m' + spanEndTimeShift: '5m' + filterByTraceID: true + filterBySpanID: false + tags: + - key: service.name + value: service_name diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 00000000..c31f3275 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,42 @@ +auth_enabled: false + +server: + http_listen_address: 127.0.0.1 + http_listen_port: 13100 + grpc_listen_address: 127.0.0.1 + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + retention_period: 168h + ingestion_rate_mb: 4 + ingestion_burst_size_mb: 8 + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + +analytics: + reporting_enabled: false diff --git a/infra/minio/api-policy.json b/infra/minio/api-policy.json new file mode 100644 index 00000000..4af04447 --- /dev/null +++ b/infra/minio/api-policy.json @@ -0,0 +1,35 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/staging/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/attachments/*", + "arn:aws:s3:::messenger-attachments/variants/*" + ] + } + ] +} diff --git a/infra/minio/init.sh b/infra/minio/init.sh new file mode 100755 index 00000000..e6bc3828 --- /dev/null +++ b/infra/minio/init.sh @@ -0,0 +1,37 @@ +#!/bin/sh +set -eu + +ROOT_USER="$(cat /run/secrets/minio_root_user)" +ROOT_PASSWORD="$(cat /run/secrets/minio_root_password)" + +mkdir -p /tmp/mc/certs/CAs +cp /run/ca/ca.crt /tmp/mc/certs/CAs/lab-ca.crt + +export MC_CONFIG_DIR=/tmp/mc + +mc alias set local https://s3:9000 \ + "$ROOT_USER" "$ROOT_PASSWORD" + +mc mb --ignore-existing local/messenger-attachments +mc anonymous set private local/messenger-attachments + +for role in api worker +do + ACCESS_KEY="$(cat "/run/secrets/s3_${role}_access_key_id")" + SECRET_KEY="$(cat "/run/secrets/s3_${role}_secret_access_key")" + + mc admin policy create \ + local "messenger-$role" \ + "/config/$role-policy.json" + + mc admin user add \ + local "$ACCESS_KEY" "$SECRET_KEY" >/dev/null 2>&1 + + mc admin policy attach \ + local "messenger-$role" \ + --user "$ACCESS_KEY" >/dev/null 2>&1 + + echo "PASS: MinIO $role identity configured" +done + +echo "PASS: MinIO HTTPS initialization complete" diff --git a/infra/minio/worker-policy.json b/infra/minio/worker-policy.json new file mode 100644 index 00000000..ec9d0966 --- /dev/null +++ b/infra/minio/worker-policy.json @@ -0,0 +1,24 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/staging/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:PutObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/attachments/*", + "arn:aws:s3:::messenger-attachments/variants/*" + ] + } + ] +} diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..263b7562 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,57 @@ +events { + worker_connections 1024; +} + +http { + resolver 127.0.0.11 valid=5s ipv6=off; + resolver_timeout 2s; + + server_tokens off; + + upstream api_backend { + zone api_backend 64k; + + server api-1:8443 resolve max_fails=1 fail_timeout=5s; + server api-2:8443 resolve max_fails=1 fail_timeout=5s; + } + + server { + listen 8443 ssl; + + ssl_certificate /etc/nginx/tls/tls.crt; + ssl_certificate_key /etc/nginx/tls/tls.key; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + client_max_body_size 12m; + + location / { + proxy_pass https://api_backend; + proxy_http_version 1.1; + + proxy_ssl_certificate /etc/nginx/client/tls.crt; + proxy_ssl_certificate_key /etc/nginx/client/tls.key; + + proxy_ssl_trusted_certificate /etc/nginx/ca/ca.crt; + proxy_ssl_verify on; + proxy_ssl_verify_depth 2; + + proxy_ssl_server_name on; + proxy_ssl_name api.internal; + proxy_ssl_protocols TLSv1.2 TLSv1.3; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto https; + + proxy_connect_timeout 2s; + proxy_read_timeout 10s; + proxy_send_timeout 10s; + + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/infra/openbao/openbao.hcl b/infra/openbao/openbao.hcl new file mode 100644 index 00000000..c0e15eda --- /dev/null +++ b/infra/openbao/openbao.hcl @@ -0,0 +1,25 @@ +ui = false + + +api_addr = "https://openbao:8200" + +storage "file" { + path = "/openbao/data" +} + +listener "tcp" { + address = "0.0.0.0:8200" + cluster_address = "127.0.0.1:8201" + + tls_disable = false + tls_cert_file = "/run/tls/tls.crt" + tls_key_file = "/run/tls/tls.key" + tls_min_version = "tls12" + + tls_client_ca_file = "/run/ca/ca.crt" + tls_require_and_verify_client_cert = false + tls_disable_client_certs = false +} + +default_lease_ttl = "15m" +max_lease_ttl = "1h" diff --git a/infra/openbao/policies/api.hcl b/infra/openbao/policies/api.hcl new file mode 100644 index 00000000..190c5291 --- /dev/null +++ b/infra/openbao/policies/api.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/api" { + capabilities = ["read"] +} diff --git a/infra/openbao/policies/dispatcher.hcl b/infra/openbao/policies/dispatcher.hcl new file mode 100644 index 00000000..dbcfe82c --- /dev/null +++ b/infra/openbao/policies/dispatcher.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/dispatcher" { + capabilities = ["read"] +} diff --git a/infra/openbao/policies/worker.hcl b/infra/openbao/policies/worker.hcl new file mode 100644 index 00000000..6c67e260 --- /dev/null +++ b/infra/openbao/policies/worker.hcl @@ -0,0 +1,3 @@ +path "secret/data/messenger/worker" { + capabilities = ["read"] +} diff --git a/infra/otel/config.yaml b/infra/otel/config.yaml new file mode 100644 index 00000000..a1362ea0 --- /dev/null +++ b/infra/otel/config.yaml @@ -0,0 +1,94 @@ +extensions: + basicauth/ingest: + htpasswd: + file: /run/secrets/otel_htpasswd + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /run/tls/tls.crt + key_file: /run/tls/tls.key + min_version: "1.2" + auth: + authenticator: basicauth/ingest + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + + batch: + timeout: 2s + send_batch_size: 512 + send_batch_max_size: 1024 + +exporters: + prometheus: + endpoint: 127.0.0.1:18889 + metric_expiration: 30s + resource_to_telemetry_conversion: + enabled: true + + otlphttp/tempo: + endpoint: https://tempo:3200 + timeout: 5s + tls: + ca_file: /run/ca/ca.crt + insecure: false + insecure_skip_verify: false + headers: + Authorization: "${file:/run/secrets/otel_backend_authorization}" + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 128 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s + + otlphttp/loki: + endpoint: https://loki:3100/otlp + timeout: 5s + tls: + ca_file: /run/ca/ca.crt + insecure: false + insecure_skip_verify: false + headers: + Authorization: "${file:/run/secrets/otel_backend_authorization}" + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 128 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s + +service: + extensions: [basicauth/ingest] + telemetry: + metrics: + address: 127.0.0.1:18888 + + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] + + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] diff --git a/infra/postgres/grants.sql b/infra/postgres/grants.sql new file mode 100644 index 00000000..f8f52074 --- /dev/null +++ b/infra/postgres/grants.sql @@ -0,0 +1,11 @@ +GRANT SELECT, UPDATE ON TABLE + public.attachments, + public.attachment_jobs +TO messenger_worker; + +GRANT SELECT, UPDATE ON TABLE + public.attachments, + public.attachment_jobs +TO messenger_dispatcher; + +REVOKE ALL ON TABLE public.alembic_version FROM messenger_api; diff --git a/infra/postgres/init-roles.sh b/infra/postgres/init-roles.sh new file mode 100755 index 00000000..d6146c10 --- /dev/null +++ b/infra/postgres/init-roles.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +set -euo pipefail + +psql \ + --username "$POSTGRES_USER" \ + --dbname "$POSTGRES_DB" \ + --set ON_ERROR_STOP=1 \ + --set migrate_password="$(cat /run/secrets/db_migrate_password)" \ + --set api_password="$(cat /run/secrets/db_api_password)" \ + --set worker_password="$(cat /run/secrets/db_worker_password)" \ + --set dispatcher_password="$(cat /run/secrets/db_dispatcher_password)" <<'SQL' + +CREATE ROLE messenger_migrate LOGIN PASSWORD :'migrate_password'; +CREATE ROLE messenger_api LOGIN PASSWORD :'api_password'; +CREATE ROLE messenger_worker LOGIN PASSWORD :'worker_password'; +CREATE ROLE messenger_dispatcher LOGIN PASSWORD :'dispatcher_password'; + +REVOKE ALL ON DATABASE messenger FROM PUBLIC; +REVOKE ALL ON SCHEMA public FROM PUBLIC; + +GRANT CONNECT ON DATABASE messenger TO + messenger_migrate, + messenger_api, + messenger_worker, + messenger_dispatcher; + +GRANT USAGE, CREATE ON SCHEMA public TO messenger_migrate; + +GRANT USAGE ON SCHEMA public TO + messenger_api, + messenger_worker, + messenger_dispatcher; + +ALTER DEFAULT PRIVILEGES FOR ROLE messenger_migrate + IN SCHEMA public + GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO messenger_api; + +ALTER DEFAULT PRIVILEGES FOR ROLE messenger_migrate + IN SCHEMA public + GRANT USAGE, SELECT ON SEQUENCES TO messenger_api; + +SQL + +echo "PASS: PostgreSQL roles initialized" diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 00000000..fd88e411 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,5 @@ +local all all trust +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::/0 scram-sha-256 +hostnossl all all 0.0.0.0/0 reject +hostnossl all all ::/0 reject diff --git a/infra/prometheus/RUNBOOK.md b/infra/prometheus/RUNBOOK.md new file mode 100644 index 00000000..b5f4bd3f --- /dev/null +++ b/infra/prometheus/RUNBOOK.md @@ -0,0 +1,74 @@ +# Регламент диагностики и устранения инцидентов + +## SLI / SLO + +- SLO доступности API: не менее 99% за 30 дней. +- SLO задержки: не менее 95% бизнес-запросов выполняются за 500 мс за 30 дней. +- SLI доступности: 1 - количество HTTP 5xx / общее количество бизнес-запросов. +- SLI задержки: доля бизнес-запросов, выполненных не более чем за 500 мс. +- Запросы к health endpoints исключаются из расчётов. +- При отсутствии запросов показатели не оцениваются. +- Для демонстрации инцидентов используются сокращённые окна наблюдения. + +## Ошибки HTTP + + + +Алерт: MessengerHighHTTPErrorRate. + +Условие срабатывания: доля HTTP 5xx превышает 1% +за последнюю минуту в течение 15 секунд. + +### Диагностика + +1. Проверить долю ошибок и задержки HTTP-запросов в Grafana. +2. Проверить доступность PostgreSQL и состояние пула соединений. +3. Найти логи ошибочных запросов в Loki. +4. Открыть соответствующие трассировки в Tempo. +5. Определить причину ошибки или замедления. + +### Восстановление + +Восстановить работоспособность проблемного сервиса. +Проверить готовность API, выполнить smoke-тесты +и убедиться, что алерт перешёл в неактивное состояние. + +## Задержка очереди + + + +Алерт: MessengerQueueLag. + +Условие срабатывания: возраст самой старой задачи +в очереди превышает 30 секунд в течение 15 секунд. + +### Диагностика + +1. Проверить глубину очереди и возраст самой старой задачи. +2. Проверить доступность и загрузку worker. +3. Проверить очереди и потребителей RabbitMQ. +4. Изучить логи dispatcher и worker в Loki. +5. Проверить трассировки обработки вложений в Tempo. + +### Восстановление + +Восстановить работу worker или проблемного сервиса. +Убедиться, что очередь сокращается, вложения переходят +в состояние ready, а алерт становится неактивным. + +## Отказ системы сбора телеметрии + +### Диагностика + +1. Проверить доступность Tempo и Loki. +2. Проверить потребление памяти OpenTelemetry Collector. +3. Проверить размер и ёмкость очередей экспортёров. +4. Проверить количество ошибок экспорта и потерь телеметрии. +5. Убедиться, что бизнес-API продолжает работать. + +### Восстановление + +Восстановить доступность проблемного backend. +Убедиться, что очереди экспортёров сокращаются, +отправка телеметрии возобновилась, а API работает корректно. +Зафиксировать количество потерянной телеметрии. diff --git a/infra/prometheus/prometheus.yaml b/infra/prometheus/prometheus.yaml new file mode 100644 index 00000000..38bb9252 --- /dev/null +++ b/infra/prometheus/prometheus.yaml @@ -0,0 +1,43 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s + +rule_files: + - /etc/prometheus/rules.yml + +scrape_configs: + - job_name: otel-collector + scheme: https + tls_config: + ca_file: /run/ca/ca.crt + insecure_skip_verify: false + basic_auth: + username: prometheus + password_file: /run/secrets/prometheus_scrape_password + static_configs: + - targets: + - otel-collector:8889 + + - job_name: otel-collector-internal + scheme: https + tls_config: + ca_file: /run/ca/ca.crt + insecure_skip_verify: false + basic_auth: + username: prometheus + password_file: /run/secrets/prometheus_scrape_password + static_configs: + - targets: + - otel-collector:8888 + + - job_name: prometheus + scheme: https + tls_config: + ca_file: /run/ca/ca.crt + insecure_skip_verify: false + basic_auth: + username: prometheus + password_file: /run/secrets/prometheus_scrape_password + static_configs: + - targets: + - prometheus:9090 diff --git a/infra/prometheus/rules.yaml b/infra/prometheus/rules.yaml new file mode 100644 index 00000000..33a6e0a5 --- /dev/null +++ b/infra/prometheus/rules.yaml @@ -0,0 +1,58 @@ +groups: + - name: messenger-sli + interval: 5s + rules: + - record: messenger:sli_http_error_ratio:1m + expr: | + ( + sum(rate(messenger_http_requests_total{route=~"/api/.*",status_class="5xx"}[1m])) + or vector(0) + ) + / + sum(rate(messenger_http_requests_total{route=~"/api/.*"}[1m])) + + - record: messenger:sli_http_availability:1m + expr: | + 1 - messenger:sli_http_error_ratio:1m + + - record: messenger:sli_http_p95_seconds:1m + expr: | + histogram_quantile( + 0.95, + sum by (le) ( + rate(messenger_http_request_duration_seconds_bucket{route=~"/api/.*"}[1m]) + ) + ) + + - record: messenger:sli_http_latency_good_ratio:1m + expr: | + sum(rate(messenger_http_request_duration_seconds_bucket{route=~"/api/.*",le="0.5"}[1m])) + / + sum(rate(messenger_http_request_duration_seconds_count{route=~"/api/.*"}[1m])) + + - name: messenger-alerts + interval: 5s + rules: + - alert: MessengerHighHTTPErrorRate + expr: | + messenger:sli_http_error_ratio:1m > 0.01 + for: 15s + labels: + severity: critical + annotations: + summary: "HTTP 5xx error ratio exceeds 1%" + description: "Business API error ratio is {{ $value }}" + runbook: "infra/prometheus/RUNBOOK.md#http-errors" + + - alert: MessengerQueueLag + expr: | + max by (queue_name) ( + messenger_queue_oldest_age_seconds + ) > 30 + for: 15s + labels: + severity: warning + annotations: + summary: "Attachment queue lag exceeds 30 seconds" + description: "Oldest pending job age is {{ $value }} seconds" + runbook: "infra/prometheus/RUNBOOK.md#queue-lag" diff --git a/infra/rabbitmq/enabled_plugins b/infra/rabbitmq/enabled_plugins new file mode 100644 index 00000000..352dfc4d --- /dev/null +++ b/infra/rabbitmq/enabled_plugins @@ -0,0 +1 @@ +[rabbitmq_management]. diff --git a/infra/rabbitmq/tls.conf b/infra/rabbitmq/tls.conf new file mode 100644 index 00000000..c1b7da82 --- /dev/null +++ b/infra/rabbitmq/tls.conf @@ -0,0 +1,23 @@ +listeners.tcp = none +listeners.ssl.default = 5671 + +ssl_options.cacertfile = /run/ca/ca.crt +ssl_options.certfile = /run/tls/tls.crt +ssl_options.keyfile = /run/tls/tls.key + +ssl_options.verify = verify_none +ssl_options.fail_if_no_peer_cert = false + +ssl_options.versions.1 = tlsv1.3 +ssl_options.versions.2 = tlsv1.2 + +management.ssl.port = 15671 +management.ssl.cacertfile = /run/ca/ca.crt +management.ssl.certfile = /run/tls/tls.crt +management.ssl.keyfile = /run/tls/tls.key + +definitions.import_backend = local_filesystem +definitions.local.path = /run/secrets/rabbitmq_definitions + +# Single-node deployment: local distribution only. +distribution.listener.interface = 127.0.0.1 diff --git a/infra/redis/redis.conf b/infra/redis/redis.conf new file mode 100644 index 00000000..ad267a2e --- /dev/null +++ b/infra/redis/redis.conf @@ -0,0 +1,18 @@ +bind 0.0.0.0 +protected-mode yes + +port 0 +tls-port 6379 + +tls-cert-file /run/tls/tls.crt +tls-key-file /run/tls/tls.key +tls-ca-cert-file /run/ca/ca.crt + +tls-auth-clients no +tls-protocols "TLSv1.2 TLSv1.3" + +aclfile /run/secrets/redis_acl + +appendonly yes +appendfsync everysec +dir /data diff --git a/infra/telemetry-proxy/loki.conf b/infra/telemetry-proxy/loki.conf new file mode 100644 index 00000000..da2e42f5 --- /dev/null +++ b/infra/telemetry-proxy/loki.conf @@ -0,0 +1,149 @@ +worker_processes 1; +pid /tmp/nginx.pid; +error_log /dev/stderr warn; + +events { + worker_connections 512; +} + +http { + server_tokens off; + access_log /dev/stdout; + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + + server { + listen 3100 ssl; + ssl_certificate /run/tls/tls.crt; + ssl_certificate_key /run/tls/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + client_max_body_size 16m; + + location = /otlp/v1/logs { + auth_basic "Telemetry ingestion"; + auth_basic_user_file /run/secrets/otel_backend_htpasswd; + + limit_except POST { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + + location = /loki/api/v1/query { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /loki/api/v1/query_range { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /loki/api/v1/labels { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location /loki/api/v1/label/ { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /loki/api/v1/series { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /loki/api/v1/index/stats { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /loki/api/v1/detected_fields { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /loki/api/v1/detected_labels { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location = /ready { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13100; + } + + location / { + return 403; + } + } +} diff --git a/infra/telemetry-proxy/otel-collector.conf b/infra/telemetry-proxy/otel-collector.conf new file mode 100644 index 00000000..e34abd27 --- /dev/null +++ b/infra/telemetry-proxy/otel-collector.conf @@ -0,0 +1,64 @@ +worker_processes 1; +pid /tmp/nginx.pid; +error_log /dev/stderr warn; + +events { + worker_connections 512; +} + +http { + server_tokens off; + access_log /dev/stdout; + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + + server { + listen 8888 ssl; + + ssl_certificate /run/tls/tls.crt; + ssl_certificate_key /run/tls/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + location = /metrics { + auth_basic "Prometheus metrics"; + auth_basic_user_file /run/secrets/prometheus_scrape_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:18888; + } + + location / { + return 403; + } + } + + server { + listen 8889 ssl; + + ssl_certificate /run/tls/tls.crt; + ssl_certificate_key /run/tls/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + location = /metrics { + auth_basic "Prometheus metrics"; + auth_basic_user_file /run/secrets/prometheus_scrape_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:18889; + } + + location / { + return 403; + } + } +} diff --git a/infra/telemetry-proxy/tempo.conf b/infra/telemetry-proxy/tempo.conf new file mode 100644 index 00000000..fa6a39e6 --- /dev/null +++ b/infra/telemetry-proxy/tempo.conf @@ -0,0 +1,125 @@ +worker_processes 1; +pid /tmp/nginx.pid; +error_log /dev/stderr warn; + +events { + worker_connections 512; +} + +http { + server_tokens off; + access_log /dev/stdout; + client_body_temp_path /tmp/client_body; + proxy_temp_path /tmp/proxy; + + server { + listen 3200 ssl; + ssl_certificate /run/tls/tls.crt; + ssl_certificate_key /run/tls/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + + client_max_body_size 16m; + + location = /v1/traces { + auth_basic "Telemetry ingestion"; + auth_basic_user_file /run/secrets/otel_backend_htpasswd; + + limit_except POST { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:14318; + } + + + location /api/traces/ { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location /api/v2/traces/ { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location = /api/search { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location = /api/echo { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location = /api/metrics/query { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location = /api/metrics/query_range { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location = /ready { + auth_basic "Telemetry queries"; + auth_basic_user_file /run/secrets/grafana_datasource_htpasswd; + + limit_except GET { + deny all; + } + + proxy_set_header Authorization ""; + proxy_pass http://127.0.0.1:13200; + } + + location / { + return 403; + } + } +} diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 00000000..4021529a --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,29 @@ +server: + http_listen_address: 127.0.0.1 + http_listen_port: 13200 + grpc_listen_address: 127.0.0.1 + +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 127.0.0.1:14318 + +ingester: + max_block_duration: 5m + +compactor: + compaction: + block_retention: 168h + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + +usage_report: + reporting_enabled: false diff --git a/migrations/README b/migrations/README new file mode 100644 index 00000000..e0d0858f --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 00000000..4a1870a1 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,56 @@ +import asyncio +import ssl + +from alembic import context +from sqlalchemy import pool +from sqlalchemy.ext.asyncio import async_engine_from_config + + +config = context.config + +DATABASE_URL_FILE = "/run/secrets/database_url" + + +def read_database_url() -> str: + with open(DATABASE_URL_FILE, encoding="utf-8") as file: + return file.read().strip() + + +config.set_main_option("sqlalchemy.url", read_database_url()) + +target_metadata = None + + +def do_run_migrations(connection) -> None: + context.configure( + connection=connection, + target_metadata=target_metadata, + ) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + connectable = async_engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + connect_args={ + "ssl": ssl.create_default_context( + cafile="/run/ca/ca.crt", + ), + }, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + asyncio.run(run_async_migrations()) + + +run_migrations_online() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 00000000..11016301 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/a6b12026a002_job_retries.py b/migrations/versions/a6b12026a002_job_retries.py new file mode 100644 index 00000000..3fde2807 --- /dev/null +++ b/migrations/versions/a6b12026a002_job_retries.py @@ -0,0 +1,42 @@ +from alembic import op +import sqlalchemy as sa + + +revision = "a6b12026a002" +down_revision = "e5a12026a001" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "attachment_jobs", + sa.Column("next_attempt_at", sa.DateTime(timezone=True)), + ) + + op.add_column( + "attachment_jobs", + sa.Column("last_error_code", sa.String(64)), + ) + + op.add_column( + "attachment_jobs", + sa.Column("finished_at", sa.DateTime(timezone=True)), + ) + + op.create_index( + "ix_attachment_jobs_retry_schedule", + "attachment_jobs", + ["status", "next_attempt_at"], + ) + + +def downgrade(): + op.drop_index( + "ix_attachment_jobs_retry_schedule", + table_name="attachment_jobs", + ) + + op.drop_column("attachment_jobs", "finished_at") + op.drop_column("attachment_jobs", "last_error_code") + op.drop_column("attachment_jobs", "next_attempt_at") \ No newline at end of file diff --git a/migrations/versions/a7b12026a003_failed_publication.py b/migrations/versions/a7b12026a003_failed_publication.py new file mode 100644 index 00000000..b82e944e --- /dev/null +++ b/migrations/versions/a7b12026a003_failed_publication.py @@ -0,0 +1,33 @@ +from alembic import op +import sqlalchemy as sa + + +revision = "a7b12026a003" +down_revision = "a6b12026a002" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "attachment_jobs", + sa.Column("failed_published_at", sa.DateTime(timezone=True)), + ) + + op.create_index( + "ix_attachment_jobs_failed_unpublished", + "attachment_jobs", + ["created_at"], + postgresql_where=sa.text( + "status = 'failed' AND failed_published_at IS NULL" + ), + ) + + +def downgrade(): + op.drop_index( + "ix_attachment_jobs_failed_unpublished", + table_name="attachment_jobs", + ) + + op.drop_column("attachment_jobs", "failed_published_at") \ No newline at end of file diff --git a/migrations/versions/b3a91c0e7d42_message_idempotency.py b/migrations/versions/b3a91c0e7d42_message_idempotency.py new file mode 100644 index 00000000..1a794894 --- /dev/null +++ b/migrations/versions/b3a91c0e7d42_message_idempotency.py @@ -0,0 +1,61 @@ +"""Message idempotency for lab 3. + +Revision ID: b3a91c0e7d42 +Revises: f7c51e1e945b +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "b3a91c0e7d42" +down_revision = "f7c51e1e945b" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "message_idempotency", + sa.Column("user_id", sa.Uuid(), nullable=False), + sa.Column("chat_id", sa.Uuid(), nullable=False), + sa.Column("key", sa.String(length=128), nullable=False), + sa.Column("request_hash", sa.String(length=64), nullable=False), + sa.Column("message_id", sa.Uuid(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.ForeignKeyConstraint( + ["user_id"], + ["users.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["chat_id"], + ["chats.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["message_id"], + ["messages.id"], + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("user_id", "chat_id", "key"), + ) + + op.create_index( + "ix_message_idempotency_created_at", + "message_idempotency", + ["created_at"], + ) + + +def downgrade() -> None: + op.drop_index( + "ix_message_idempotency_created_at", + table_name="message_idempotency", + ) + op.drop_table("message_idempotency") \ No newline at end of file diff --git a/migrations/versions/b8b12026a004_job_generation.py b/migrations/versions/b8b12026a004_job_generation.py new file mode 100644 index 00000000..d9666d30 --- /dev/null +++ b/migrations/versions/b8b12026a004_job_generation.py @@ -0,0 +1,24 @@ +from alembic import op +import sqlalchemy as sa + + +revision = "b8b12026a004" +down_revision = "a7b12026a003" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "attachment_jobs", + sa.Column( + "generation", + sa.Integer(), + nullable=False, + server_default="1", + ), + ) + + +def downgrade(): + op.drop_column("attachment_jobs", "generation") \ No newline at end of file diff --git a/migrations/versions/c8f42a19e6b0_attachments.py b/migrations/versions/c8f42a19e6b0_attachments.py new file mode 100644 index 00000000..7463682c --- /dev/null +++ b/migrations/versions/c8f42a19e6b0_attachments.py @@ -0,0 +1,78 @@ + +from alembic import op +import sqlalchemy as sa + + +revision = "c8f42a19e6b0" +down_revision = "b3a91c0e7d42" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "attachments", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("chat_id", sa.Uuid(), nullable=False), + sa.Column("uploader_id", sa.Uuid(), nullable=False), + sa.Column("filename", sa.String(length=255), nullable=False), + sa.Column("content_type", sa.String(length=100), nullable=False), + sa.Column("size_bytes", sa.BigInteger(), nullable=False), + sa.Column("s3_key", sa.String(length=512), nullable=False), + sa.Column("status", sa.String(length=20), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.ForeignKeyConstraint( + ["chat_id"], + ["chats.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["uploader_id"], + ["users.id"], + ondelete="RESTRICT", + ), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("s3_key", name="uq_attachments_s3_key"), + sa.CheckConstraint( + "size_bytes > 0 AND size_bytes <= 10485760", + name="ck_attachments_size", + ), + sa.CheckConstraint( + "status IN ('pending', 'ready')", + name="ck_attachments_status", + ), + ) + + op.create_index( + "ix_attachments_chat_id", + "attachments", + ["chat_id"], + ) + + op.create_table( + "message_attachments", + sa.Column("message_id", sa.Uuid(), nullable=False), + sa.Column("attachment_id", sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint( + ["message_id"], + ["messages.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["attachment_id"], + ["attachments.id"], + ondelete="RESTRICT", + ), + sa.PrimaryKeyConstraint("message_id", "attachment_id"), + ) + + +def downgrade() -> None: + op.drop_table("message_attachments") + op.drop_index("ix_attachments_chat_id", table_name="attachments") + op.drop_table("attachments") diff --git a/migrations/versions/c9b12026a005_execution_id.py b/migrations/versions/c9b12026a005_execution_id.py new file mode 100644 index 00000000..a6ef3555 --- /dev/null +++ b/migrations/versions/c9b12026a005_execution_id.py @@ -0,0 +1,19 @@ +from alembic import op +import sqlalchemy as sa + + +revision = "c9b12026a005" +down_revision = "b8b12026a004" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "attachment_jobs", + sa.Column("execution_id", sa.UUID(), nullable=True), + ) + + +def downgrade(): + op.drop_column("attachment_jobs", "execution_id") \ No newline at end of file diff --git a/migrations/versions/d6a12026a006_trace_context.py b/migrations/versions/d6a12026a006_trace_context.py new file mode 100644 index 00000000..7c34c555 --- /dev/null +++ b/migrations/versions/d6a12026a006_trace_context.py @@ -0,0 +1,25 @@ +from alembic import op +import sqlalchemy as sa + + +revision = "d6a12026a006" +down_revision = "c9b12026a005" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "attachment_jobs", + sa.Column("traceparent", sa.Text(), nullable=True), + ) + + op.add_column( + "attachment_jobs", + sa.Column("tracestate", sa.Text(), nullable=True), + ) + + +def downgrade(): + op.drop_column("attachment_jobs", "tracestate") + op.drop_column("attachment_jobs", "traceparent") diff --git a/migrations/versions/d9e53b20f7c1_attachment_metadata.py b/migrations/versions/d9e53b20f7c1_attachment_metadata.py new file mode 100644 index 00000000..72bb1460 --- /dev/null +++ b/migrations/versions/d9e53b20f7c1_attachment_metadata.py @@ -0,0 +1,80 @@ + +from alembic import op +import sqlalchemy as sa + + +revision = "d9e53b20f7c1" +down_revision = "c8f42a19e6b0" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.alter_column( + "attachments", + "uploader_id", + new_column_name="owner_id", + ) + + op.add_column( + "attachments", + sa.Column( + "sha256", + sa.String(length=64), + nullable=False, + ), + ) + + op.add_column( + "attachments", + sa.Column( + "variants", + sa.JSON(), + nullable=False, + server_default=sa.text("'[]'::json"), + ), + ) + + op.add_column( + "attachments", + sa.Column( + "error_code", + sa.String(length=100), + nullable=True, + ), + ) + + op.add_column( + "attachments", + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + ) + + op.create_check_constraint( + "ck_attachments_sha256", + "attachments", + "sha256 ~ '^[a-f0-9]{64}$'", + ) + + +def downgrade() -> None: + op.drop_constraint( + "ck_attachments_sha256", + "attachments", + type_="check", + ) + + op.drop_column("attachments", "updated_at") + op.drop_column("attachments", "error_code") + op.drop_column("attachments", "variants") + op.drop_column("attachments", "sha256") + + op.alter_column( + "attachments", + "owner_id", + new_column_name="uploader_id", + ) diff --git a/migrations/versions/e5a12026a001_async_jobs.py b/migrations/versions/e5a12026a001_async_jobs.py new file mode 100644 index 00000000..d6f87082 --- /dev/null +++ b/migrations/versions/e5a12026a001_async_jobs.py @@ -0,0 +1,77 @@ +from alembic import op +import sqlalchemy as sa + +revision = "e5a12026a001" +down_revision = "d9e53b20f7c1" +branch_labels = None +depends_on = None + + +def upgrade(): + op.drop_constraint( + "ck_attachments_status", + "attachments", + type_="check", + ) + op.create_check_constraint( + "ck_attachments_status", + "attachments", + "status IN ('queued', 'processing', 'ready', 'failed')", + ) + + op.create_table( + "attachment_jobs", + sa.Column("id", sa.Uuid(), primary_key=True), + sa.Column( + "attachment_id", + sa.Uuid(), + sa.ForeignKey("attachments.id", ondelete="CASCADE"), + nullable=False, + unique=True, + ), + sa.Column( + "attempt", + sa.Integer(), + nullable=False, + server_default="1", + ), + sa.Column( + "status", + sa.String(20), + nullable=False, + server_default="queued", + ), + sa.Column("published_at", sa.DateTime(timezone=True)), + sa.Column("started_at", sa.DateTime(timezone=True)), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + ) + + op.create_index( + "ix_attachment_jobs_unpublished", + "attachment_jobs", + ["published_at"], + ) + + +def downgrade(): + op.drop_index( + "ix_attachment_jobs_unpublished", + table_name="attachment_jobs", + ) + op.drop_table("attachment_jobs") + + op.drop_constraint( + "ck_attachments_status", + "attachments", + type_="check", + ) + op.create_check_constraint( + "ck_attachments_status", + "attachments", + "status IN ('pending', 'ready')", + ) \ No newline at end of file diff --git a/migrations/versions/e7a12026a007_security_grants.py b/migrations/versions/e7a12026a007_security_grants.py new file mode 100644 index 00000000..6dc4b965 --- /dev/null +++ b/migrations/versions/e7a12026a007_security_grants.py @@ -0,0 +1,46 @@ +"""Configure restricted database roles for lab7.""" + +from alembic import op + + +revision = "e7a12026a007" +down_revision = "d6a12026a006" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute(""" + GRANT SELECT, UPDATE ON TABLE + public.attachments, + public.attachment_jobs + TO messenger_worker + """) + + op.execute(""" + GRANT SELECT, UPDATE ON TABLE + public.attachments, + public.attachment_jobs + TO messenger_dispatcher + """) + + op.execute(""" + REVOKE ALL ON TABLE public.alembic_version + FROM messenger_api + """) + + +def downgrade(): + op.execute(""" + REVOKE SELECT, UPDATE ON TABLE + public.attachments, + public.attachment_jobs + FROM messenger_worker + """) + + op.execute(""" + REVOKE SELECT, UPDATE ON TABLE + public.attachments, + public.attachment_jobs + FROM messenger_dispatcher + """) diff --git a/migrations/versions/f7c51e1e945b_initial_schema.py b/migrations/versions/f7c51e1e945b_initial_schema.py new file mode 100644 index 00000000..5bc1512b --- /dev/null +++ b/migrations/versions/f7c51e1e945b_initial_schema.py @@ -0,0 +1,110 @@ +"""initial schema + +Revision ID: f7c51e1e945b +Revises: +Create Date: 2026-10-07 18:33:37.771593 + +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = "f7c51e1e945b" +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.create_table( + "users", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("username", sa.String(length=32), nullable=False), + sa.Column("display_name", sa.String(length=100), nullable=False), + sa.Column("password_hash", sa.Text(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("username", name="uq_users_username"), + ) + + op.create_table( + "chats", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("title", sa.String(length=100), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.PrimaryKeyConstraint("id"), + ) + + op.create_table( + "chat_members", + sa.Column("chat_id", sa.Uuid(), nullable=False), + sa.Column("user_id", sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint( + ["chat_id"], + ["chats.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["user_id"], + ["users.id"], + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("chat_id", "user_id"), + ) + + op.create_table( + "messages", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("chat_id", sa.Uuid(), nullable=False), + sa.Column("sender_id", sa.Uuid(), nullable=False), + sa.Column("text", sa.String(length=4000), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + sa.ForeignKeyConstraint( + ["chat_id"], + ["chats.id"], + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["sender_id"], + ["users.id"], + ondelete="RESTRICT", + ), + sa.PrimaryKeyConstraint("id"), + ) + + op.create_index( + "ix_messages_chat_created_id", + "messages", + ["chat_id", "created_at", "id"], + unique=False, + ) + + +def downgrade() -> None: + op.drop_index( + "ix_messages_chat_created_id", + table_name="messages", + ) + op.drop_table("messages") + op.drop_table("chat_members") + op.drop_table("chats") + op.drop_table("users") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..a00f0567 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,34 @@ +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.15.1 +click==8.5.0 +fastapi==0.141.1 +h11==0.16.0 +idna==3.20 +pydantic==2.13.5 +pydantic_core==2.46.5 +starlette==1.7.0 +typing-inspection==0.4.4 +typing_extensions==4.16.0 +uvicorn==0.53.0 +SQLAlchemy==2.1.4 +asyncpg==0.32.0 +alembic==1.20.0 +greenlet==3.5.6 +argon2-cffi==25.1.0 +redis==7.0.1 +boto3==1.43.120 +Pillow==13.0.0 +python-multipart==0.0.32 +pika==1.3.2 +opentelemetry-api==1.45.2 +opentelemetry-sdk==1.45.2 +opentelemetry-exporter-otlp-proto-http==1.45.2 +opentelemetry-instrumentation-fastapi==0.66b2 +opentelemetry-instrumentation-asgi==0.66b2 +opentelemetry-instrumentation-logging==0.66b2 +opentelemetry-instrumentation-botocore==0.66b2 +opentelemetry-instrumentation-pika==0.66b2 +opentelemetry-semantic-conventions==0.66b2 + +openapi-spec-validator==0.7.2 diff --git a/scripts/bao-entrypoint.py b/scripts/bao-entrypoint.py new file mode 100644 index 00000000..205d5813 --- /dev/null +++ b/scripts/bao-entrypoint.py @@ -0,0 +1,150 @@ +import json +import os +import ssl +import sys +import time +from pathlib import Path +from urllib.request import Request, urlopen + +BASE_URL = "https://openbao:8200/v1" + +IDENTITY = os.environ["BAO_IDENTITY"] +ROLE = os.environ["BAO_ROLE"] + +SECRET_DIR = Path("/run/app-secrets") + +EXPECTED = { + "api": { + "database_url", + "cache_url", + "s3_access_key_id", + "s3_secret_access_key", + "otel_password", + }, + "worker": { + "database_url", + "s3_access_key_id", + "s3_secret_access_key", + "rabbitmq_password", + "otel_password", + }, + "dispatcher": { + "database_url", + "rabbitmq_password", + "otel_password", + }, +} + +context = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +context.minimum_version = ssl.TLSVersion.TLSv1_2 + +context.load_cert_chain( + certfile="/run/bao-client/tls.crt", + keyfile="/run/bao-client/tls.key", +) + + +def request(path, method="GET", data=None, token=None): + headers = {"Content-Type": "application/json"} + + if token: + headers["X-Vault-Token"] = token + + body = ( + json.dumps(data).encode() + if data is not None + else None + ) + + req = Request( + BASE_URL + path, + headers=headers, + data=body, + method=method, + ) + + with urlopen( + req, context=context, timeout=10 + ) as response: + return json.load(response) + + +def fetch_secrets(): + result = request( + "/auth/cert/login", + "POST", + {"name": IDENTITY}, + ) + + auth = result["auth"] + + if set(auth["policies"]) != {f"messenger-{ROLE}"}: + raise RuntimeError("Unexpected OpenBao policy") + + if not 0 < auth["lease_duration"] <= 900: + raise RuntimeError("Unexpected token TTL") + + result = request( + f"/secret/data/messenger/{ROLE}", + token=auth["client_token"], + ) + + values = result["data"]["data"] + + if set(values) != EXPECTED[ROLE]: + raise RuntimeError("Unexpected secret set") + + if not all( + isinstance(value, str) and value + for value in values.values() + ): + raise RuntimeError("Invalid secret value") + + return values + + +def main(): + if len(sys.argv) < 2: + raise SystemExit("Missing application command") + + os.umask(0o077) + + for attempt in range(1, 7): + try: + values = fetch_secrets() + break + except Exception as exc: + print( + f"OpenBao attempt {attempt}/6 failed: " + f"{type(exc).__name__}", + flush=True, + ) + + if attempt == 6: + raise SystemExit( + "ERROR: OpenBao unavailable" + ) from None + + time.sleep(5) + + for name, value in values.items(): + path = SECRET_DIR / name + path.write_text(value + "\n") + path.chmod(0o600) + + print( + f"PASS: OpenBao identity={IDENTITY}, " + f"role={ROLE}, secrets={len(values)}", + flush=True, + ) + + del values + + os.execvp(sys.argv[1], sys.argv[1:]) + + +if __name__ == "__main__": + main() diff --git a/scripts/bootstrap-data-security.sh b/scripts/bootstrap-data-security.sh new file mode 100755 index 00000000..22fc3c02 --- /dev/null +++ b/scripts/bootstrap-data-security.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +umask 077 + +mkdir -p secrets +chmod 700 secrets + +python3 - <<'PY' +from pathlib import Path +import secrets +import hashlib + +directory = Path("secrets") + + +def save(name, value): + path = directory / name + path.write_text(value + "\n") + path.chmod(0o644) + + +def password(name): + path = directory / name + + if not path.exists(): + save(name, secrets.token_hex(32)) + + return path.read_text().strip() + + +for role in ("migrate", "api", "worker", "dispatcher"): + secret = password(f"db_{role}_password") + + save( + f"database_url_{role}", + f"postgresql+asyncpg://messenger_{role}:" + f"{secret}@postgres:5432/messenger", + ) + +redis_password = password("redis_api_password") + +digest = hashlib.sha256( + redis_password.encode() +).hexdigest() + +save( + "redis_acl", + "user default off\n" + f"user messenger_api on #{digest} " + "~session:* ~rate:login:* " + "-@all +ping +get +set +del " + "+incr +expire +ttl +eval " + "+client|setinfo +client|setname +select", +) + +save( + "cache_url", + f"rediss://messenger_api:{redis_password}@redis:6379/0", +) + +print("PASS: PostgreSQL and Redis credentials generated") +PY diff --git a/scripts/bootstrap-messaging-security.sh b/scripts/bootstrap-messaging-security.sh new file mode 100755 index 00000000..0a6971bb --- /dev/null +++ b/scripts/bootstrap-messaging-security.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +umask 077 + +mkdir -p secrets infra/rabbitmq +chmod 700 secrets + +python3 - <<'PY' +import json +import secrets +import hashlib +import base64 +from pathlib import Path + +directory = Path("secrets") + + +def password(name, size=32): + path = directory / name + + if not path.exists(): + path.write_text(secrets.token_hex(size) + "\n") + + path.chmod(0o644) + + return path.read_text().strip() + + +for role in ("api", "worker"): + password(f"s3_{role}_access_key_id", 10) + password(f"s3_{role}_secret_access_key") + +users = [] + +for role in ("admin", "producer", "consumer"): + value = password(f"rabbitmq_{role}_password") + + salt = secrets.token_bytes(4) + digest = hashlib.sha256( + salt + value.encode() + ).digest() + + users.append({ + "name": f"messenger_{role}", + "password_hash": base64.b64encode( + salt + digest + ).decode(), + "hashing_algorithm": "rabbit_password_hashing_sha256", + "tags": ["administrator"] if role == "admin" else [], + }) + +definitions = { + "users": users, + "vhosts": [{"name": "messenger"}], + "permissions": [ + { + "user": "messenger_admin", + "vhost": "messenger", + "configure": ".*", + "write": ".*", + "read": ".*", + }, + { + "user": "messenger_producer", + "vhost": "messenger", + "configure": "^$a", + "write": "^amq\\.default$", + "read": "^$a", + }, + { + "user": "messenger_consumer", + "vhost": "messenger", + "configure": "^$a", + "write": "^$a", + "read": "^attachment\\.process\\.v1$", + }, + ], + "queues": [ + { + "name": name, + "vhost": "messenger", + "durable": True, + "auto_delete": False, + "arguments": {}, + } + for name in ( + "attachment.process.v1", + "attachment.failed.v1", + ) + ], +} + +path = directory / "rabbitmq_definitions.json" + +path.write_text( + json.dumps(definitions, indent=2) + "\n" +) + +path.chmod(0o644) + +print("PASS: separate S3 and RabbitMQ credentials generated") +PY diff --git a/scripts/bootstrap-telemetry-security.sh b/scripts/bootstrap-telemetry-security.sh new file mode 100755 index 00000000..650ff0a8 --- /dev/null +++ b/scripts/bootstrap-telemetry-security.sh @@ -0,0 +1,208 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +umask 077 +mkdir -p secrets +chmod 700 secrets + +python3 - <<'PY' +from pathlib import Path +import secrets + +directory = Path("secrets") + +for name in ( + "otel_api_password", + "otel_worker_password", + "otel_dispatcher_password", + "prometheus_scrape_password", + "grafana_datasource_password", + "otel_backend_password", +): + path = directory / name + + if not path.exists(): + path.write_text(secrets.token_hex(32) + "\n") + + path.chmod(0o644) + + print(f"PASS: {name} prepared") +PY + +{ + for role in api worker dispatcher + do + printf '%s\n' "$(cat "secrets/otel_${role}_password")" | + docker run --rm -i \ + --entrypoint htpasswd \ + httpd:2.4-alpine \ + -niB "messenger_${role}" + done +} > secrets/otel_htpasswd.tmp + +chmod 644 secrets/otel_htpasswd.tmp + +mv secrets/otel_htpasswd.tmp secrets/otel_htpasswd + +echo "PASS: Collector authentication file prepared" + +printf '%s\n' "$(cat secrets/otel_backend_password)" | + docker run --rm -i \ + --entrypoint htpasswd \ + httpd:2.4-alpine \ + -niB collector > secrets/otel_backend_htpasswd.tmp + +printf '%s\n' "$(cat secrets/grafana_datasource_password)" | + docker run --rm -i \ + --entrypoint htpasswd \ + httpd:2.4-alpine \ + -niB grafana > secrets/grafana_datasource_htpasswd.tmp + +for name in otel_backend_htpasswd grafana_datasource_htpasswd +do + chmod 644 "secrets/$name.tmp" + mv "secrets/$name.tmp" "secrets/$name" +done + +echo "PASS: backend authentication files prepared" + +python3 - <<'PY' +import base64 +from pathlib import Path + +directory = Path("secrets") + +password = ( + directory / "otel_backend_password" +).read_text().strip() + +encoded = base64.b64encode( + f"collector:{password}".encode() +).decode() + +path = directory / "otel_backend_authorization" + +path.write_text(f"Basic {encoded}") +path.chmod(0o644) + +print("PASS: Collector backend authorization prepared") +PY + +printf '%s\n' "$(cat secrets/prometheus_scrape_password)" | + docker run --rm -i \ + --entrypoint htpasswd \ + httpd:2.4-alpine \ + -niB prometheus > secrets/prometheus_scrape_htpasswd.tmp + +chmod 644 secrets/prometheus_scrape_htpasswd.tmp + +mv secrets/prometheus_scrape_htpasswd.tmp \ + secrets/prometheus_scrape_htpasswd + +echo "PASS: Prometheus scrape authentication prepared" + +python3 - <<'PY' +from pathlib import Path + +directory = Path("secrets") + +users = {} + +for filename in ( + "grafana_datasource_htpasswd", + "prometheus_scrape_htpasswd", +): + for line in (directory / filename).read_text().splitlines(): + if line.strip(): + username, password_hash = line.split(":", 1) + users[username] = password_hash + +assert set(users) == {"grafana", "prometheus"} + +lines = [ + "tls_server_config:", + " cert_file: /run/tls/tls.crt", + " key_file: /run/tls/tls.key", + " min_version: TLS12", + "", + "basic_auth_users:", +] + +for username, password_hash in users.items(): + lines.append(f' {username}: "{password_hash}"') + +path = directory / "prometheus_web.yaml" +path.write_text("\n".join(lines) + "\n") +path.chmod(0o644) + +print("PASS: Prometheus HTTPS web configuration prepared") +PY + +python3 - <<'PY' +from pathlib import Path +import json + +password = Path( + "secrets/grafana_datasource_password" +).read_text().strip() + +ca = Path("certs/ca/ca.crt").read_text() + +source = Path( + "infra/grafana/provisioning/datasources/datasources.yaml" +).read_text() + +for service, port in ( + ("prometheus", 9090), + ("loki", 3100), + ("tempo", 3200), +): + old = f" url: http://{service}:{port}" + + assert source.count(old) == 1, old + + new = ( + f" url: https://{service}:{port}\n" + " basicAuth: true\n" + " basicAuthUser: grafana\n" + " secureJsonData:\n" + f" basicAuthPassword: {json.dumps(password)}\n" + f" tlsCACert: {json.dumps(ca)}" + ) + + source = source.replace(old, new, 1) + +source = source.replace( + " jsonData:\n", + " jsonData:\n" + " tlsAuthWithCACert: true\n" + " tlsSkipVerify: false\n", +) + +start = source.index(" - name: Prometheus") +end = source.index(" - name: Loki", start) + +block = source[start:end] + +if " jsonData:" not in block: + block = block.rstrip() + ( + "\n jsonData:\n" + " tlsAuthWithCACert: true\n" + " tlsSkipVerify: false\n\n" + ) + + source = source[:start] + block + source[end:] + +assert source.count("tlsAuthWithCACert: true") == 3 +assert source.count("tlsSkipVerify: false") == 3 +assert source.count("basicAuth: true") == 3 +assert "url: http://" not in source + +path = Path("secrets/grafana_datasources.yaml") +path.write_text(source) +path.chmod(0o644) + +print("PASS: Grafana HTTPS datasources prepared") +PY diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh new file mode 100755 index 00000000..f8f246b9 --- /dev/null +++ b/scripts/bootstrap.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +bash scripts/generate-certs.sh +bash scripts/configure-mtls.sh +bash scripts/prepare-tls-permissions.sh +bash scripts/bootstrap-data-security.sh +bash scripts/bootstrap-messaging-security.sh +bash scripts/bootstrap-telemetry-security.sh + +mkdir -p secrets +chmod 700 secrets +umask 077 + +create_random_secret() { + local name="$1" + local value="$2" + + if [[ ! -s "secrets/$name" ]]; then + printf '%s\n' "$value" > "secrets/$name" + fi + + chmod 644 "secrets/$name" +} + +create_random_secret postgres_password "$(python3 -c 'import secrets; print(secrets.token_hex(24))')" + +create_random_secret minio_root_user "minio-$(python3 -c 'import secrets; print(secrets.token_hex(12))')" +create_random_secret minio_root_password "$(python3 -c 'import secrets; print(secrets.token_hex(32))')" + +chmod 644 secrets/* + +if [[ ! -f .env ]]; then + cp .env.example .env +fi + +if ! grep -qE '^GRAFANA_ADMIN_PASSWORD=.+$' .env; then + sed -i '/^GRAFANA_ADMIN_PASSWORD=/d' .env + printf '\nGRAFANA_ADMIN_PASSWORD=%s\n' \ + "$(python3 -c 'import secrets; print(secrets.token_hex(24))')" >> .env +fi + +chmod 600 .env + +docker compose config --quiet diff --git a/scripts/cleanup_staging.py b/scripts/cleanup_staging.py new file mode 100644 index 00000000..6e68bed0 --- /dev/null +++ b/scripts/cleanup_staging.py @@ -0,0 +1,68 @@ +import argparse +import asyncio +import os +from datetime import datetime, timedelta, timezone + +from sqlalchemy import text + +from src.database import SessionFactory, engine +from src.storage import delete_object, object_exists + + +RETENTION_SECONDS = int(os.getenv("STAGING_RETENTION_SECONDS", "86400")) + + +async def cleanup(apply: bool): + cutoff = datetime.now(timezone.utc) - timedelta(seconds=RETENTION_SECONDS) + + async with SessionFactory() as session: + result = await session.execute( + text(""" + SELECT a.id, a.chat_id, a.content_type, a.s3_key, + a.created_at + FROM attachments a + JOIN attachment_jobs j ON j.attachment_id = a.id + WHERE a.status = 'ready' + AND j.status = 'ready' + AND a.s3_key LIKE 'attachments/%' + AND a.created_at < :cutoff + """), + {"cutoff": cutoff}, + ) + + rows = result.all() + + candidates = 0 + + for row in rows: + extension = "png" if row.content_type == "image/png" else "jpg" + staging_key = f"staging/{row.chat_id}/{row.id}.{extension}" + + if not await object_exists(staging_key): + continue + + candidates += 1 + + if not apply: + print(f"DRY RUN: {staging_key}") + continue + + await delete_object(staging_key) + print(f"DELETED: {staging_key}") + + print(f"Candidates: {candidates}") + + +async def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--apply", action="store_true") + args = parser.parse_args() + + try: + await cleanup(args.apply) + finally: + await engine.dispose() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/scripts/configure-mtls.sh b/scripts/configure-mtls.sh new file mode 100755 index 00000000..070d7b55 --- /dev/null +++ b/scripts/configure-mtls.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +fingerprint="$( + openssl x509 \ + -in certs/services/lb-client/tls.crt \ + -noout -fingerprint -sha1 \ + | cut -d= -f2 \ + | tr -d ':' \ + | tr '[:upper:]' '[:lower:]' +)" + +[[ "$fingerprint" =~ ^[0-9a-f]{40}$ ]] + +mkdir -p certs/generated + +sed "s/__LB_FINGERPRINT__/$fingerprint/g" \ + infra/api-proxy/nginx.conf.template \ + > certs/generated/api-proxy.conf + +chmod 644 certs/generated/api-proxy.conf + +echo "PASS: mTLS identity configuration generated" diff --git a/scripts/configure-openbao.py b/scripts/configure-openbao.py new file mode 100644 index 00000000..adc34ec2 --- /dev/null +++ b/scripts/configure-openbao.py @@ -0,0 +1,124 @@ +import json +import ssl +import sys +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +BASE_URL = "https://openbao:8200/v1" + +CONTEXT = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +ROOT_TOKEN = sys.stdin.readline().strip() + +assert ROOT_TOKEN, "Operator token required" + + +def request(path, method="GET", data=None): + headers = { + "X-Vault-Token": ROOT_TOKEN, + "Content-Type": "application/json", + } + + body = ( + json.dumps(data).encode() + if data is not None + else None + ) + + req = Request( + BASE_URL + path, + headers=headers, + data=body, + method=method, + ) + + try: + with urlopen( + req, context=CONTEXT, timeout=15 + ) as response: + raw = response.read() + return json.loads(raw) if raw else {} + except HTTPError as exc: + raise RuntimeError( + f"{method} {path}: HTTP {exc.code}" + ) from None + + +mounts = request("/sys/mounts")["data"] + +if "secret/" not in mounts: + request( + "/sys/mounts/secret", + "POST", + { + "type": "kv", + "options": {"version": "2"}, + }, + ) +else: + assert mounts["secret/"]["type"] == "kv" + assert mounts["secret/"]["options"]["version"] == "2" + +print("PASS: KV v2 enabled") + +auth = request("/sys/auth")["data"] + +if "cert/" not in auth: + request( + "/sys/auth/cert", + "POST", + {"type": "cert"}, + ) +else: + assert auth["cert/"]["type"] == "cert" + +print("PASS: certificate authentication enabled") + +for role in ("api", "worker", "dispatcher"): + policy = Path( + f"/operator/policies/{role}.hcl" + ).read_text() + + request( + f"/sys/policies/acl/messenger-{role}", + "PUT", + {"policy": policy}, + ) + + print(f"PASS: messenger-{role} policy configured") + +identities = { + "bao-api-1": "api", + "bao-api-2": "api", + "bao-worker": "worker", + "bao-dispatcher": "dispatcher", +} + +for identity, role in identities.items(): + certificate = Path( + f"/operator/certificates/{identity}.crt" + ).read_text() + + request( + f"/auth/cert/certs/{identity}", + "POST", + { + "certificate": certificate, + "allowed_common_names": [identity], + "allowed_dns_sans": [identity], + "token_policies": [f"messenger-{role}"], + "token_ttl": "15m", + "token_max_ttl": "1h", + "token_no_default_policy": True, + }, + ) + + print( + f"PASS: {identity} -> messenger-{role}, " + "TTL=15m, max TTL=1h" + ) + +print("\nPASS: OPENBAO CONFIGURATION") diff --git a/scripts/configure-openbao.sh b/scripts/configure-openbao.sh new file mode 100755 index 00000000..76732825 --- /dev/null +++ b/scripts/configure-openbao.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +operator_file="${BAO_OPERATOR_FILE:-${HOME}/.local/share/lab7-openbao-operator/init.json}" + +test -r "$operator_file" + +args=() + +for identity in bao-api-1 bao-api-2 bao-worker bao-dispatcher +do + args+=( + -v "$PWD/certs/services/$identity/tls.crt:/operator/certificates/$identity.crt:ro" + ) +done + +python3 - "$operator_file" <<'PY' | \ + docker compose run --rm --no-deps -T \ + "${args[@]}" \ + -v "$PWD/infra/openbao/policies:/operator/policies:ro" \ + -v "$PWD/scripts/configure-openbao.py:/operator/configure.py:ro" \ + --entrypoint python migrate \ + /operator/configure.py +import json +import sys +from pathlib import Path + +data = json.loads(Path(sys.argv[1]).read_text()) + +print(data["root_token"]) +PY diff --git a/scripts/generate-certs.sh b/scripts/generate-certs.sh new file mode 100755 index 00000000..49bac24c --- /dev/null +++ b/scripts/generate-certs.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +umask 077 + +mkdir -p certs/ca certs/private certs/services + +if [[ ! -s certs/ca/ca.crt && ! -s certs/private/ca.key ]]; then + openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:3072 \ + -out certs/private/ca.key + + openssl req -new -x509 \ + -key certs/private/ca.key \ + -sha256 \ + -days 365 \ + -subj "/CN=Lab7 Local CA" \ + -addext "basicConstraints=critical,CA:TRUE,pathlen:0" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + -out certs/ca/ca.crt +fi + +test -s certs/ca/ca.crt +test -s certs/private/ca.key + +chmod 644 certs/ca/ca.crt +chmod 600 certs/private/ca.key + +issue_certificate() { + local name="$1" + local usage="$2" + local san="$3" + local dir="certs/services/$name" + + mkdir -p "$dir" + + if [[ -s "$dir/tls.crt" && -s "$dir/tls.key" ]]; then + openssl verify -CAfile certs/ca/ca.crt "$dir/tls.crt" + return + fi + + openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:2048 \ + -out "$dir/tls.key" + + openssl req -new \ + -key "$dir/tls.key" \ + -subj "/CN=$name" \ + -out "$dir/tls.csr" + + cat > "$dir/extensions.cnf" <&2 + exit 1 +fi + +set +e +docker compose exec -T openbao bao operator init \ + -status >/dev/null 2>&1 +status=$? +set -e + +case "$status" in + 0) + echo "ERROR: OpenBao is already initialized" >&2 + exit 1 + ;; + 2) + ;; + *) + echo "ERROR: cannot determine OpenBao initialization status" >&2 + exit 1 + ;; +esac + +( + set -o noclobber + + docker compose exec -T openbao bao operator init \ + -key-shares=3 \ + -key-threshold=2 \ + -format=json > "$operator_file" +) + +chmod 600 "$operator_file" + +python3 - "$operator_file" <<'PY' +import json +import sys +from pathlib import Path + +data = json.loads(Path(sys.argv[1]).read_text()) + +assert len(data["unseal_keys_b64"]) == 3 +assert data["root_token"] + +print("PASS: OpenBao initialized; operator material saved outside Git") +PY diff --git a/scripts/prepare-tls-permissions.sh b/scripts/prepare-tls-permissions.sh new file mode 100755 index 00000000..71dabfb9 --- /dev/null +++ b/scripts/prepare-tls-permissions.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +prepare_service() { + local service="$1" + local uid="$2" + local gid="$3" + + local source="certs/services/$service" + local target="certs/runtime/$service" + + sudo install -d -m 750 \ + -o "$uid" -g "$gid" "$target" + + sudo install -m 644 \ + -o "$uid" -g "$gid" \ + "$source/tls.crt" "$target/tls.crt" + + sudo install -m 600 \ + -o "$uid" -g "$gid" \ + "$source/tls.key" "$target/tls.key" + + echo "PASS: $service TLS permissions configured" +} + +prepare_service postgres 999 999 +prepare_service redis 999 999 +prepare_service rabbitmq 100 101 +prepare_service otel-collector 10001 10001 +prepare_service loki 10001 10001 +prepare_service tempo 10001 10001 +prepare_service grafana 472 472 +prepare_service prometheus 65534 65534 + +prepare_service bao-api-1 10001 10001 +prepare_service bao-api-2 10001 10001 +prepare_service bao-worker 10001 10001 +prepare_service bao-dispatcher 10001 10001 + +prepare_service openbao 100 1000 + +sudo install -d -m 700 -o 100 -g 1000 openbao-local/data + +echo "PASS: runtime TLS permissions prepared" diff --git a/scripts/replay_job.py b/scripts/replay_job.py new file mode 100644 index 00000000..d4a23bb0 --- /dev/null +++ b/scripts/replay_job.py @@ -0,0 +1,83 @@ + +import argparse +import asyncio +from uuid import UUID + +from sqlalchemy import text + +from src.database import SessionFactory, engine + + +async def replay(job_id: UUID): + async with SessionFactory() as session: + async with session.begin(): + result = await session.execute( + text(""" + SELECT j.id, j.attachment_id, j.status, + j.generation, a.status AS attachment_status + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = :job_id + FOR UPDATE OF j, a + """), + {"job_id": job_id}, + ) + + row = result.one_or_none() + + if row is None: + print("REJECTED: job not found") + return + + if row.status != "failed" or row.attachment_status != "failed": + print("REJECTED: job and attachment must be failed") + return + + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'queued', + generation = generation + 1, + attempt = 1, + published_at = NULL, + started_at = NULL, + execution_id = NULL, + next_attempt_at = NULL, + last_error_code = NULL, + finished_at = NULL, + failed_published_at = NULL + WHERE id = :job_id + """), + {"job_id": job_id}, + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'queued', + error_code = NULL, + updated_at = now() + WHERE id = :attachment_id + """), + {"attachment_id": row.attachment_id}, + ) + + print( + f"REPLAY ACCEPTED: job={job_id}, " + f"generation={row.generation + 1}" + ) + + +async def main(): + parser = argparse.ArgumentParser() + parser.add_argument("job_id", type=UUID) + args = parser.parse_args() + + try: + await replay(args.job_id) + finally: + await engine.dispose() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..c7c85485 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +echo "Stopping application services..." + +docker compose stop -t 5 \ + nginx \ + api-1-proxy api-2-proxy \ + api-1 api-2 \ + worker dispatcher + +echo "Restarting persistent services..." + +docker compose restart -t 5 \ + postgres redis rabbitmq s3 \ + prometheus grafana \ + loki tempo openbao + +echo "Unsealing OpenBao..." + +bash scripts/unseal-openbao.sh + +echo "Restarting telemetry services..." + +docker compose restart -t 5 \ + loki-proxy tempo-proxy \ + otel-collector otel-collector-proxy + +echo "Starting application services..." + +docker compose start \ + api-1 api-2 \ + worker dispatcher + +docker compose start \ + api-1-proxy api-2-proxy nginx + +echo "PASS: restart completed without deleting volumes" diff --git a/scripts/seed-openbao.py b/scripts/seed-openbao.py new file mode 100644 index 00000000..9b379801 --- /dev/null +++ b/scripts/seed-openbao.py @@ -0,0 +1,46 @@ +import json +import ssl +import sys +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +BASE_URL = "https://openbao:8200/v1" + +CONTEXT = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +payload = json.load(sys.stdin) + +root_token = payload["root_token"] + +for role, values in payload["secrets"].items(): + request = Request( + f"{BASE_URL}/secret/data/messenger/{role}", + data=json.dumps({"data": values}).encode(), + headers={ + "X-Vault-Token": root_token, + "Content-Type": "application/json", + }, + method="POST", + ) + + try: + with urlopen( + request, + context=CONTEXT, + timeout=15, + ) as response: + result = json.load(response) + except HTTPError as exc: + raise SystemExit( + f"ERROR: {role}: HTTP {exc.code}" + ) from None + + print( + f"PASS: messenger/{role}: " + f"{len(values)} secrets stored, " + f"version={result['data']['version']}" + ) + +print("\nPASS: OPENBAO SECRETS SEEDED") diff --git a/scripts/seed-openbao.sh b/scripts/seed-openbao.sh new file mode 100755 index 00000000..652084d0 --- /dev/null +++ b/scripts/seed-openbao.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +operator_file="${BAO_OPERATOR_FILE:-${HOME}/.local/share/lab7-openbao-operator/init.json}" + +test -r "$operator_file" + +python3 - "$operator_file" <<'PY' | \ + docker compose run --rm --no-deps -T \ + -v "$PWD/scripts/seed-openbao.py:/operator/seed.py:ro" \ + --entrypoint python migrate \ + /operator/seed.py +import json +import sys +from pathlib import Path + +operator = json.loads( + Path(sys.argv[1]).read_text() +) + +mapping = { + "api": { + "database_url": "database_url_api", + "cache_url": "cache_url", + "s3_access_key_id": "s3_api_access_key_id", + "s3_secret_access_key": "s3_api_secret_access_key", + "otel_password": "otel_api_password", + }, + "worker": { + "database_url": "database_url_worker", + "s3_access_key_id": "s3_worker_access_key_id", + "s3_secret_access_key": "s3_worker_secret_access_key", + "rabbitmq_password": "rabbitmq_consumer_password", + "otel_password": "otel_worker_password", + }, + "dispatcher": { + "database_url": "database_url_dispatcher", + "rabbitmq_password": "rabbitmq_producer_password", + "otel_password": "otel_dispatcher_password", + }, +} + +values = {} + +for role, files in mapping.items(): + values[role] = {} + + for name, filename in files.items(): + value = (Path("secrets") / filename).read_text().strip() + + assert value, f"Empty secret: {filename}" + + values[role][name] = value + +print(json.dumps({ + "root_token": operator["root_token"], + "secrets": values, +})) +PY diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..451835fc --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +: "${TARGET_INSTANCE_ID:?}" + +case "$TARGET_INSTANCE_ID" in + api-1|api-2) + docker compose stop -t 2 \ + "${TARGET_INSTANCE_ID}-proxy" \ + "$TARGET_INSTANCE_ID" + + echo "PASS: stopped $TARGET_INSTANCE_ID and its TLS proxy" + ;; + *) + echo "Unknown instance: $TARGET_INSTANCE_ID" >&2 + exit 1 + ;; +esac diff --git a/scripts/unseal-openbao.sh b/scripts/unseal-openbao.sh new file mode 100755 index 00000000..f9cb9841 --- /dev/null +++ b/scripts/unseal-openbao.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +operator_file="${BAO_OPERATOR_FILE:-${HOME}/.local/share/lab7-openbao-operator/init.json}" + +test -r "$operator_file" + +python3 - "$operator_file" <<'PY' | \ + docker compose run --rm --no-deps -T \ + --entrypoint python migrate \ + -c ' +import json +import ssl +import sys +from urllib.request import Request, urlopen + +context = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +base_url = "https://openbao:8200" + +with urlopen( + base_url + "/v1/sys/seal-status", + context=context, + timeout=10, +) as response: + status = json.load(response) + +if not status["initialized"]: + raise SystemExit("ERROR: OpenBao is not initialized") + +if not status["sealed"]: + print("PASS: OpenBao is already unsealed") + raise SystemExit(0) + +keys = json.load(sys.stdin) + +for key in keys: + request = Request( + base_url + "/v1/sys/unseal", + data=json.dumps({"key": key}).encode(), + headers={"Content-Type": "application/json"}, + method="PUT", + ) + + with urlopen( + request, context=context, timeout=10 + ) as response: + result = json.load(response) + + print( + "Sealed:", result["sealed"], + "| Progress:", result["progress"], + "| Threshold:", result["t"], + ) + + if not result["sealed"]: + print("PASS: OpenBao successfully unsealed") + break +else: + raise SystemExit("ERROR: OpenBao remains sealed") +' +import json +import sys +from pathlib import Path + +data = json.loads(Path(sys.argv[1]).read_text()) + +print(json.dumps(data["unseal_keys_b64"][:2])) +PY diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/cursor.py b/src/cursor.py new file mode 100644 index 00000000..23dfb48b --- /dev/null +++ b/src/cursor.py @@ -0,0 +1,86 @@ +import base64 +import binascii +import json +from datetime import datetime +from uuid import UUID + + +def encode_cursor( + chat_id: UUID, + created_at: datetime, + message_id: UUID, +) -> str: + data = { + "chat_id": str(chat_id), + "created_at": created_at.isoformat(), + "message_id": str(message_id), + } + + raw = json.dumps( + data, + separators=(",", ":"), + ).encode("utf-8") + + return base64.urlsafe_b64encode(raw).decode("ascii") + + +def decode_cursor(cursor: str) -> tuple[UUID, datetime, UUID]: + try: + raw = base64.urlsafe_b64decode(cursor.encode("ascii")) + + data = json.loads(raw.decode("utf-8")) + + if not isinstance(data, dict): + raise ValueError("Invalid cursor") + + if set(data.keys()) != { + "chat_id", + "created_at", + "message_id", + }: + raise ValueError("Invalid cursor") + + chat_id = UUID(data["chat_id"]) + created_at = datetime.fromisoformat(data["created_at"]) + message_id = UUID(data["message_id"]) + + if created_at.tzinfo is None or created_at.utcoffset() is None: + raise ValueError("Invalid cursor") + + return chat_id, created_at, message_id + + except ( + ValueError, + KeyError, + TypeError, + UnicodeError, + binascii.Error, + json.JSONDecodeError, + ) as exc: + raise ValueError("Invalid cursor") from exc + + +def encode_chat_cursor(user_id: UUID, created_at: datetime, chat_id: UUID) -> str: + data = { + "user_id": str(user_id), + "created_at": created_at.isoformat(), + "chat_id": str(chat_id), + } + raw = json.dumps(data, separators=(",", ":")).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii") + + +def decode_chat_cursor(cursor: str) -> tuple[UUID, datetime, UUID]: + try: + raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True) + data = json.loads(raw.decode("utf-8")) + if not isinstance(data, dict) or set(data) != {"user_id", "created_at", "chat_id"}: + raise ValueError("Invalid cursor") + user_id = UUID(data["user_id"]) + created_at = datetime.fromisoformat(data["created_at"]) + chat_id = UUID(data["chat_id"]) + if created_at.tzinfo is None or created_at.utcoffset() is None: + raise ValueError("Invalid cursor") + return user_id, created_at, chat_id + except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error, json.JSONDecodeError) as exc: + raise ValueError("Invalid cursor") from exc diff --git a/src/database.py b/src/database.py new file mode 100644 index 00000000..bc6699f2 --- /dev/null +++ b/src/database.py @@ -0,0 +1,183 @@ +from collections.abc import AsyncIterator + +import socket +import ssl +from threading import Lock + +from sqlalchemy.pool import AsyncAdaptedQueuePool +from sqlalchemy.util.queue import AsyncAdaptedQueue + +from sqlalchemy import event, text +from opentelemetry import trace +from opentelemetry.trace import SpanKind, Status, StatusCode +from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.ext.asyncio import ( + AsyncSession, + async_sessionmaker, + create_async_engine, +) + + +DATABASE_URL_FILE = "/run/app-secrets/database_url" + +POOL_SIZE = 5 +MAX_OVERFLOW = 5 +POOL_TIMEOUT_SECONDS = 5 +DB_CONNECT_TIMEOUT_SECONDS = 5 + + +def read_database_url() -> str: + with open(DATABASE_URL_FILE, encoding="utf-8") as file: + return file.read().strip() + + +class MeasuredQueue(AsyncAdaptedQueue): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.waiting = 0 + self.waiting_lock = Lock() + + def get(self, block=True, timeout=None): + waiting = block and self.empty() + + if waiting: + with self.waiting_lock: + self.waiting += 1 + + try: + return super().get(block, timeout) + finally: + if waiting: + with self.waiting_lock: + self.waiting -= 1 + + +class MeasuredPool(AsyncAdaptedQueuePool): + _queue_class = MeasuredQueue + + def connect(self): + tracer = trace.get_tracer("messenger.database") + + with tracer.start_as_current_span( + "postgresql.pool.acquire", + kind=SpanKind.CLIENT, + attributes={ + "db.system.name": "postgresql", + "db.operation.name": "CONNECT", + "server.address": "postgres", + }, + record_exception=False, + set_status_on_exception=False, + ) as span: + try: + connection = super().connect() + except BaseException as exc: + span.set_attribute( + "error.type", type(exc).__name__ + ) + span.set_status(Status(StatusCode.ERROR)) + raise + + span.set_status(Status(StatusCode.OK)) + return connection + + def waiting_count(self): + with self._pool.waiting_lock: + return self._pool.waiting + + +database_url = read_database_url() + +engine = create_async_engine( + database_url, + poolclass=MeasuredPool, + pool_size=POOL_SIZE, + max_overflow=MAX_OVERFLOW, + pool_timeout=POOL_TIMEOUT_SECONDS, + connect_args={ + "timeout": DB_CONNECT_TIMEOUT_SECONDS, + "ssl": ssl.create_default_context( + cafile="/run/ca/ca.crt", + ), + }, + pool_pre_ping=True, +) + +@event.listens_for(engine.sync_engine, "before_cursor_execute") +def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): + operation = statement.lstrip().split(None, 1) + operation = operation[0].upper() if operation else "OTHER" + + if operation not in { + "SELECT", "INSERT", "UPDATE", "DELETE", + "WITH", "CREATE", "ALTER", "DROP", + }: + operation = "OTHER" + + tracer = trace.get_tracer("messenger.database") + + manager = tracer.start_as_current_span( + f"postgresql.{operation}", + kind=SpanKind.CLIENT, + attributes={ + "db.system.name": "postgresql", + "db.operation.name": operation, + "server.address": "postgres", + }, + record_exception=False, + set_status_on_exception=False, + ) + + span = manager.__enter__() + context._messenger_db_span = (manager, span) + + +def finish_database_span(context, failed=False): + if context is None: + return + + state = getattr(context, "_messenger_db_span", None) + + if state is None: + return + + context._messenger_db_span = None + manager, span = state + + span.set_status( + Status(StatusCode.ERROR if failed else StatusCode.OK) + ) + + manager.__exit__(None, None, None) + + +@event.listens_for(engine.sync_engine, "after_cursor_execute") +def after_cursor_execute(conn, cursor, statement, parameters, context, executemany): + finish_database_span(context) + + +@event.listens_for(engine.sync_engine, "handle_error") +def handle_database_error(exception_context): + finish_database_span( + exception_context.execution_context, + failed=True, + ) + +SessionFactory = async_sessionmaker( + bind=engine, + expire_on_commit=False, +) + + +async def get_db_session() -> AsyncIterator[AsyncSession]: + async with SessionFactory() as session: + yield session + + +async def ping_database() -> bool: + try: + async with engine.connect() as connection: + await connection.execute(text("SELECT 1")) + return True + except (SQLAlchemyError, OSError): + return False \ No newline at end of file diff --git a/src/dispatcher.py b/src/dispatcher.py new file mode 100644 index 00000000..a474ea55 --- /dev/null +++ b/src/dispatcher.py @@ -0,0 +1,175 @@ +import asyncio +import logging + +from sqlalchemy import text + +from src.database import SessionFactory, engine +from src.queue import connect, publish, publish_failed +from src.telemetry import setup +from src.runtime_metrics import update_queue + +logging.basicConfig(level=logging.INFO) + + +async def collect_queue_metrics(): + async with SessionFactory() as session: + result = await session.execute( + text(""" + SELECT + count(*) AS depth, + COALESCE( + EXTRACT(EPOCH FROM ( + now() - min(created_at) + )), + 0 + ) AS oldest + FROM attachment_jobs + WHERE status = 'queued' + """) + ) + + row = result.one() + update_queue(row.depth, row.oldest) + + +async def dispatch(channel): + async with SessionFactory() as session: + async with session.begin(): + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'queued', + published_at = NULL, + started_at = NULL, + execution_id = NULL + WHERE status = 'processing' + AND started_at < now() - interval '90 seconds' + """) + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'queued', + updated_at = now() + WHERE status = 'processing' + AND id IN ( + SELECT attachment_id + FROM attachment_jobs + WHERE status = 'queued' + ) + """) + ) + + result = await session.execute( + text(""" + SELECT id, attachment_id, attempt, generation, created_at, + traceparent, tracestate + FROM attachment_jobs + WHERE published_at IS NULL + AND status = 'queued' + AND ( + next_attempt_at IS NULL + OR next_attempt_at <= now() + ) + ORDER BY created_at LIMIT 25 + FOR + UPDATE SKIP LOCKED + """) + ) + + rows = result.all() + + for row in rows: + publish(channel, row) + + await session.execute( + text(""" + UPDATE attachment_jobs + SET published_at = now() + WHERE id = :id + """), + {"id": row.id}, + ) + + return len(rows) + + +async def dispatch_failed(channel): + async with SessionFactory() as session: + async with session.begin(): + result = await session.execute( + text(""" + SELECT id, attachment_id, attempt, generation, + last_error_code, created_at, finished_at + FROM attachment_jobs + WHERE status = 'failed' + AND failed_published_at IS NULL + ORDER BY created_at + LIMIT 25 + FOR UPDATE SKIP LOCKED + """) + ) + + rows = result.all() + + for row in rows: + payload = { + "schema_version": 1, + "type": "attachment.failed.v1", + "job_id": str(row.id), + "attachment_id": str(row.attachment_id), + "attempt": row.attempt, + "generation": row.generation, + "error_code": row.last_error_code, + "created_at": row.created_at.isoformat(), + "finished_at": ( + row.finished_at.isoformat() + if row.finished_at + else None + ), + } + + publish_failed(channel, payload) + + await session.execute( + text(""" + UPDATE attachment_jobs + SET failed_published_at = now() + WHERE id = :id + """), + {"id": row.id}, + ) + + return len(rows) + + +async def main(): + setup("messenger-dispatcher") + while True: + connection = None + + try: + connection, channel = connect() + channel.confirm_delivery() + + while True: + count = await dispatch(channel) + failed_count = await dispatch_failed(channel) + await collect_queue_metrics() + await asyncio.sleep(0.2 if count or failed_count else 1) + + except Exception: + logging.exception("Dispatcher reconnect") + await asyncio.sleep(3) + + finally: + if connection and connection.is_open: + connection.close() + + +if __name__ == "__main__": + try: + asyncio.run(main()) + finally: + asyncio.run(engine.dispose()) \ No newline at end of file diff --git a/src/errors.py b/src/errors.py new file mode 100644 index 00000000..8b853205 --- /dev/null +++ b/src/errors.py @@ -0,0 +1,12 @@ +class APIError(Exception): + def __init__( + self, + status_code: int, + code: str, + message: str, + headers: dict[str, str] | None = None, + ): + self.status_code = status_code + self.code = code + self.message = message + self.headers = headers \ No newline at end of file diff --git a/src/images.py b/src/images.py new file mode 100644 index 00000000..2acf0f6f --- /dev/null +++ b/src/images.py @@ -0,0 +1,71 @@ +import hashlib +import io +import os + +from PIL import Image, UnidentifiedImageError + +from src.errors import APIError + + +MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760")) +MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000")) + +ALLOWED_FORMATS = { + "PNG": "image/png", + "JPEG": "image/jpeg", +} + + +def validate_image(body: bytes, content_type: str) -> tuple[int, str]: + if content_type not in ALLOWED_FORMATS.values(): + raise APIError( + status_code=415, + code="unsupported_media_type", + message="Only PNG and JPEG images are supported", + ) + + size_bytes = len(body) + + if size_bytes > MAX_UPLOAD_BYTES: + raise APIError( + status_code=413, + code="payload_too_large", + message="Image exceeds maximum upload size", + ) + + if size_bytes == 0: + raise APIError( + status_code=400, + code="invalid_request", + message="Image must not be empty", + ) + + try: + with Image.open(io.BytesIO(body)) as image: + if image.format not in ALLOWED_FORMATS: + raise ValueError("Unsupported image format") + + if ALLOWED_FORMATS[image.format] != content_type: + raise ValueError("Content-Type does not match image format") + + width, height = image.size + + if width * height > MAX_IMAGE_PIXELS: + raise APIError( + status_code=413, + code="payload_too_large", + message="Image exceeds maximum pixel count", + ) + + image.load() + + except APIError: + raise + except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc: + raise APIError( + status_code=400, + code="invalid_request", + message="Invalid image data", + ) from exc + + return size_bytes, hashlib.sha256(body).hexdigest() diff --git a/src/main.py b/src/main.py new file mode 100644 index 00000000..1e5083b6 --- /dev/null +++ b/src/main.py @@ -0,0 +1,861 @@ +from datetime import datetime, timedelta, timezone +from uuid import UUID, uuid4 +import os +import re +import base64 +import binascii +import asyncio + +from fastapi import Depends, FastAPI, Request, Header, Query +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from fastapi.security import ( + HTTPAuthorizationCredentials, + HTTPBearer, +) +from botocore.exceptions import BotoCoreError, ClientError +from sqlalchemy import text +from sqlalchemy.exc import IntegrityError, SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncSession +from starlette.exceptions import HTTPException as StarletteHTTPException +from contextlib import asynccontextmanager + +from src.database import engine, get_db_session, ping_database, SessionFactory +from src.errors import APIError +from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage, Attachment +from src.repositories import ( + create_chat, + list_chats, + create_user as create_user_in_db, + get_user_by_id, + get_chat_by_id, + get_user_credentials_by_username, + create_message, + get_messages, + create_attachment, + get_attachment, + attachment_key_exists, +) +from src.security import verify_password +from src.rate_limit import ( + enforce_login_ip, + enforce_login_username, +) +from src.sessions import ( + create_session, + delete_session, + get_session_user_id, + ping_session_store, + redis_client, +) +from src.images import MAX_UPLOAD_BYTES, validate_image +from src.storage import delete_object, put_object, get_object + + +@asynccontextmanager +async def lifespan(app: FastAPI): + yield + await redis_client.aclose() + await engine.dispose() + + + +from src.telemetry import ( + setup, + HTTPMetricsMiddleware, + capture_trace_context, + TELEMETRY_ENABLED, +) +from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor + +setup("messenger-api") + +app = FastAPI(lifespan=lifespan) +if TELEMETRY_ENABLED: + app.add_middleware(HTTPMetricsMiddleware) + +INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4()) + +bearer_security = HTTPBearer(auto_error=False) + + +async def get_current_user( + credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security), + session: AsyncSession = Depends(get_db_session), +) -> User: + if credentials is None or credentials.scheme.lower() != "bearer": + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + 'WWW-Authenticate': 'Bearer realm="messenger"', + }, + ) + + user_id = await get_session_user_id(credentials.credentials) + + if user_id is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + 'WWW-Authenticate': 'Bearer realm="messenger"', + }, + ) + + user = await get_user_by_id(session, user_id) + + if user is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + 'WWW-Authenticate': 'Bearer realm="messenger"', + }, + ) + + return user + + +@app.middleware("http") +async def request_middleware(request: Request, call_next): + request_id = str(uuid4()) + request.state.request_id = request_id + + if request.method in {"POST", "PUT", "PATCH"}: + content_type = request.headers.get("content-type") + + if content_type is not None: + media_type = content_type.split(";", 1)[0].strip().lower() + + is_attachment_upload = ( + request.method == "POST" + and re.fullmatch( + r"/api/v1/chats/[^/]+/attachments", + request.url.path, + ) is not None + ) + + allowed_media_types = ( + {"image/png", "image/jpeg"} + if is_attachment_upload + else {"application/json"} + ) + + if media_type not in allowed_media_types: + return JSONResponse( + status_code=415, + content={ + "error": { + "code": "unsupported_media_type", + "message": "Unsupported media type", + "request_id": request_id, + } + }, + headers={ + "X-Request-Id": request_id, + "X-Instance-Id": INSTANCE_ID, + }, + ) + + response = await call_next(request) + + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + + return response + + +@app.exception_handler(RequestValidationError) +async def validation_exception_handler( + request: Request, + exc: RequestValidationError, +): + request_id = request.state.request_id + + return JSONResponse( + status_code=400, + content={ + "error": { + "code": "invalid_request", + "message": "Invalid request", + "request_id": request_id, + } + }, + ) + + +@app.exception_handler(APIError) +async def api_error_handler(request: Request, exc: APIError): + request_id = request.state.request_id + + return JSONResponse( + status_code=exc.status_code, + content={ + "error": { + "code": exc.code, + "message": exc.message, + "request_id": request_id, + } + }, + headers=exc.headers, + ) + + +@app.exception_handler(SQLAlchemyError) +async def database_exception_handler( + request: Request, + exc: SQLAlchemyError, +): + request_id = request.state.request_id + + return JSONResponse( + status_code=503, + content={ + "error": { + "code": "unavailable", + "message": "Database unavailable", + "request_id": request_id, + } + }, + ) + + +@app.exception_handler(OSError) +async def database_connection_exception_handler( + request: Request, + exc: OSError, +): + request_id = request.state.request_id + + return JSONResponse( + status_code=503, + content={ + "error": { + "code": "unavailable", + "message": "Database unavailable", + "request_id": request_id, + } + }, + ) + + +@app.exception_handler(StarletteHTTPException) +async def http_exception_handler( + request: Request, + exc: StarletteHTTPException, +): + request_id = request.state.request_id + + if exc.status_code == 404: + code = "not_found" + message = "Not found" + else: + code = "invalid_request" + message = "Invalid request" + + return JSONResponse( + status_code=exc.status_code, + content={ + "error": { + "code": code, + "message": message, + "request_id": request_id, + } + }, + headers=exc.headers, + ) + + +@app.exception_handler(Exception) +async def unexpected_exception_handler( + request: Request, + exc: Exception, +): + request_id = request.state.request_id + + return JSONResponse( + status_code=500, + content={ + "error": { + "code": "internal_error", + "message": "Internal server error", + "request_id": request_id, + } + }, + ) + + +@app.get("/health/live") +async def health_live(): + return {"status": "ok"} + + +@app.get("/health/ready") +async def health_ready(): + database_ready = await ping_database() + session_store_ready = await ping_session_store() + + if not database_ready or not session_store_ready: + raise APIError( + status_code=503, + code="unavailable", + message="Service dependencies unavailable", + ) + + return {"status": "ok"} + + +@app.post("/api/v1/users", response_model=User, status_code=201) +async def create_user( + data: CreateUser, + session: AsyncSession = Depends(get_db_session), +): + try: + async with session.begin(): + return await create_user_in_db(session, data) + + except IntegrityError as exc: + raise APIError( + status_code=409, + code="conflict", + message="Username already exists", + ) from exc + + +@app.get("/api/v1/users/me", response_model=User) +async def get_me( + current_user: User = Depends(get_current_user), +): + return current_user + + +@app.post( + "/api/v1/auth/sessions", + response_model=SessionResponse, + status_code=201, +) +async def create_auth_session( + request: Request, + authorization: str | None = Header(default=None), + session: AsyncSession = Depends(get_db_session), +): + client_ip = ( + request.client.host + if request.client is not None + else "unknown" + ) + + await enforce_login_ip(client_ip) + + credentials = None + if authorization is not None: + scheme, separator, encoded = authorization.partition(" ") + if separator and scheme.lower() == "basic": + try: + decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8") + if ":" in decoded: + credentials = decoded.split(":", 1) + except (ValueError, UnicodeError, binascii.Error): + pass + if credentials is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"', + }, + ) + + await enforce_login_username(credentials[0]) + + user_credentials = await get_user_credentials_by_username( + session, + credentials[0], + ) + + if user_credentials is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"', + }, + ) + + if not await asyncio.to_thread( + verify_password, + user_credentials.password_hash, + credentials[1], + ): + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"', + }, + ) + + user = User( + id=user_credentials.id, + username=user_credentials.username, + display_name=user_credentials.display_name, + created_at=user_credentials.created_at, + ) + + token, ttl = await create_session(user.id) + + expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl) + + return SessionResponse( + token=token, + token_type="Bearer", + expires_at=expires_at, + user=user, + ) + + +@app.delete( + "/api/v1/auth/sessions/current", + status_code=204, +) +async def delete_current_session( + credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security), + current_user: User = Depends(get_current_user), +): + await delete_session(credentials.credentials) + + +@app.post( + "/api/v1/chats", + response_model=Chat, + status_code=201, +) +async def create_chat_endpoint( + data: CreateChat, + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> Chat: + try: + chat = await create_chat( + session=session, + data=data, + current_user_id=current_user.id, + ) + await session.commit() + except Exception: + await session.rollback() + raise + + return chat + + +@app.get( + "/api/v1/chats", + response_model=ChatPage, +) +async def get_chats( + limit: int = 50, + cursor: str | None = None, + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> ChatPage: + if limit < 1 or limit > 100: + raise APIError( + status_code=400, + code="invalid_request", + message="Limit must be between 1 and 100", + ) + + return await list_chats( + session=session, + current_user_id=current_user.id, + limit=limit, + cursor=cursor, + ) + + +@app.get( + "/api/v1/chats/{chat_id}", + response_model=Chat, +) +async def get_chat_endpoint( + chat_id: UUID, + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> Chat: + chat = await get_chat_by_id( + session=session, + chat_id=chat_id, + current_user_id=current_user.id, + ) + + if chat is None: + raise APIError( + status_code=404, + code="not_found", + message="Chat not found", + ) + + return chat + + +@app.post( + "/api/v1/chats/{chat_id}/messages", + response_model=Message, + status_code=201, +) +async def create_message_endpoint( + chat_id: UUID, + data: CreateMessage, + idempotency_key: str | None = Header( + default=None, + alias="Idempotency-Key", + ), + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> Message: + + if ( + idempotency_key is None + or re.fullmatch( + r"[A-Za-z0-9._:-]{1,128}", + idempotency_key, + ) is None + ): + raise APIError( + status_code=400, + code="invalid_request", + message="Invalid or missing Idempotency-Key", + ) + + try: + message = await create_message( + session=session, + chat_id=chat_id, + current_user_id=current_user.id, + data=data, + idempotency_key=idempotency_key, + ) + + await session.commit() + + except Exception: + await session.rollback() + raise + + return message + + +@app.get( + "/api/v1/chats/{chat_id}/messages", + response_model=MessagePage, +) +async def get_messages_endpoint( + chat_id: UUID, + limit: int = 50, + cursor: str | None = None, + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> MessagePage: + if limit < 1 or limit > 100: + raise APIError( + status_code=400, + code="invalid_request", + message="Limit must be between 1 and 100", + ) + + return await get_messages( + session=session, + chat_id=chat_id, + current_user_id=current_user.id, + limit=limit, + cursor=cursor, + ) + + +@app.post( + "/api/v1/chats/{chat_id}/attachments", + response_model=Attachment, + status_code=202, +) +async def upload_attachment_endpoint( + chat_id: UUID, + request: Request, + filename: str = Query(min_length=1, max_length=255), + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> Attachment: + chat = await get_chat_by_id( + session=session, + chat_id=chat_id, + current_user_id=current_user.id, + ) + + if chat is None: + raise APIError( + status_code=404, + code="not_found", + message="Chat not found", + ) + + content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + + if content_type not in {"image/png", "image/jpeg"}: + raise APIError( + status_code=415, + code="unsupported_media_type", + message="Only PNG and JPEG images are supported", + ) + + body = bytearray() + + async for chunk in request.stream(): + if len(body) + len(chunk) > MAX_UPLOAD_BYTES: + raise APIError( + status_code=413, + code="payload_too_large", + message="Image exceeds maximum upload size", + ) + + body.extend(chunk) + + image_bytes = bytes(body) + size_bytes, sha256 = validate_image(image_bytes, content_type) + + attachment_id = uuid4() + extension = "png" if content_type == "image/png" else "jpg" + s3_key = f"staging/{chat_id}/{attachment_id}.{extension}" + + try: + await put_object( + key=s3_key, + body=image_bytes, + content_type=content_type, + ) + except (BotoCoreError, ClientError, OSError, TimeoutError) as exc: + raise APIError( + status_code=503, + code="unavailable", + message="Object storage unavailable", + ) from exc + + try: + attachment = await create_attachment( + session=session, + attachment_id=attachment_id, + chat_id=chat_id, + owner_id=current_user.id, + filename=filename, + content_type=content_type, + size_bytes=size_bytes, + sha256=sha256, + s3_key=s3_key, + ) + + trace_context = capture_trace_context() + + await session.execute( + text(""" + INSERT INTO attachment_jobs ( + id, attachment_id, traceparent, tracestate + ) + VALUES ( + :job_id, :attachment_id, :traceparent, :tracestate + ) + """), + { + "job_id": uuid4(), + "attachment_id": attachment_id, + "traceparent": trace_context.get("traceparent"), + "tracestate": trace_context.get("tracestate"), + }, + ) + + await session.commit() + + except BaseException: + try: + await session.rollback() + except Exception: + pass + + try: + async with SessionFactory() as verification_session: + exists = await attachment_key_exists( + verification_session, + s3_key, + ) + except Exception: + exists = True + + if not exists: + try: + await asyncio.shield(delete_object(s3_key)) + except Exception: + pass + + raise + + return attachment + + + +@app.get( + "/api/v1/attachments/{attachment_id}", + response_model=Attachment, +) +async def get_attachment_endpoint( + attachment_id: UUID, + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), +) -> Attachment: + result = await get_attachment( + session=session, + attachment_id=attachment_id, + current_user_id=current_user.id, + ) + + if result is None: + raise APIError( + status_code=404, + code="not_found", + message="Attachment not found", + ) + + attachment, s3_key = result + return attachment + + +@app.get("/api/v1/attachments/{attachment_id}/content") +async def get_attachment_content_endpoint( + attachment_id: UUID, + current_user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_db_session), + variant: str = Query(default="original"), +): + result = await get_attachment( + session=session, + attachment_id=attachment_id, + current_user_id=current_user.id, + ) + + if result is None: + raise APIError( + status_code=404, + code="not_found", + message="Attachment not found", + ) + + attachment, s3_key = result + + if attachment.status != "ready": + raise APIError( + status_code=409, + code="conflict", + message="Attachment is not ready", + ) + + if variant == "original": + media_type = attachment.content_type + + elif variant in {"thumbnail", "crop", "optimized"}: + selected = next( + (item for item in attachment.variants if item.name == variant), + None, + ) + + if selected is None: + raise APIError( + status_code=404, + code="not_found", + message="Variant not found", + ) + + extension = { + "thumbnail": "jpg", + "crop": "jpg", + "optimized": "webp", + }[variant] + + s3_key = selected.s3_key or ( + f"variants/{attachment.chat_id}/{attachment_id}/" + f"{variant}.{extension}" + ) + media_type = selected.content_type + + else: + raise APIError( + status_code=404, + code="not_found", + message="Variant not found", + ) + + try: + body = await get_object(s3_key) + except (BotoCoreError, ClientError, OSError, TimeoutError) as exc: + raise APIError( + status_code=503, + code="unavailable", + message="Object storage unavailable", + ) from exc + + return Response( + content=body, + media_type=media_type, + headers={ + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + }, + ) + +if TELEMETRY_ENABLED: + FastAPIInstrumentor.instrument_app( + app, + excluded_urls="health/live,health/ready", + exclude_spans=["receive", "send"], + ) + + +import asyncio as benchmark_asyncio +import os as benchmark_os +from fastapi.responses import JSONResponse as BenchmarkJSONResponse +from opentelemetry import trace as benchmark_trace + + +if benchmark_os.getenv("TELEMETRY_BENCHMARK_ENABLED", "0") == "1": + @app.get("/api/v1/_benchmark/{scenario}", include_in_schema=False) + async def telemetry_benchmark(scenario: str): + span = benchmark_trace.get_current_span() + context = span.get_span_context() + + if scenario not in {"normal", "error", "slow"}: + return BenchmarkJSONResponse( + {"error": "unknown_scenario"}, + status_code=400, + ) + + span.set_attribute("benchmark.scenario", scenario) + + if scenario == "slow": + await benchmark_asyncio.sleep(0.6) + + status = 503 if scenario == "error" else 200 + + if scenario == "error": + span.set_status(benchmark_trace.StatusCode.ERROR) + + return BenchmarkJSONResponse( + { + "scenario": scenario, + "trace_id": format(context.trace_id, "032x"), + "sampled": bool(context.trace_flags.sampled), + }, + status_code=status, + ) diff --git a/src/models.py b/src/models.py new file mode 100644 index 00000000..d52102bf --- /dev/null +++ b/src/models.py @@ -0,0 +1,153 @@ +from datetime import datetime +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + + username: str = Field( + min_length=3, + max_length=32, + pattern=r"^[a-z0-9_]+$", + ) + + display_name: str = Field( + min_length=1, + max_length=100, + ) + + password: str = Field( + min_length=12, + max_length=128, + ) + + @field_validator("display_name") + @classmethod + def validate_display_name(cls, value: str) -> str: + if not value.strip(): + raise ValueError("Display name must not be blank") + + return value + + +class User(BaseModel): + id: UUID + username: str + display_name: str + created_at: datetime + + +class SessionResponse(BaseModel): + token: str + token_type: str + expires_at: datetime + user: User + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + + title: str = Field( + min_length=1, + max_length=100, + ) + + member_ids: list[UUID] = Field( + min_length=1, + max_length=100, + ) + + @field_validator("title") + @classmethod + def validate_title(cls, value: str) -> str: + if not value.strip(): + raise ValueError("Chat title must not be blank") + + return value + + @field_validator("member_ids") + @classmethod + def validate_member_ids(cls, value: list[UUID]) -> list[UUID]: + if len(value) != len(set(value)): + raise ValueError("Member IDs must be unique") + + return value + + +class Chat(BaseModel): + id: UUID + title: str + member_ids: list[UUID] + created_at: datetime + + +class ChatPage(BaseModel): + items: list[Chat] + next_cursor: str | None + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + + text: str = Field(max_length=4000) + attachment_ids: list[UUID] = Field(default_factory=list, max_length=10) + + @field_validator("attachment_ids") + @classmethod + def validate_attachment_ids(cls, value: list[UUID]) -> list[UUID]: + if len(value) != len(set(value)): + raise ValueError("Attachment IDs must be unique") + + return value + + @model_validator(mode="after") + def validate_content(self): + if not self.text.strip() and not self.attachment_ids: + raise ValueError("Message must contain text or attachments") + + return self + + +class Message(BaseModel): + id: UUID + chat_id: UUID + sender_id: UUID + text: str + created_at: datetime + attachment_ids: list[UUID] = Field(default_factory=list) + + +class MessagePage(BaseModel): + items: list[Message] + next_cursor: str | None + + +class Variant(BaseModel): + model_config = ConfigDict(extra="forbid") + + name: str = Field(pattern=r"^(thumbnail|crop|optimized)$") + content_type: str = Field(pattern=r"^image/(jpeg|png|webp)$") + size_bytes: int = Field(ge=1) + width: int = Field(ge=1) + height: int = Field(ge=1) + sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + s3_key: str | None = Field(default=None, exclude=True) + + +class Attachment(BaseModel): + model_config = ConfigDict(extra="forbid") + + id: UUID + chat_id: UUID + owner_id: UUID + filename: str = Field(min_length=1, max_length=255) + content_type: str = Field(pattern=r"^image/(png|jpeg)$") + size_bytes: int = Field(ge=1, le=10485760) + sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + status: str = Field(pattern=r"^(queued|processing|ready|failed)$") + variants: list[Variant] + error_code: str | None + created_at: datetime + updated_at: datetime diff --git a/src/queue.py b/src/queue.py new file mode 100644 index 00000000..1e2e2fb8 --- /dev/null +++ b/src/queue.py @@ -0,0 +1,120 @@ +import json +import os +import ssl +from datetime import timezone +from pathlib import Path + +import pika +from opentelemetry import trace +from opentelemetry.trace import SpanKind, Status, StatusCode +from src.telemetry import capture_trace_context, restore_trace_context + +QUEUE = "attachment.process.v1" +DLQ = "attachment.failed.v1" + + +def connect(): + password = Path( + os.environ["RABBITMQ_PASSWORD_FILE"] + ).read_text().strip() + + credentials = pika.PlainCredentials( + os.environ["RABBITMQ_USERNAME"], + password, + ) + + host = os.getenv("RABBITMQ_HOST", "rabbitmq") + + tls_context = ssl.create_default_context( + cafile="/run/ca/ca.crt", + ) + + tls_context.minimum_version = ssl.TLSVersion.TLSv1_2 + + connection = pika.BlockingConnection( + pika.ConnectionParameters( + host=host, + port=5671, + virtual_host="messenger", + credentials=credentials, + ssl_options=pika.SSLOptions(tls_context, host), + heartbeat=60, + blocked_connection_timeout=30, + connection_attempts=3, + retry_delay=2, + ) + ) + + channel = connection.channel() + + return connection, channel + + +def publish(channel, row): + tracer = trace.get_tracer("messenger.dispatcher") + context = restore_trace_context({ + "traceparent": row.traceparent, + "tracestate": row.tracestate, + }) + + with tracer.start_as_current_span( + "attachment.publish", + context=context, + kind=SpanKind.PRODUCER, + record_exception=False, + set_status_on_exception=False, + attributes={ + "messaging.system": "rabbitmq", + "messaging.destination.name": QUEUE, + "job.attempt": row.attempt, + "job.generation": row.generation, + }, + ) as span: + try: + publish_message(channel, row) + span.set_status(Status(StatusCode.OK)) + except Exception: + span.set_status(Status(StatusCode.ERROR)) + raise + + +def publish_message(channel, row): + payload = { + "schema_version": 1, + "job_id": str(row.id), + "type": "attachment.process.v1", + "attachment_id": str(row.attachment_id), + "pipeline_version": 1, + "attempt": row.attempt, + "generation": row.generation, + "created_at": row.created_at.astimezone( + timezone.utc + ).isoformat().replace("+00:00", "Z"), + } + + channel.basic_publish( + exchange="", + routing_key=QUEUE, + body=json.dumps(payload).encode(), + properties=pika.BasicProperties( + delivery_mode=2, + content_type="application/json", + message_id=str(row.id), + headers=capture_trace_context(), + ), + mandatory=True, + ) + + +def publish_failed(channel, payload: dict): + channel.basic_publish( + exchange="", + routing_key=DLQ, + body=json.dumps(payload).encode(), + properties=pika.BasicProperties( + delivery_mode=2, + content_type="application/json", + message_id=payload["job_id"], + ), + mandatory=True, + ) \ No newline at end of file diff --git a/src/rate_limit.py b/src/rate_limit.py new file mode 100644 index 00000000..36ad93ab --- /dev/null +++ b/src/rate_limit.py @@ -0,0 +1,104 @@ +import hashlib +import math +import os + +from redis.exceptions import RedisError + +from src.errors import APIError +from src.sessions import redis_client + + +LOGIN_WINDOW_SECONDS = int( + os.getenv("LOGIN_WINDOW_SECONDS", "60") +) + +LOGIN_USERNAME_LIMIT = int( + os.getenv("LOGIN_USERNAME_LIMIT", "5") +) + +LOGIN_IP_LIMIT = int( + os.getenv("LOGIN_IP_LIMIT", "60") +) + +if min( + LOGIN_WINDOW_SECONDS, + LOGIN_USERNAME_LIMIT, + LOGIN_IP_LIMIT, +) <= 0: + raise ValueError("Login rate limits must be positive") + + +INCREMENT_SCRIPT = """ +local count = redis.call('INCR', KEYS[1]) + +if count == 1 then + redis.call('EXPIRE', KEYS[1], ARGV[1]) +end + +local ttl = redis.call('TTL', KEYS[1]) + +if ttl < 0 then + redis.call('EXPIRE', KEYS[1], ARGV[1]) + ttl = tonumber(ARGV[1]) +end + +return {count, ttl} +""" + + +def make_key(scope: str, value: str) -> str: + digest = hashlib.sha256( + value.encode("utf-8") + ).hexdigest() + + return f"rate:login:{scope}:{digest}" + + +async def enforce_limit( + scope: str, + value: str, + limit: int, +) -> None: + key = make_key(scope, value) + + try: + count, ttl = await redis_client.eval( + INCREMENT_SCRIPT, + 1, + key, + LOGIN_WINDOW_SECONDS, + ) + except RedisError as exc: + raise APIError( + status_code=503, + code="unavailable", + message="Login rate limiter unavailable", + ) from exc + + if int(count) > limit: + retry_after = max(1, math.ceil(ttl)) + + raise APIError( + status_code=429, + code="rate_limited", + message="Too many login attempts", + headers={ + "Retry-After": str(retry_after), + }, + ) + + +async def enforce_login_ip(ip: str) -> None: + await enforce_limit( + "ip", + ip, + LOGIN_IP_LIMIT, + ) + + +async def enforce_login_username(username: str) -> None: + await enforce_limit( + "username", + username, + LOGIN_USERNAME_LIMIT, + ) diff --git a/src/repositories.py b/src/repositories.py new file mode 100644 index 00000000..2b9551f0 --- /dev/null +++ b/src/repositories.py @@ -0,0 +1,876 @@ +import asyncio +from uuid import UUID, uuid4 +import hashlib +import json + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from src.models import Attachment, Chat, ChatPage, CreateChat, CreateUser, User, CreateMessage, Message, MessagePage +from src.security import hash_password +from src.errors import APIError +from src.cursor import decode_cursor, encode_cursor, decode_chat_cursor, encode_chat_cursor + + +async def create_user( + session: AsyncSession, + data: CreateUser, +) -> User: + user_id = uuid4() + password_hash = await asyncio.to_thread(hash_password, data.password) + + result = await session.execute( + text( + """ + INSERT INTO users ( + id, + username, + display_name, + password_hash + ) + VALUES ( + :id, + :username, + :display_name, + :password_hash + ) + RETURNING + id, + username, + display_name, + created_at + """ + ), + { + "id": user_id, + "username": data.username, + "display_name": data.display_name, + "password_hash": password_hash, + }, + ) + + row = result.one() + + return User( + id=UUID(str(row.id)), + username=row.username, + display_name=row.display_name, + created_at=row.created_at, + ) + +async def get_user_credentials_by_username( + session: AsyncSession, + username: str, +): + result = await session.execute( + text( + """ + SELECT + id, + username, + display_name, + password_hash, + created_at + FROM users + WHERE username = :username + """ + ), + { + "username": username, + }, + ) + + return result.one_or_none() + + +async def get_user_by_id( + session: AsyncSession, + user_id: UUID, +) -> User | None: + result = await session.execute( + text( + """ + SELECT + id, + username, + display_name, + created_at + FROM users + WHERE id = :user_id + """ + ), + { + "user_id": user_id, + }, + ) + + row = result.one_or_none() + + if row is None: + return None + + return User( + id=UUID(str(row.id)), + username=row.username, + display_name=row.display_name, + created_at=row.created_at, + ) + + +async def create_chat( + session: AsyncSession, + data: CreateChat, + current_user_id: UUID, +) -> Chat: + if current_user_id not in data.member_ids: + raise APIError( + status_code=400, + code="invalid_request", + message="Current user must be a chat member", + ) + + users_result = await session.execute( + text( + """ + SELECT id + FROM users + WHERE id = ANY(:member_ids) + """ + ), + { + "member_ids": data.member_ids, + }, + ) + + existing_user_ids = { + UUID(str(row.id)) + for row in users_result + } + + if existing_user_ids != set(data.member_ids): + raise APIError( + status_code=400, + code="invalid_request", + message="Unknown chat member", + ) + + chat_id = uuid4() + + chat_result = await session.execute( + text( + """ + INSERT INTO chats ( + id, + title + ) + VALUES ( + :id, + :title + ) + RETURNING + id, + title, + created_at + """ + ), + { + "id": chat_id, + "title": data.title, + }, + ) + + chat_row = chat_result.one() + + for member_id in data.member_ids: + await session.execute( + text( + """ + INSERT INTO chat_members ( + chat_id, + user_id + ) + VALUES ( + :chat_id, + :user_id + ) + """ + ), + { + "chat_id": chat_id, + "user_id": member_id, + }, + ) + + return Chat( + id=UUID(str(chat_row.id)), + title=chat_row.title, + member_ids=data.member_ids, + created_at=chat_row.created_at, + ) + + +async def get_chat_by_id( + session: AsyncSession, + chat_id: UUID, + current_user_id: UUID, +) -> Chat | None: + chat_result = await session.execute( + text( + """ + SELECT + c.id, + c.title, + c.created_at + FROM chats AS c + JOIN chat_members AS cm + ON cm.chat_id = c.id + WHERE c.id = :chat_id + AND cm.user_id = :current_user_id + """ + ), + { + "chat_id": chat_id, + "current_user_id": current_user_id, + }, + ) + + chat_row = chat_result.one_or_none() + + if chat_row is None: + return None + + members_result = await session.execute( + text( + """ + SELECT user_id + FROM chat_members + WHERE chat_id = :chat_id + ORDER BY user_id + """ + ), + { + "chat_id": chat_id, + }, + ) + + member_ids = [ + UUID(str(row.user_id)) + for row in members_result + ] + + return Chat( + id=UUID(str(chat_row.id)), + title=chat_row.title, + member_ids=member_ids, + created_at=chat_row.created_at, + ) + + +async def list_chats( + session: AsyncSession, + current_user_id: UUID, + limit: int, + cursor: str | None = None, +) -> ChatPage: + cursor_created_at = None + cursor_chat_id = None + if cursor is not None: + try: + cursor_user_id, cursor_created_at, cursor_chat_id = decode_chat_cursor(cursor) + except ValueError as exc: + raise APIError(status_code=400, code="invalid_request", message="Invalid cursor") from exc + if cursor_user_id != current_user_id: + raise APIError(status_code=400, code="invalid_request", message="Invalid cursor") + + result = await session.execute( + text( + """ + SELECT c.id, c.title, c.created_at + FROM chats AS c + JOIN chat_members AS cm ON cm.chat_id = c.id + WHERE cm.user_id = :current_user_id + AND ( + CAST(:cursor_created_at AS timestamptz) IS NULL + OR (c.created_at, c.id) > ( + CAST(:cursor_created_at AS timestamptz), + CAST(:cursor_chat_id AS uuid) + ) + ) + ORDER BY c.created_at, c.id + LIMIT :fetch_limit + """ + ), + { + "current_user_id": current_user_id, + "cursor_created_at": cursor_created_at, + "cursor_chat_id": cursor_chat_id, + "fetch_limit": limit + 1, + }, + ) + rows = result.all() + has_more = len(rows) > limit + page_rows = rows[:limit] + items = [] + for chat_row in page_rows: + members_result = await session.execute( + text( + """ + SELECT user_id + FROM chat_members + WHERE chat_id = :chat_id + ORDER BY user_id + """ + ), + {"chat_id": chat_row.id}, + ) + items.append( + Chat( + id=UUID(str(chat_row.id)), + title=chat_row.title, + member_ids=[UUID(str(row.user_id)) for row in members_result], + created_at=chat_row.created_at, + ) + ) + next_cursor = None + if has_more: + last = page_rows[-1] + next_cursor = encode_chat_cursor( + current_user_id, last.created_at, UUID(str(last.id)) + ) + return ChatPage(items=items, next_cursor=next_cursor) + + +async def create_message( + session: AsyncSession, + chat_id: UUID, + current_user_id: UUID, + data: CreateMessage, + idempotency_key: str, +) -> Message: + membership_result = await session.execute( + text(""" + SELECT 1 + FROM chat_members + WHERE chat_id = :chat_id + AND user_id = :user_id + """), + { + "chat_id": chat_id, + "user_id": current_user_id, + }, + ) + + if membership_result.scalar_one_or_none() is None: + raise APIError( + status_code=404, + code="not_found", + message="Chat not found", + ) + + canonical_body = json.dumps( + { + "text": data.text, + "attachment_ids": [str(attachment_id) for attachment_id in data.attachment_ids], + }, + sort_keys=True, + ensure_ascii=False, + separators=(",", ":"), + ) + + request_hash = hashlib.sha256( + canonical_body.encode("utf-8") + ).hexdigest() + + scope = ( + f"{current_user_id}:POST:" + f"/api/v1/chats/{chat_id}/messages:" + f"{idempotency_key}" + ) + + await session.execute( + text(""" + SELECT pg_advisory_xact_lock( + hashtextextended(:scope, 0) + ) + """), + {"scope": scope}, + ) + + await session.execute( + text(""" + DELETE FROM message_idempotency + WHERE user_id = :user_id + AND chat_id = :chat_id + AND key = :key + AND created_at <= + clock_timestamp() - INTERVAL '24 hours' + """), + { + "user_id": current_user_id, + "chat_id": chat_id, + "key": idempotency_key, + }, + ) + + existing_result = await session.execute( + text(""" + SELECT + i.request_hash, + m.id, + m.chat_id, + m.sender_id, + m.text, + m.created_at + FROM message_idempotency AS i + JOIN messages AS m + ON m.id = i.message_id + WHERE i.user_id = :user_id + AND i.chat_id = :chat_id + AND i.key = :key + """), + { + "user_id": current_user_id, + "chat_id": chat_id, + "key": idempotency_key, + }, + ) + + existing = existing_result.one_or_none() + + if existing is not None: + if existing.request_hash != request_hash: + raise APIError( + status_code=409, + code="conflict", + message=( + "Idempotency key already used " + "with different request body" + ), + ) + + attachment_result = await session.execute( + text(""" + SELECT attachment_id + FROM message_attachments + WHERE message_id = :message_id + ORDER BY attachment_id + """), + {"message_id": existing.id}, + ) + + attachment_ids = [ + UUID(str(row.attachment_id)) + for row in attachment_result.all() + ] + + return Message( + id=UUID(str(existing.id)), + chat_id=UUID(str(existing.chat_id)), + sender_id=UUID(str(existing.sender_id)), + text=existing.text, + created_at=existing.created_at, + attachment_ids=attachment_ids, + ) + + if data.attachment_ids: + attachments_result = await session.execute( + text(""" + SELECT id + FROM attachments + WHERE id = ANY (:attachment_ids) + AND chat_id = :chat_id + AND status != 'failed' + """), + { + "attachment_ids": data.attachment_ids, + "chat_id": chat_id, + }, + ) + + valid_attachment_ids = { + UUID(str(row.id)) + for row in attachments_result.all() + } + + if valid_attachment_ids != set(data.attachment_ids): + raise APIError( + status_code=400, + code="invalid_request", + message="Invalid attachments for this chat", + ) + + message_id = uuid4() + + message_result = await session.execute( + text(""" + INSERT INTO messages ( + id, + chat_id, + sender_id, + text + ) + VALUES ( + :id, + :chat_id, + :sender_id, + :text + ) + RETURNING + id, + chat_id, + sender_id, + text, + created_at + """), + { + "id": message_id, + "chat_id": chat_id, + "sender_id": current_user_id, + "text": data.text, + }, + ) + + row = message_result.one() + + for attachment_id in data.attachment_ids: + await session.execute( + text(""" + INSERT INTO message_attachments (message_id, + attachment_id) + VALUES (:message_id, + :attachment_id) + """), + { + "message_id": message_id, + "attachment_id": attachment_id, + }, + ) + + await session.execute( + text(""" + INSERT INTO message_idempotency ( + user_id, + chat_id, + key, + request_hash, + message_id + ) + VALUES ( + :user_id, + :chat_id, + :key, + :request_hash, + :message_id + ) + """), + { + "user_id": current_user_id, + "chat_id": chat_id, + "key": idempotency_key, + "request_hash": request_hash, + "message_id": message_id, + }, + ) + + return Message( + id=UUID(str(row.id)), + chat_id=UUID(str(row.chat_id)), + sender_id=UUID(str(row.sender_id)), + text=row.text, + created_at=row.created_at, + attachment_ids=data.attachment_ids, + ) + + +async def get_messages( + session: AsyncSession, + chat_id: UUID, + current_user_id: UUID, + limit: int, + cursor: str | None, +) -> MessagePage: + membership_result = await session.execute( + text( + """ + SELECT 1 + FROM chat_members + WHERE chat_id = :chat_id + AND user_id = :current_user_id + """ + ), + { + "chat_id": chat_id, + "current_user_id": current_user_id, + }, + ) + + if membership_result.scalar_one_or_none() is None: + raise APIError( + status_code=404, + code="not_found", + message="Chat not found", + ) + + cursor_created_at = None + cursor_message_id = None + + if cursor is not None: + try: + ( + cursor_chat_id, + cursor_created_at, + cursor_message_id, + ) = decode_cursor(cursor) + except ValueError: + raise APIError( + status_code=400, + code="invalid_request", + message="Invalid cursor", + ) + + if cursor_chat_id != chat_id: + raise APIError( + status_code=400, + code="invalid_request", + message="Cursor belongs to another chat", + ) + + if cursor is None: + messages_result = await session.execute( + text( + """ + SELECT + id, + chat_id, + sender_id, + text, + created_at + FROM messages + WHERE chat_id = :chat_id + ORDER BY created_at, id + LIMIT :fetch_limit + """ + ), + { + "chat_id": chat_id, + "fetch_limit": limit + 1, + }, + ) + else: + messages_result = await session.execute( + text( + """ + SELECT + id, + chat_id, + sender_id, + text, + created_at + FROM messages + WHERE chat_id = :chat_id + AND (created_at, id) > ( + :cursor_created_at, + :cursor_message_id + ) + ORDER BY created_at, id + LIMIT :fetch_limit + """ + ), + { + "chat_id": chat_id, + "cursor_created_at": cursor_created_at, + "cursor_message_id": cursor_message_id, + "fetch_limit": limit + 1, + }, + ) + + rows = messages_result.all() + + has_more = len(rows) > limit + rows = rows[:limit] + + attachments_by_message = {} + + if rows: + attachment_result = await session.execute( + text(""" + SELECT message_id, attachment_id + FROM message_attachments + WHERE message_id = ANY(:message_ids) + ORDER BY message_id, attachment_id + """), + { + "message_ids": [row.id for row in rows], + }, + ) + + for attachment_row in attachment_result.all(): + message_id = UUID(str(attachment_row.message_id)) + attachment_id = UUID(str(attachment_row.attachment_id)) + + attachments_by_message.setdefault( + message_id, [] + ).append(attachment_id) + + items = [ + Message( + id=UUID(str(row.id)), + chat_id=UUID(str(row.chat_id)), + sender_id=UUID(str(row.sender_id)), + text=row.text, + created_at=row.created_at, + attachment_ids=attachments_by_message.get( + UUID(str(row.id)), [] + ), + ) + for row in rows + ] + + next_cursor = None + + if has_more: + last_message = items[-1] + + next_cursor = encode_cursor( + chat_id=chat_id, + created_at=last_message.created_at, + message_id=last_message.id, + ) + + return MessagePage( + items=items, + next_cursor=next_cursor, + ) + + +def attachment_from_row(row) -> Attachment: + return Attachment( + id=UUID(str(row.id)), + chat_id=UUID(str(row.chat_id)), + owner_id=UUID(str(row.owner_id)), + filename=row.filename, + content_type=row.content_type, + size_bytes=row.size_bytes, + sha256=row.sha256, + status=row.status, + variants=row.variants, + error_code=row.error_code, + created_at=row.created_at, + updated_at=row.updated_at, + ) + + +async def create_attachment( + session: AsyncSession, + attachment_id: UUID, + chat_id: UUID, + owner_id: UUID, + filename: str, + content_type: str, + size_bytes: int, + sha256: str, + s3_key: str, +) -> Attachment: + result = await session.execute( + text( + """ + INSERT INTO attachments ( + id, + chat_id, + owner_id, + filename, + content_type, + size_bytes, + sha256, + s3_key, + status + ) + VALUES ( + :id, + :chat_id, + :owner_id, + :filename, + :content_type, + :size_bytes, + :sha256, + :s3_key, + 'queued' + ) + RETURNING + id, + chat_id, + owner_id, + filename, + content_type, + size_bytes, + sha256, + status, + variants, + error_code, + created_at, + updated_at + """ + ), + { + "id": attachment_id, + "chat_id": chat_id, + "owner_id": owner_id, + "filename": filename, + "content_type": content_type, + "size_bytes": size_bytes, + "sha256": sha256, + "s3_key": s3_key, + }, + ) + + return attachment_from_row(result.one()) + + +async def get_attachment( + session: AsyncSession, + attachment_id: UUID, + current_user_id: UUID, +): + result = await session.execute( + text( + """ + SELECT + a.id, + a.chat_id, + a.owner_id, + a.filename, + a.content_type, + a.size_bytes, + a.sha256, + a.s3_key, + a.status, + a.variants, + a.error_code, + a.created_at, + a.updated_at + FROM attachments AS a + JOIN chat_members AS cm + ON cm.chat_id = a.chat_id + WHERE a.id = :attachment_id + AND cm.user_id = :current_user_id + """ + ), + { + "attachment_id": attachment_id, + "current_user_id": current_user_id, + }, + ) + + row = result.one_or_none() + + if row is None: + return None + + return attachment_from_row(row), row.s3_key + +async def attachment_key_exists(session: AsyncSession, s3_key: str) -> bool: + result = await session.execute( + text("SELECT 1 FROM attachments WHERE s3_key = :s3_key"), + {"s3_key": s3_key}, + ) + return result.first() is not None \ No newline at end of file diff --git a/src/runtime_metrics.py b/src/runtime_metrics.py new file mode 100644 index 00000000..194fbd49 --- /dev/null +++ b/src/runtime_metrics.py @@ -0,0 +1,158 @@ +import os +import resource +import time +from threading import Lock + +from opentelemetry import metrics +from opentelemetry.metrics import Observation + + +_lock = Lock() +_busy = 0 +_backlog = 0 +_oldest = 0.0 +_queue_updated = 0.0 +_initialized = False +_last_cpu = time.process_time() +_last_wall = time.monotonic() + + +def cpu_usage(options): + global _last_cpu, _last_wall + + with _lock: + cpu = time.process_time() + wall = time.monotonic() + + value = (cpu - _last_cpu) / max(wall - _last_wall, 0.001) + + _last_cpu = cpu + _last_wall = wall + + return [Observation(max(0, value) * 100)] + + +def memory_usage(options): + with open("/proc/self/statm", encoding="utf-8") as file: + resident = int(file.read().split()[1]) + + return [Observation(resident * os.sysconf("SC_PAGE_SIZE"))] + + +def worker_started(): + global _busy + + with _lock: + _busy += 1 + + +def worker_finished(): + global _busy + + with _lock: + _busy -= 1 + + +def update_queue(depth, oldest): + global _backlog, _oldest, _queue_updated + + with _lock: + _backlog = int(depth) + _oldest = float(oldest) + _queue_updated = time.monotonic() + + +def queue_observation(field): + def callback(options): + with _lock: + if not _queue_updated: + return [] + + if time.monotonic() - _queue_updated > 15: + return [] + + value = _backlog if field == "depth" else _oldest + + return [ + Observation( + value, + {"queue_name": "attachment.process.v1"}, + ) + ] + + return callback + + +def setup_runtime_metrics(service_name): + global _initialized + + if _initialized: + return + + from src.database import engine, POOL_SIZE, MAX_OVERFLOW + + meter = metrics.get_meter("messenger.runtime") + pool = engine.sync_engine.pool + + meter.create_observable_gauge( + "messenger_process_cpu_percent", + callbacks=[cpu_usage], + ) + + meter.create_observable_gauge( + "messenger_process_memory_bytes", + callbacks=[memory_usage], + ) + + meter.create_observable_gauge( + "messenger_db_pool_used", + callbacks=[ + lambda options: [Observation(pool.checkedout())] + ], + ) + + meter.create_observable_gauge( + "messenger_db_pool_capacity", + callbacks=[ + lambda options: [ + Observation(POOL_SIZE + MAX_OVERFLOW) + ] + ], + ) + + meter.create_observable_gauge( + "messenger_db_pool_waiting", + callbacks=[ + lambda options: [ + Observation(pool.waiting_count()) + ] + ], + ) + + if service_name == "messenger-worker": + meter.create_observable_gauge( + "messenger_worker_busy", + callbacks=[ + lambda options: [Observation(_busy)] + ], + ) + + meter.create_observable_gauge( + "messenger_worker_capacity", + callbacks=[ + lambda options: [Observation(1)] + ], + ) + + if service_name == "messenger-dispatcher": + meter.create_observable_gauge( + "messenger_queue_depth", + callbacks=[queue_observation("depth")], + ) + + meter.create_observable_gauge( + "messenger_queue_oldest_age_seconds", + callbacks=[queue_observation("oldest")], + ) + + _initialized = True diff --git a/src/security.py b/src/security.py new file mode 100644 index 00000000..91428d9d --- /dev/null +++ b/src/security.py @@ -0,0 +1,24 @@ +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError +from argon2.low_level import Type + + +password_hasher = PasswordHasher( + memory_cost=32768, + time_cost=2, + parallelism=1, + salt_len=16, + hash_len=32, + type=Type.ID, +) + + +def hash_password(password: str) -> str: + return password_hasher.hash(password) + + +def verify_password(password_hash: str, password: str) -> bool: + try: + return password_hasher.verify(password_hash, password) + except VerifyMismatchError: + return False diff --git a/src/sessions.py b/src/sessions.py new file mode 100644 index 00000000..0b4359c6 --- /dev/null +++ b/src/sessions.py @@ -0,0 +1,90 @@ +import os +import secrets +from uuid import UUID + +from redis.asyncio import Redis +from redis.exceptions import RedisError + +from src.errors import APIError + + +CACHE_URL_FILE = "/run/app-secrets/cache_url" +DEFAULT_SESSION_TTL_SECONDS = 3600 + + +def read_cache_url() -> str: + with open(CACHE_URL_FILE, encoding="utf-8") as file: + return file.read().strip() + + +def get_session_ttl_seconds() -> int: + return int( + os.getenv( + "SESSION_TTL_SECONDS", + str(DEFAULT_SESSION_TTL_SECONDS), + ) + ) + + +redis_client = Redis.from_url( + read_cache_url(), + decode_responses=True, + socket_connect_timeout=5, + socket_timeout=5, + ssl_ca_certs="/run/ca/ca.crt", + ssl_cert_reqs="required", + ssl_check_hostname=True, +) + + +def session_store_unavailable() -> APIError: + return APIError( + status_code=503, + code="unavailable", + message="Session store unavailable", + ) + + +async def create_session(user_id: UUID) -> tuple[str, int]: + token = secrets.token_urlsafe(32) + ttl = get_session_ttl_seconds() + + try: + await redis_client.set( + f"session:{token}", + str(user_id), + ex=ttl, + ) + except RedisError as exc: + raise session_store_unavailable() from exc + + return token, ttl + + +async def get_session_user_id(token: str) -> UUID | None: + try: + value = await redis_client.get(f"session:{token}") + except RedisError as exc: + raise session_store_unavailable() from exc + + if value is None: + return None + + try: + return UUID(value) + except ValueError: + return None + + +async def delete_session(token: str) -> None: + try: + await redis_client.delete(f"session:{token}") + except RedisError as exc: + raise session_store_unavailable() from exc + + +async def ping_session_store() -> bool: + try: + return bool(await redis_client.ping()) + except RedisError: + return False \ No newline at end of file diff --git a/src/storage.py b/src/storage.py new file mode 100644 index 00000000..d7bdced5 --- /dev/null +++ b/src/storage.py @@ -0,0 +1,117 @@ + +import asyncio +import os +from pathlib import Path + +import boto3 +from botocore.config import Config +from contextlib import contextmanager +from opentelemetry import trace +from opentelemetry.trace import SpanKind, Status, StatusCode + + +@contextmanager +def storage_span(operation): + tracer = trace.get_tracer("messenger.storage") + + with tracer.start_as_current_span( + f"s3.{operation}", + kind=SpanKind.CLIENT, + record_exception=False, + set_status_on_exception=False, + attributes={ + "rpc.system": "aws-api", + "rpc.service": "S3", + "rpc.method": operation, + }, + ) as span: + try: + yield + span.set_status(Status(StatusCode.OK)) + except Exception: + span.set_status(Status(StatusCode.ERROR)) + raise + + +def read_secret(env_name: str) -> str: + path = os.environ[env_name] + return Path(path).read_text(encoding="utf-8").strip() + + +s3_client = boto3.client( + "s3", + endpoint_url=os.environ["S3_ENDPOINT"], + verify="/run/ca/ca.crt", + region_name=os.getenv("S3_REGION", "us-east-1"), + aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"), + aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"), + config=Config( + signature_version="s3v4", + connect_timeout=2, + read_timeout=3, + retries={"total_max_attempts": 1, "mode": "standard"}, + s3={"addressing_style": "path"}, + ), +) + +S3_BUCKET = os.environ["S3_BUCKET"] + + +async def put_object(key: str, body: bytes, content_type: str) -> None: + with storage_span("PutObject"): + await asyncio.to_thread( + s3_client.put_object, + Bucket=S3_BUCKET, + Key=key, + Body=body, + ContentType=content_type, + ) + + +async def get_object(key: str) -> bytes: + with storage_span("GetObject"): + def download() -> bytes: + response = s3_client.get_object(Bucket=S3_BUCKET, Key=key) + stream = response["Body"] + try: + return stream.read() + finally: + stream.close() + + return await asyncio.to_thread(download) + + +async def delete_object(key: str) -> None: + with storage_span("DeleteObject"): + await asyncio.to_thread( + s3_client.delete_object, + Bucket=S3_BUCKET, + Key=key, + ) + + +async def ping_storage() -> bool: + try: + await asyncio.to_thread( + s3_client.head_bucket, + Bucket=S3_BUCKET, + ) + return True + except Exception: + return False + + +async def object_exists(key: str) -> bool: + from botocore.exceptions import ClientError + + try: + await asyncio.to_thread( + s3_client.head_object, + Bucket=S3_BUCKET, + Key=key, + ) + return True + except ClientError as exc: + if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}: + return False + raise \ No newline at end of file diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 00000000..5606b556 --- /dev/null +++ b/src/telemetry.py @@ -0,0 +1,369 @@ +import base64 +from pathlib import Path +import json +import logging +import os +import socket +import time + +from opentelemetry import metrics, trace +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator +from opentelemetry._logs import set_logger_provider +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.trace import SpanKind, Status, StatusCode + + +propagator = TraceContextTextMapPropagator() + + +def capture_trace_context(): + carrier = {} + propagator.inject(carrier) + return carrier + + +def restore_trace_context(carrier): + headers = { + key: value + for key, value in (carrier or {}).items() + if key in {"traceparent", "tracestate"} + and isinstance(value, str) + } + return propagator.extract(headers) + + +TELEMETRY_ENABLED = os.getenv( + "TELEMETRY_ENABLED", "1" +).lower() in {"1", "true", "yes", "on"} + +TRACE_SAMPLE_RATIO = float( + os.getenv("TELEMETRY_TRACE_SAMPLE_RATIO", "1.0") +) + +if not 0.0 <= TRACE_SAMPLE_RATIO <= 1.0: + raise ValueError("TELEMETRY_TRACE_SAMPLE_RATIO must be between 0 and 1") + +_initialized = False +logger = logging.getLogger("messenger.telemetry") + + +class JsonFormatter(logging.Formatter): + def format(self, record): + context = trace.get_current_span().get_span_context() + + return json.dumps({ + "timestamp": self.formatTime(record), + "level": record.levelname, + "event": record.getMessage(), + "trace_id": ( + format(context.trace_id, "032x") + if context.is_valid else "" + ), + "span_id": ( + format(context.span_id, "016x") + if context.is_valid else "" + ), + }, ensure_ascii=False) + + +def setup(service_name): + global _initialized + + if _initialized: + return + + if not TELEMETRY_ENABLED: + logger.handlers.clear() + logger.addHandler(logging.NullHandler()) + logger.propagate = False + _initialized = True + return + + resource = Resource.create({ + "service.name": service_name, + "service.version": os.getenv("APP_VERSION", "6.0.0"), + "service.instance.id": os.getenv( + "INSTANCE_ID", socket.gethostname() + ), + "deployment.environment.name": "lab", + }) + + endpoint = os.getenv( + "OTEL_EXPORTER_OTLP_ENDPOINT", + "https://otel-collector:4318", + ).rstrip("/") + + if not endpoint.startswith("https://"): + raise ValueError("OTLP endpoint must use HTTPS") + + username = os.environ["OTEL_USERNAME"] + + password = Path( + "/run/app-secrets/otel_password" + ).read_text().strip() + + credentials = base64.b64encode( + f"{username}:{password}".encode("utf-8") + ).decode("ascii") + + exporter_security = { + "certificate_file": "/run/ca/ca.crt", + "headers": { + "Authorization": f"Basic {credentials}", + }, + } + + tracer_provider = TracerProvider( + resource=resource, + sampler=ParentBased( + root=TraceIdRatioBased(TRACE_SAMPLE_RATIO) + ), + ) + tracer_provider.add_span_processor( + BatchSpanProcessor( + OTLPSpanExporter( + endpoint=f"{endpoint}/v1/traces", + **exporter_security, + timeout=3, + ), + max_queue_size=2048, + max_export_batch_size=256, + schedule_delay_millis=2000, + ) + ) + trace.set_tracer_provider(tracer_provider) + + reader = PeriodicExportingMetricReader( + OTLPMetricExporter( + endpoint=f"{endpoint}/v1/metrics", + **exporter_security, + timeout=3, + ), + export_interval_millis=5000, + export_timeout_millis=3000, + ) + + metrics.set_meter_provider( + MeterProvider( + resource=resource, + metric_readers=[reader], + views=[ + View( + instrument_name="messenger_http_request_duration", + aggregation=ExplicitBucketHistogramAggregation( + boundaries=[ + 0.005, 0.01, 0.025, 0.05, 0.1, + 0.25, 0.5, 1, 2.5, 5, 10, 30 + ] + ), + ), + View( + instrument_name="messenger_job_duration", + aggregation=ExplicitBucketHistogramAggregation( + boundaries=[ + 0.01, 0.025, 0.05, 0.1, 0.25, + 0.5, 1, 2.5, 5, 10, 30, 60 + ] + ), + ), + View( + instrument_name="messenger_attachment_ready_duration", + aggregation=ExplicitBucketHistogramAggregation( + boundaries=[ + 0.1, 0.25, 0.5, 1, 2, 3, 5, + 10, 15, 30, 60, 120, 300 + ] + ), + ), + ], + ) + ) + + logger_provider = LoggerProvider(resource=resource) + logger_provider.add_log_record_processor( + BatchLogRecordProcessor( + OTLPLogExporter( + endpoint=f"{endpoint}/v1/logs", + **exporter_security, + timeout=3, + ), + max_queue_size=2048, + max_export_batch_size=256, + schedule_delay_millis=2000, + ) + ) + set_logger_provider(logger_provider) + + handler = LoggingHandler( + level=logging.INFO, + logger_provider=logger_provider, + ) + handler.setFormatter(JsonFormatter()) + + logger.handlers.clear() + logger.addHandler(handler) + logger.setLevel(logging.INFO) + logger.propagate = False + + from src.runtime_metrics import setup_runtime_metrics + + setup_runtime_metrics(service_name) + + _initialized = True + + +def event(name, **fields): + if not TELEMETRY_ENABLED: + return + + logger.info( + json.dumps( + {"event": name, **fields}, + ensure_ascii=False, + ) + ) + + +class HTTPMetricsMiddleware: + def __init__(self, app): + self.app = app + + meter = metrics.get_meter("messenger.api") + + self.requests = meter.create_counter( + "messenger_http_requests", + description="HTTP requests", + ) + + self.duration = meter.create_histogram( + "messenger_http_request_duration", + unit="s", + description="HTTP request duration", + ) + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + started = time.perf_counter() + status = 500 + + async def wrapped_send(message): + nonlocal status + + if message["type"] == "http.response.start": + status = message["status"] + + await send(message) + + try: + await self.app(scope, receive, wrapped_send) + finally: + route = getattr( + scope.get("route"), "path", "unmatched" + ) + + method = scope.get("method", "OTHER") + + if method not in { + "GET", "POST", "PUT", "PATCH", + "DELETE", "HEAD", "OPTIONS", + }: + method = "OTHER" + + elapsed = time.perf_counter() - started + + attributes = { + "method": method, + "route": route, + "status_code": status, + "status_class": f"{status // 100}xx", + } + + self.requests.add(1, attributes) + self.duration.record(elapsed, attributes) + + event( + "http_request_completed", + method=method, + route=route, + status_code=status, + duration_ms=round(elapsed * 1000, 3), + ) + + +async def observe_job(process, payload, headers=None): + if not TELEMETRY_ENABLED: + return await process(payload) + + tracer = trace.get_tracer("messenger.worker") + meter = metrics.get_meter("messenger.worker") + + jobs = meter.create_counter( + "messenger_jobs", + description="Job processing attempts by outcome", + ) + + duration = meter.create_histogram( + "messenger_job_duration", + unit="s", + description="Job processing duration", + ) + + started = time.perf_counter() + outcome = "error" + + with tracer.start_as_current_span( + "attachment.process", + kind=SpanKind.CONSUMER, + context=restore_trace_context(headers), + record_exception=False, + set_status_on_exception=False, + ) as span: + try: + outcome = await process(payload) + + if outcome not in { + "success", "failed", "retry", "skipped" + }: + outcome = "unknown" + + return outcome + + finally: + elapsed = time.perf_counter() - started + + span.set_attribute("job.outcome", outcome) + span.set_attribute("job.type", "attachment.process.v1") + span.set_attribute("job.attempt", payload.get("attempt", 1)) + span.set_attribute("job.generation", payload.get("generation", 1)) + + if outcome in {"failed", "retry", "error", "unknown"}: + span.set_status(Status(StatusCode.ERROR)) + else: + span.set_status(Status(StatusCode.OK)) + + attributes = { + "job_type": "attachment.process.v1", + "outcome": outcome, + } + jobs.add(1, attributes) + duration.record(elapsed, attributes) + + event( + "job_processing_completed", + outcome=outcome, + duration_ms=round(elapsed * 1000, 3), + ) diff --git a/src/worker.py b/src/worker.py new file mode 100644 index 00000000..cc3795a6 --- /dev/null +++ b/src/worker.py @@ -0,0 +1,489 @@ +import asyncio +import hashlib +import io +import os +import json +import logging +import time +import random +from uuid import UUID, uuid4 + +from PIL import Image, ImageOps, UnidentifiedImageError +from sqlalchemy import text + +from src.database import SessionFactory +from src.telemetry import setup, observe_job +from src.runtime_metrics import worker_started, worker_finished +from opentelemetry import metrics +from src.queue import QUEUE, connect +from src.storage import get_object, put_object +from src.images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES + +logging.basicConfig(level=logging.INFO) + +MAX_PROCESSING_SECONDS = float( + os.getenv("MAX_PROCESSING_SECONDS", "30") +) + + +class PermanentProcessingError(Exception): + pass + + +def retry_delay(attempt: int) -> float: + base = min(60.0, 2.0 ** attempt) + return base * random.uniform(0.75, 1.25) + + +def validate_worker_image(body: bytes): + if not body or len(body) > MAX_UPLOAD_BYTES: + raise PermanentProcessingError("invalid_image_size") + + try: + with Image.open(io.BytesIO(body)) as image: + if image.format not in {"PNG", "JPEG"}: + raise PermanentProcessingError("unsupported_image_format") + + if image.width * image.height > MAX_IMAGE_PIXELS: + raise PermanentProcessingError("image_pixel_limit") + + image.verify() + + except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc: + raise PermanentProcessingError("invalid_image") from exc + + +def make_thumbnail(body: bytes): + with Image.open(io.BytesIO(body)) as source: + source.load() + image = ImageOps.exif_transpose(source) + image.thumbnail((256, 256), Image.Resampling.LANCZOS) + + if image.mode != "RGB": + rgba = image.convert("RGBA") + background = Image.new("RGBA", rgba.size, "white") + background.alpha_composite(rgba) + image = background.convert("RGB") + + output = io.BytesIO() + image.save(output, format="JPEG", quality=85, optimize=True) + + return output.getvalue(), image.width, image.height + + +def make_crop(body: bytes): + with Image.open(io.BytesIO(body)) as source: + source.load() + image = ImageOps.exif_transpose(source).convert("RGB") + image = ImageOps.fit( + image, + (128, 128), + method=Image.Resampling.LANCZOS, + centering=(0.5, 0.5), + ) + + output = io.BytesIO() + image.save(output, format="JPEG", quality=85, optimize=True) + + return output.getvalue(), image.width, image.height + + +def make_optimized(body: bytes): + with Image.open(io.BytesIO(body)) as source: + source.load() + image = ImageOps.exif_transpose(source).convert("RGB") + + output = io.BytesIO() + image.save(output, format="WEBP", quality=80, method=4) + + return output.getvalue(), image.width, image.height + + +def fault_injection(point: str): + if os.getenv("FAULT_INJECTION_ENABLED") != "1": + return + + if os.getenv("FAULT_INJECTION_POINT") != point: + return + + marker = f"/tmp/lab5_fault_{point}" + + try: + fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return + + os.close(fd) + logging.error("FAULT INJECTION: %s", point) + os._exit(77) + + +async def process(payload: dict): + job_id = UUID(payload["job_id"]) + attachment_id = UUID(payload["attachment_id"]) + generation = payload.get("generation", 1) + execution_id = uuid4() + + + async with SessionFactory() as session: + async with session.begin(): + result = await session.execute( + text(""" + SELECT j.status, j.attempt, j.generation, + a.s3_key, a.content_type, a.chat_id, j.created_at + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = :job_id + AND j.attachment_id = :attachment_id + FOR UPDATE OF j + """), + {"job_id": job_id, "attachment_id": attachment_id}, + ) + + row = result.one_or_none() + + if row is None or row.status in ("ready", "failed"): + return "skipped" + + if row.attempt != payload["attempt"]: + return "skipped" + + if row.generation != generation: + return "skipped" + + if row.status == "processing": + return "skipped" + + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'processing', + started_at = now(), + execution_id = :execution_id + WHERE id = :id + """), + {"id": job_id, "execution_id": execution_id}, + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'processing', updated_at = now() + WHERE id = :id + """), + {"id": attachment_id}, + ) + + try: + retry_marker = "/tmp/lab6_retry_once" + try: + os.unlink(retry_marker) + except FileNotFoundError: + pass + else: + await asyncio.sleep(8) + raise RuntimeError("controlled_temporary_failure") + + body = await get_object(row.s3_key) + validate_worker_image(body) + thumbnail, width, height = await asyncio.to_thread( + make_thumbnail, body + ) + + crop, crop_width, crop_height = await asyncio.to_thread( + make_crop, body + ) + + optimized, optimized_width, optimized_height = await asyncio.to_thread( + make_optimized, body + ) + + original_key = ( + f"attachments/{row.chat_id}/{attachment_id}/g{generation}/original" + ) + thumbnail_key = ( + f"variants/{row.chat_id}/{attachment_id}/g{generation}/thumbnail.jpg" + ) + + fault_injection("before_side_effect") + + await put_object(original_key, body, row.content_type) + await put_object(thumbnail_key, thumbnail, "image/jpeg") + crop_key = ( + f"variants/{row.chat_id}/{attachment_id}/g{generation}/crop.jpg" + ) + optimized_key = ( + f"variants/{row.chat_id}/{attachment_id}/g{generation}/optimized.webp" + ) + + await put_object(crop_key, crop, "image/jpeg") + await put_object(optimized_key, optimized, "image/webp") + + fault_injection("after_side_effect") + + + if ( + os.getenv("FAULT_INJECTION_ENABLED") == "1" + and os.getenv("FAULT_INJECTION_POINT") == "pause_before_commit" + ): + marker = "/tmp/lab5_pause_before_commit" + + with open(marker, "w", encoding="utf-8") as file: + file.write(str(execution_id)) + + deadline = time.monotonic() + 180 + + while os.path.exists(marker): + if time.monotonic() >= deadline: + raise TimeoutError("pause_before_commit_timeout") + await asyncio.sleep(0.1) + + + variant = { + "name": "thumbnail", + "s3_key": thumbnail_key, + "content_type": "image/jpeg", + "size_bytes": len(thumbnail), + "width": width, + "height": height, + "sha256": hashlib.sha256(thumbnail).hexdigest(), + } + + async with SessionFactory() as session: + async with session.begin(): + result = await session.execute( + text(""" + SELECT status, attempt, generation, execution_id + FROM attachment_jobs + WHERE id = :id + FOR UPDATE + """), + {"id": job_id}, + ) + + current = result.one_or_none() + + if ( + current is None + or current.status != "processing" + or current.attempt != row.attempt + or current.generation != generation + or current.execution_id != execution_id + ): + return "skipped" + await session.execute( + text(""" + UPDATE attachments + SET status = 'ready', + s3_key = :key, + variants = CAST(:variants AS json), + error_code = NULL, + updated_at = now() + WHERE id = :id + """), + { + "id": attachment_id, + "key": original_key, + "variants": json.dumps([ + variant, + { + "name": "crop", + "s3_key": crop_key, + "content_type": "image/jpeg", + "size_bytes": len(crop), + "width": crop_width, + "height": crop_height, + "sha256": hashlib.sha256(crop).hexdigest(), + }, + { + "name": "optimized", + "s3_key": optimized_key, + "content_type": "image/webp", + "size_bytes": len(optimized), + "width": optimized_width, + "height": optimized_height, + "sha256": hashlib.sha256(optimized).hexdigest(), + }, + ]), + }, + ) + + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'ready', + next_attempt_at = NULL, + last_error_code = NULL, + finished_at = now() + WHERE id = :id + """), + {"id": job_id}, + ) + + + meter = metrics.get_meter("messenger.worker") + + end_to_end = meter.create_histogram( + "messenger_attachment_ready_duration", + unit="s", + description="Time from durable acceptance to ready", + ) + + end_to_end.record( + max(0, time.time() - row.created_at.timestamp()), + {"job_type": "attachment.process.v1"}, + ) + + return "success" + + except Exception as exc: + + logging.exception("Processing failed: %s", attachment_id) + + permanent = isinstance(exc, PermanentProcessingError) + + error_code = ( + + str(exc)[:64] + + if permanent + + else "temporary_processing_error" + + ) + + async with SessionFactory() as session: + async with session.begin(): + result = await session.execute( + text(""" + SELECT status, attempt, generation, execution_id + FROM attachment_jobs + WHERE id = :id + FOR UPDATE + """), + {"id": job_id}, + ) + + current = result.one_or_none() + + if ( + current is None + or current.status != "processing" + or current.attempt != row.attempt + or current.generation != generation + or current.execution_id != execution_id + ): + return "skipped" + if permanent or row.attempt >= 5: + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'failed', + next_attempt_at = NULL, + last_error_code = :error_code, + finished_at = now() + WHERE id = :id + """), + {"id": job_id, "error_code": error_code}, + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'failed', + error_code = :error_code, + updated_at = now() + WHERE id = :id + """), + { + "id": attachment_id, + "error_code": error_code, + }, + ) + else: + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'queued', + attempt = attempt + 1, + published_at = NULL, + started_at = NULL, + next_attempt_at = now() + (:delay * interval '1 second'), + last_error_code = :error_code + WHERE id = :id + """), + { + "id": job_id, + "delay": retry_delay(row.attempt), + "error_code": error_code, + } + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'queued', updated_at = now() + WHERE id = :id + """), + {"id": attachment_id}, + ) + + + return "failed" if permanent or row.attempt >= 5 else "retry" + + +def main(): + setup("messenger-worker") + while True: + connection = None + + try: + connection, channel = connect() + channel.basic_qos(prefetch_count=1) + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + def callback(ch, method, properties, body): + + worker_started() + try: + loop.run_until_complete( + asyncio.wait_for( + observe_job( + process, + json.loads(body), + properties.headers, + ), + timeout=MAX_PROCESSING_SECONDS, + ) + ) + fault_injection("before_ack") + ch.basic_ack(delivery_tag=method.delivery_tag) + except Exception: + logging.exception("Worker processing error") + ch.basic_nack( + delivery_tag=method.delivery_tag, + requeue=True, + ) + time.sleep(2) + finally: + worker_finished() + + channel.basic_consume( + queue=QUEUE, + on_message_callback=callback, + ) + channel.start_consuming() + + except Exception: + logging.exception("Worker reconnect") + time.sleep(3) + + finally: + if connection and connection.is_open: + connection.close() + + +if __name__ == "__main__": + main() diff --git a/student-tests/audit_containers.py b/student-tests/audit_containers.py new file mode 100644 index 00000000..3cebc30e --- /dev/null +++ b/student-tests/audit_containers.py @@ -0,0 +1,52 @@ +import json +import subprocess + +ids = subprocess.check_output( + ["docker", "compose", "ps", "-q"], + text=True, +).split() + +assert ids, "No running containers" + +containers = json.loads( + subprocess.check_output( + ["docker", "inspect", *ids], + text=True, + ) +) + +for container in sorted(containers, key=lambda c: c["Name"]): + name = container["Config"]["Labels"][ + "com.docker.compose.service" + ] + + host = container["HostConfig"] + config = container["Config"] + + print(f"\n=== {name} ===") + print("User:", config["User"] or "image default") + print("Privileged:", host["Privileged"]) + print("Network mode:", host["NetworkMode"]) + print("PID mode:", host["PidMode"] or "private") + print("CapAdd:", host["CapAdd"]) + print("CapDrop:", host["CapDrop"]) + print("SecurityOpt:", host["SecurityOpt"]) + print("Memory MiB:", host["Memory"] // 1024**2) + print("CPU:", host["NanoCpus"] / 10**9) + print("PidsLimit:", host.get("PidsLimit")) + print("ReadOnlyRootfs:", host["ReadonlyRootfs"]) + print("Published ports:", host["PortBindings"]) + + assert not host["Privileged"], name + assert host["NetworkMode"] != "host", name + assert host["PidMode"] != "host", name + assert host["IpcMode"] != "host", name + assert not host["CapAdd"], name + + for mount in container["Mounts"]: + assert "docker.sock" not in mount["Source"], name + assert "docker.sock" not in mount["Destination"], name + + print("PASS: basic isolation") + +print("\nPASS: BASIC CONTAINER ISOLATION") diff --git a/student-tests/audit_images.py b/student-tests/audit_images.py new file mode 100644 index 00000000..f2a6cab5 --- /dev/null +++ b/student-tests/audit_images.py @@ -0,0 +1,203 @@ +import json +import subprocess +import tarfile +import tempfile +from pathlib import Path + +source = Path("student-tests/audit_secrets.py").read_text() +namespace = {} + +exec( + source.split('paths = subprocess.check_output(', 1)[0], + namespace, +) + +patterns = namespace["values"] +private_key = namespace["private_key"] + +services = [ + "api-1", + "api-2", + "worker", + "dispatcher", + "migrate", +] + +failures = 0 +files_checked = 0 +layers_checked = set() + +overlap = max( + 256, + max(len(value) for value in patterns), +) + + +def command(*args): + return subprocess.check_output(args) + + +def inspect_stream(stream, label): + global failures + + tail = b"" + + while True: + chunk = stream.read(1024 * 1024) + + if not chunk: + break + + content = tail + chunk + + if any(value in content for value in patterns): + print("FAIL: known credential:", label) + failures += 1 + return + + if private_key.search(content): + print("FAIL: private key:", label) + failures += 1 + return + + tail = content[-overlap:] + + +def inspect_bytes(content, label): + import io + + inspect_stream(io.BytesIO(content), label) + + +images = {} + +for service in services: + container = command( + "docker", "compose", "ps", "-a", "-q", service + ).decode().strip() + + assert container, f"Missing container: {service}" + + image_name = command( + "docker", "inspect", + "--format", "{{.Config.Image}}", + container, + ).decode().strip() + + image = command( + "docker", "image", "inspect", + "--format", "{{.Id}}", + image_name, + ).decode().strip() + + print(f"Selected: {service}: {image_name}: {image}") + + images.setdefault(image, []).append(service) + + +print("=== DOCKER IMAGE SECRET AUDIT ===") +print("Services:", len(services)) +print("Unique images:", len(images)) +print("Credential patterns:", len(patterns)) + +for image, names in images.items(): + label = ",".join(names) + + print("\nInspecting:", label, flush=True) + + inspect_bytes( + command("docker", "image", "inspect", image), + f"{label}: image configuration", + ) + + inspect_bytes( + command( + "docker", "history", + "--no-trunc", image, + ), + f"{label}: build history", + ) + + with tempfile.TemporaryDirectory( + prefix="lab7-image-audit-" + ) as directory: + + archive = Path(directory) / "image.tar" + + subprocess.run( + [ + "docker", "image", "save", + "-o", str(archive), image, + ], + check=True, + ) + + with tarfile.open(archive, "r:*") as outer: + manifest = json.load( + outer.extractfile("manifest.json") + ) + + for entry in manifest: + config = outer.extractfile(entry["Config"]) + + inspect_stream( + config, + f"{label}: archived configuration", + ) + + for layer in entry["Layers"]: + if layer in layers_checked: + continue + + layer_stream = outer.extractfile(layer) + + with tarfile.open( + fileobj=layer_stream, + mode="r|*", + ) as inner: + + for member in inner: + inspect_bytes( + member.name.encode(), + f"{label}: layer path", + ) + + if not member.isfile(): + continue + + files_checked += 1 + + stream = inner.extractfile(member) + + if stream is not None: + inspect_stream( + stream, + f"{label}: layer file " + f"#{files_checked}", + ) + + layers_checked.add(layer) + + print( + "Layers checked:", + len(layers_checked), + "| Files checked:", + files_checked, + flush=True, + ) + + print("Completed:", label, flush=True) + + +print("\n=== SUMMARY ===") +print("Services inspected:", len(services)) +print("Unique images inspected:", len(images)) +print("Unique layers inspected:", len(layers_checked)) +print("Layer files inspected:", files_checked) +print("Credential patterns:", len(patterns)) +print("Failures:", failures) + +assert files_checked > 0 +assert failures == 0, "Image secret audit failed" + +print("PASS: DOCKER IMAGE SECRET AUDIT") diff --git a/student-tests/audit_network.py b/student-tests/audit_network.py new file mode 100644 index 00000000..2761708f --- /dev/null +++ b/student-tests/audit_network.py @@ -0,0 +1,41 @@ +import socket + +targets = { + "nginx": [80, 443, 8080, 8443], + "api-1": [8080, 8443], + "api-2": [8080, 8443], + "worker": [8080], + "dispatcher": [8080], + "postgres": [5432], + "redis": [6379], + "rabbitmq": [ + 4369, 5671, 5672, 15671, 15672, + 15691, 15692, 25672, + ], + "s3": [9000, 9001], + "openbao": [8200, 8201], + "otel-collector": [ + 4317, 4318, 8888, 8889, + 18888, 18889, 55678, 55679, + ], + "prometheus": [9090], + "loki": [3100, 7946, 9095, 13100], + "tempo": [3200, 4317, 4318, 7946, 9095, 13200, 14318], + "grafana": [3000], +} + +for host, ports in targets.items(): + print(f"\n=== {host} ===") + + socket.gethostbyname(host) + + for port in ports: + try: + with socket.create_connection( + (host, port), timeout=1 + ): + print(f"{port}: OPEN") + except OSError: + print(f"{port}: CLOSED") + +print("\nNETWORK AUDIT COMPLETE") diff --git a/student-tests/audit_secrets.py b/student-tests/audit_secrets.py new file mode 100644 index 00000000..3071eedc --- /dev/null +++ b/student-tests/audit_secrets.py @@ -0,0 +1,133 @@ +import base64 +import json +import os +import re +import subprocess +from pathlib import Path +from urllib.parse import urlsplit + + +values = set() + + +def add(value): + if isinstance(value, str) and len(value.strip()) >= 16: + values.add(value.strip().encode()) + + +for path in Path("secrets").iterdir(): + if not path.is_file(): + continue + + content = path.read_text().strip() + + if re.fullmatch(r"[a-zA-Z0-9_-]{16,}", content): + add(content) + + if "://" in content and "\n" not in content: + add(content) + add(urlsplit(content).password) + + if content.startswith("Basic "): + add(content) + add(content.split(" ", 1)[1]) + + +for line in Path(".env").read_text().splitlines(): + if line.startswith("GRAFANA_ADMIN_PASSWORD="): + add(line.split("=", 1)[1]) + + +operator_file = Path( + os.getenv( + "BAO_OPERATOR_FILE", + str( + Path.home() + / ".local/share/lab7-openbao-operator/init.json" + ), + ) +) + +operator = json.loads(operator_file.read_text()) + +add(operator["root_token"]) + +for name in ("unseal_keys_b64", "unseal_keys_hex"): + for value in operator.get(name, []): + add(value) + + +# Include encoded Basic authentication credentials. +for filename, username in ( + ("otel_api_password", "messenger_api"), + ("otel_worker_password", "messenger_worker"), + ("otel_dispatcher_password", "messenger_dispatcher"), + ("otel_backend_password", "collector"), + ("grafana_datasource_password", "grafana"), + ("prometheus_scrape_password", "prometheus"), +): + password = (Path("secrets") / filename).read_text().strip() + values.add( + base64.b64encode(f"{username}:{password}".encode()) + ) + + +private_key = re.compile( + rb"-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----" +) + + +def inspect(label, content): + reasons = [] + + if any(value in content for value in values): + reasons.append("known local credential") + + if private_key.search(content): + reasons.append("private key") + + if reasons: + print(f"FAIL: {label}: {', '.join(reasons)}") + return False + + return True + + +paths = subprocess.check_output( + ["git", "ls-files", "-z"] +).decode().split("\0") + +paths = [path for path in paths if path] + +failures = 0 + +for path in paths: + content = subprocess.check_output( + ["git", "show", f":{path}"] + ) + + if not inspect(path, content): + failures += 1 + + +print("Tracked files checked:", len(paths)) +print("Known credential patterns checked:", len(values)) + + +logs = subprocess.check_output( + ["docker", "compose", "logs", "--no-color"], + stderr=subprocess.STDOUT, +) + +if not inspect("Docker Compose logs", logs): + failures += 1 +else: + print("PASS: no known local credentials in container logs") + + +print("Failures:", failures) + +if failures: + raise SystemExit(1) + +print("PASS: SECRET AUDIT") diff --git a/student-tests/audit_telemetry.py b/student-tests/audit_telemetry.py new file mode 100644 index 00000000..78feb3b2 --- /dev/null +++ b/student-tests/audit_telemetry.py @@ -0,0 +1,292 @@ +import argparse +import base64 +import json +import ssl +import time +from pathlib import Path +from urllib.parse import urlencode +from urllib.request import Request, urlopen +from urllib.error import HTTPError, URLError + +# Reuse credential patterns from the existing secret audit. +source = Path("student-tests/audit_secrets.py").read_text() +namespace = {} + +exec( + source.split('paths = subprocess.check_output(', 1)[0], + namespace, +) + +patterns = namespace["values"] +private_key = namespace["private_key"] + +password = next( + line.split("=", 1)[1].strip().strip("\"'") + for line in Path(".env").read_text().splitlines() + if line.startswith("GRAFANA_ADMIN_PASSWORD=") +) + +authorization = "Basic " + base64.b64encode( + f"admin:{password}".encode() +).decode() + +patterns.add(authorization.encode()) +patterns.add(authorization.split(" ", 1)[1].encode()) + +context = ssl.create_default_context( + cafile="certs/ca/ca.crt" +) + +BASE = "https://localhost:3000" +END = int(time.time()) +START = END - 7 * 24 * 3600 + +failures = 0 + + +def inspect(label, content): + global failures + + if isinstance(content, str): + content = content.encode() + + if any(value in content for value in patterns): + print(f"FAIL: {label}: known credential detected") + failures += 1 + + if private_key.search(content): + print(f"FAIL: {label}: private key detected") + failures += 1 + + +def query(uid, path, params=None): + url = f"{BASE}/api/datasources/proxy/uid/{uid}{path}" + + if params: + url += "?" + urlencode(params) + + request = Request( + url, + headers={ + "Authorization": authorization, + "Accept": "application/json", + }, + ) + + for attempt in range(3): + try: + with urlopen( + request, + context=context, + timeout=15, + ) as response: + raw = response.read() + break + except (HTTPError, URLError, TimeoutError) as exc: + if isinstance(exc, HTTPError): + if exc.code not in (429, 500, 502, 503, 504): + raise + + if attempt == 2: + raise + + time.sleep(attempt + 1) + + inspect(uid, raw) + + result = json.loads(raw) + + # Also inspect decoded JSON strings. + inspect( + uid, + json.dumps(result, ensure_ascii=False), + ) + + if result.get("status") == "error": + raise RuntimeError(f"{uid}: query failed") + + return result + + +print("=== TELEMETRY SECRET AUDIT ===") +print("Audit window: 7 days") +print("Credential patterns:", len(patterns)) +print("TLS CA and hostname verification: enabled") + +def scan_loki(): + # Loki: discover labels and inspect stored log records. + print("\n=== Loki ===") + + labels = query( + "loki", + "/loki/api/v1/labels", + { + "start": str(START * 10**9), + "end": str(END * 10**9), + }, + )["data"] + + assert "service_name" in labels, "Missing service_name label" + + services = query( + "loki", + "/loki/api/v1/label/service_name/values", + { + "start": str(START * 10**9), + "end": str(END * 10**9), + }, + )["data"] + + assert services, "No Loki services found" + + log_count = 0 + LIMIT = 1000 + + + def scan_logs(selector, start, end): + result = query( + "loki", + "/loki/api/v1/query_range", + { + "query": selector, + "start": str(start), + "end": str(end), + "limit": LIMIT, + "direction": "forward", + }, + ) + + streams = result["data"]["result"] + + count = sum( + len(stream.get("values", [])) + for stream in streams + ) + + if count >= LIMIT: + assert end > start, "Loki query saturated" + + middle = (start + end) // 2 + + return ( + scan_logs(selector, start, middle) + + scan_logs(selector, middle + 1, end) + ) + + return count + + + for service in services: + selector = "{service_name=" + json.dumps(service) + "}" + + log_count += scan_logs( + selector, + START * 10**9, + END * 10**9, + ) + + assert log_count > 0, "No Loki logs inspected" + + print("Loki services inspected:", len(services)) + print("Loki log records inspected:", log_count) + print("PASS: Loki scan completed") + + +def scan_tempo(): + # Tempo: discover traces and retrieve complete trace bodies. + print("\n=== Tempo ===") + + trace_ids = set() + TRACE_LIMIT = 100 + + + def discover_traces(start, end): + result = query( + "tempo", + "/api/search", + { + "q": "{}", + "start": start, + "end": end, + "limit": TRACE_LIMIT, + }, + ) + + traces = result.get("traces", []) + + if len(traces) >= TRACE_LIMIT: + assert end > start, "Tempo search saturated" + + middle = (start + end) // 2 + + discover_traces(start, middle) + discover_traces(middle + 1, end) + return + + for item in traces: + trace_ids.add(item["traceID"]) + + + # Query in hourly windows. + for start in range(max(START, END - 600), END, 3600): + discover_traces( + start, + min(start + 3599, END), + ) + + assert trace_ids, "No Tempo traces found" + + print("Tempo audit window: last 10 minutes") + print("Tempo traces discovered:", len(trace_ids)) + + selected = sorted(trace_ids)[:100] + + for index, trace_id in enumerate(selected, 1): + if index == 1 or index % 10 == 0: + print(f"Tempo progress: {index}/{len(selected)}") + query( + "tempo", + f"/api/traces/{trace_id}", + ) + + print("Tempo trace bodies inspected:", len(selected)) + print("PASS: Tempo scan completed") + + +def scan_prometheus(): + # Prometheus: inspect historical series labels. + print("\n=== Prometheus ===") + + series = query( + "prometheus", + "/api/v1/series", + { + "match[]": '{__name__=~".+"}', + "start": START, + "end": END, + }, + )["data"] + + assert series, "No Prometheus series found" + + print("Prometheus series inspected:", len(series)) + print("PASS: Prometheus scan completed") + + + +parser = argparse.ArgumentParser() +parser.add_argument( + "backend", + choices=["loki", "tempo", "prometheus"], +) +args = parser.parse_args() + +{ + "loki": scan_loki, + "tempo": scan_tempo, + "prometheus": scan_prometheus, +}[args.backend]() + +print("Failures:", failures) +assert failures == 0, "Telemetry credential audit failed" +print("PASS: TELEMETRY SECRET AUDIT:", args.backend) diff --git a/student-tests/benchmark_argon2.py b/student-tests/benchmark_argon2.py new file mode 100644 index 00000000..cd3fc385 --- /dev/null +++ b/student-tests/benchmark_argon2.py @@ -0,0 +1,57 @@ +from statistics import median +from time import perf_counter + +from argon2 import PasswordHasher +from argon2.low_level import Type + + +PASSWORD = "Synthetic-Benchmark-Password-2026!" +REPEATS = 10 + +CONFIGURATIONS = [ + (19456, 2, 1), + (32768, 2, 1), + (65536, 3, 1), + (65536, 3, 4), +] + + +def main(): + print(f"Argon2id benchmark: {REPEATS} iterations per configuration") + + for memory, iterations, parallelism in CONFIGURATIONS: + hasher = PasswordHasher( + memory_cost=memory, + time_cost=iterations, + parallelism=parallelism, + salt_len=16, + hash_len=32, + type=Type.ID, + ) + + warmup = hasher.hash(PASSWORD) + assert hasher.verify(warmup, PASSWORD) + + hash_times = [] + verify_times = [] + + for _ in range(REPEATS): + start = perf_counter() + encoded = hasher.hash(PASSWORD) + hash_times.append((perf_counter() - start) * 1000) + + start = perf_counter() + assert hasher.verify(encoded, PASSWORD) + verify_times.append((perf_counter() - start) * 1000) + + print( + f"m={memory} KiB, t={iterations}, p={parallelism}: " + f"hash={median(hash_times):.2f} ms, " + f"verify={median(verify_times):.2f} ms" + ) + + print("PASS: all configurations verified successfully") + + +if __name__ == "__main__": + main() diff --git a/student-tests/diagnose_secrets.py b/student-tests/diagnose_secrets.py new file mode 100644 index 00000000..67c816bb --- /dev/null +++ b/student-tests/diagnose_secrets.py @@ -0,0 +1,126 @@ +import base64 +import json +import os +import subprocess +from pathlib import Path +from urllib.parse import urlsplit + + +patterns = {} + + +def add(name, value): + if isinstance(value, str) and len(value.strip()) >= 16: + patterns[name] = value.strip().encode() + + +for path in Path("secrets").iterdir(): + if not path.is_file(): + continue + + content = path.read_text().strip() + + if "\n" not in content: + add(path.name, content) + + if "://" in content: + add( + path.name + ":password", + urlsplit(content).password, + ) + + if content.startswith("Basic "): + add( + path.name + ":base64", + content.split(" ", 1)[1], + ) + + +for line in Path(".env").read_text().splitlines(): + if line.startswith("GRAFANA_ADMIN_PASSWORD="): + add( + "grafana_admin_password", + line.split("=", 1)[1], + ) + + +operator_file = Path( + os.getenv( + "BAO_OPERATOR_FILE", + str( + Path.home() + / ".local/share/lab7-openbao-operator/init.json" + ), + ) +) + +operator = json.loads(operator_file.read_text()) + +add("openbao_root_token", operator["root_token"]) + +for name in ("unseal_keys_b64", "unseal_keys_hex"): + for i, value in enumerate(operator.get(name, [])): + add(f"{name}[{i}]", value) + + +for filename, username in ( + ("otel_api_password", "messenger_api"), + ("otel_worker_password", "messenger_worker"), + ("otel_dispatcher_password", "messenger_dispatcher"), + ("otel_backend_password", "collector"), + ("grafana_datasource_password", "grafana"), + ("prometheus_scrape_password", "prometheus"), +): + password = ( + Path("secrets") / filename + ).read_text().strip() + + add( + filename + ":basic_auth", + base64.b64encode( + f"{username}:{password}".encode() + ).decode(), + ) + + +def inspect(label, content): + for number, line in enumerate( + content.splitlines(), start=1 + ): + for name, value in patterns.items(): + if value in line: + print( + f"MATCH: {label}, " + f"line={number}, " + f"credential={name}" + ) + + +print("=== Evidence ===") + +path = Path( + "evidence/grade3-messaging-storage-config.txt" +) + +inspect(str(path), path.read_bytes()) + + +print("\n=== Container logs ===") + +services = subprocess.check_output( + ["docker", "compose", "config", "--services"], + text=True, +).splitlines() + +for service in services: + logs = subprocess.check_output( + [ + "docker", "compose", "logs", + "--no-color", service, + ], + stderr=subprocess.STDOUT, + ) + + inspect(service, logs) + +print("\nDiagnostic completed; values not displayed.") diff --git a/student-tests/test_collector_security.py b/student-tests/test_collector_security.py new file mode 100644 index 00000000..291a0bbe --- /dev/null +++ b/student-tests/test_collector_security.py @@ -0,0 +1,250 @@ +import base64 +import socket +import ssl +import time +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +from test_telemetry_backends import make_otlp_payload + +from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ( + ExportMetricsServiceRequest, +) + +HOST = "otel-collector" +SECRET_DIR = Path("/test-secrets") + +CONTEXT = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + + +def auth(username, filename): + password = (SECRET_DIR / filename).read_text().strip() + + encoded = base64.b64encode( + f"{username}:{password}".encode() + ).decode() + + return f"Basic {encoded}" + + +def request(port, path, authorization=None, body=None): + headers = {} + + if authorization: + headers["Authorization"] = authorization + + if body is not None: + headers["Content-Type"] = "application/x-protobuf" + + req = Request( + f"https://{HOST}:{port}{path}", + headers=headers, + data=body, + method="POST" if body is not None else "GET", + ) + + try: + with urlopen( + req, + context=CONTEXT, + timeout=10, + ) as response: + return response.status, response.read() + except HTTPError as exc: + return exc.code, exc.read() + + +def expect(label, actual, expected): + assert actual == expected, ( + f"{label}: expected {expected}, got {actual}" + ) + + print(f"PASS: {label}: {actual}") + + +def test_tls(port): + with socket.create_connection( + (HOST, port), timeout=5 + ) as raw: + with CONTEXT.wrap_socket( + raw, server_hostname=HOST + ) as connection: + print( + f"PASS: port {port} verified TLS " + f"{connection.version()}" + ) + + for context, hostname, label in ( + ( + ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), + HOST, + "untrusted CA", + ), + ( + CONTEXT, + "wrong.collector.internal", + "wrong hostname", + ), + ): + try: + with socket.create_connection( + (HOST, port), timeout=5 + ) as raw: + with context.wrap_socket( + raw, server_hostname=hostname + ): + pass + except ssl.SSLCertVerificationError: + print(f"PASS: port {port} rejects {label}") + else: + raise AssertionError( + f"Port {port} accepted {label}" + ) + + +def expect_closed(port): + try: + with socket.create_connection( + (HOST, port), timeout=3 + ): + pass + except ConnectionRefusedError: + print(f"PASS: direct port {port} refused") + else: + raise AssertionError( + f"Direct port {port} is accessible" + ) + + +def metric_payload(): + message = ExportMetricsServiceRequest() + + resource = message.resource_metrics.add() + + attribute = resource.resource.attributes.add() + attribute.key = "service.name" + attribute.value.string_value = "lab7-collector-test" + + scope = resource.scope_metrics.add() + scope.scope.name = "security-tests" + + metric = scope.metrics.add() + metric.name = "lab7_collector_security_test" + + point = metric.gauge.data_points.add() + point.time_unix_nano = time.time_ns() + point.as_int = 42 + + return message.SerializeToString() + + +def main(): + for port in (4318, 8888, 8889): + test_tls(port) + + for port in (4317, 18888, 18889): + expect_closed(port) + + payload = make_otlp_payload("loki") + + expect( + "anonymous ingestion denied", + request(4318, "/v1/logs", body=payload)[0], + 401, + ) + + wrong_auth = "Basic " + base64.b64encode( + b"messenger_api:wrong-password" + ).decode() + + expect( + "incorrect password denied", + request( + 4318, "/v1/logs", wrong_auth, payload + )[0], + 401, + ) + + scrape_auth = auth( + "prometheus", "prometheus_scrape_password" + ) + + expect( + "Prometheus cannot ingest telemetry", + request( + 4318, "/v1/logs", scrape_auth, payload + )[0], + 401, + ) + + for role in ("api", "worker", "dispatcher"): + credentials = auth( + f"messenger_{role}", + f"otel_{role}_password", + ) + + for signal, body in ( + ("logs", make_otlp_payload("loki")), + ("traces", make_otlp_payload("tempo")), + ("metrics", metric_payload()), + ): + status, response = request( + 4318, + f"/v1/{signal}", + credentials, + body, + ) + + expect( + f"{role} can export {signal}", + status, + 200, + ) + + api_auth = auth( + "messenger_api", "otel_api_password" + ) + + for port in (8888, 8889): + expect( + f"port {port} anonymous scrape denied", + request(port, "/metrics")[0], + 401, + ) + + expect( + f"port {port} API scrape denied", + request(port, "/metrics", api_auth)[0], + 401, + ) + + expect( + f"port {port} Prometheus scrape allowed", + request(port, "/metrics", scrape_auth)[0], + 200, + ) + + for _ in range(10): + status, body = request( + 8889, "/metrics", scrape_auth + ) + + if ( + status == 200 + and b"lab7_collector_security_test" in body + ): + print("PASS: exported application metric found") + break + + time.sleep(2) + else: + raise AssertionError("Exported metric not found") + + print("\nPASS: COLLECTOR SECURITY TESTS") + + +if __name__ == "__main__": + main() diff --git a/student-tests/test_container_hardening.py b/student-tests/test_container_hardening.py new file mode 100644 index 00000000..6d31de89 --- /dev/null +++ b/student-tests/test_container_hardening.py @@ -0,0 +1,90 @@ +import json +import subprocess + +ids = subprocess.check_output( + ["docker", "compose", "ps", "-a", "-q"], + text=True, +).split() + +assert ids, "No containers" + +containers = json.loads( + subprocess.check_output( + ["docker", "inspect", *ids], + text=True, + ) +) + +expected = { + "api-1", "api-2", "api-1-proxy", "api-2-proxy", + "worker", "dispatcher", "nginx", + "postgres", "redis", "rabbitmq", + "s3", "s3-init", "migrate", "openbao", + "otel-collector", "otel-collector-proxy", + "prometheus", "loki", "loki-proxy", + "tempo", "tempo-proxy", "grafana", +} + +actual = set() + +for container in sorted(containers, key=lambda c: c["Name"]): + name = container["Config"]["Labels"][ + "com.docker.compose.service" + ] + + actual.add(name) + + host = container["HostConfig"] + state = container["State"] + + assert host["PidsLimit"] == 256, name + + assert any( + item in ( + "no-new-privileges:true", + "no-new-privileges=true", + ) + for item in host.get("SecurityOpt") or [] + ), name + + assert not host["Privileged"], name + assert host["NetworkMode"] != "host", name + assert host["PidMode"] != "host", name + assert host["IpcMode"] != "host", name + assert not host["CapAdd"], name + + assert host["Memory"] > 0, name + assert host["NanoCpus"] > 0, name + + for mount in container["Mounts"]: + assert "docker.sock" not in mount["Source"], name + assert "docker.sock" not in mount["Destination"], name + + if name in {"api-1", "api-2", "worker", "dispatcher"}: + assert "ALL" in host["CapDrop"], name + assert container["Config"]["User"] not in ( + "", "0", "root" + ), name + + if name in {"migrate", "s3-init"}: + assert state["Status"] == "exited", name + assert state["ExitCode"] == 0, name + else: + assert state["Running"], name + + if name in { + "api-1", "api-2", "postgres", + "redis", "rabbitmq", "s3", + }: + assert state["Health"]["Status"] == "healthy", name + + print( + f"PASS: {name}, " + f"pids_limit=256, " + f"no-new-privileges=true, " + f"state={state['Status']}" + ) + +assert actual == expected, (expected - actual, actual - expected) + +print(f"\nPASS: ALL {len(actual)} CONTAINERS HARDENED") diff --git a/student-tests/test_data_security.py b/student-tests/test_data_security.py new file mode 100644 index 00000000..02477232 --- /dev/null +++ b/student-tests/test_data_security.py @@ -0,0 +1,190 @@ +import asyncio +import ssl +import socket +from pathlib import Path +from urllib.parse import urlsplit, unquote + +import asyncpg +from redis.asyncio import Redis +from redis.exceptions import NoPermissionError + + +CA_FILE = "/run/ca/ca.crt" +SECRET_DIR = Path("/test-secrets") + + +def read_secret(name): + return (SECRET_DIR / name).read_text().strip() + + +async def expect_failure(label, operation, exceptions): + try: + result = await operation() + + if isinstance(result, asyncpg.Connection): + await result.close() + + except exceptions as exc: + print(f"PASS: {label}: {type(exc).__name__}") + else: + raise AssertionError(f"FAIL: {label}") + + +async def test_postgres(): + print("\n========== POSTGRESQL ==========") + + context = ssl.create_default_context(cafile=CA_FILE) + + for role in ("api", "worker", "dispatcher"): + url = urlsplit(read_secret(f"database_url_{role}")) + + options = { + "host": url.hostname, + "port": url.port, + "user": url.username, + "password": unquote(url.password), + "database": url.path.lstrip("/"), + "timeout": 5, + } + + conn = await asyncpg.connect(**options, ssl=context) + + try: + row = await conn.fetchrow(""" + SELECT current_user, ssl, version + FROM pg_stat_ssl + WHERE pid = pg_backend_pid() + """) + + assert row["ssl"] is True + assert row["current_user"] == f"messenger_{role}" + + print( + f"PASS: {role}: " + f"{row['current_user']}, {row['version']}" + ) + + if role in ("worker", "dispatcher"): + await conn.fetch( + "SELECT id FROM attachments LIMIT 1" + ) + + await expect_failure( + f"{role} cannot read users", + lambda: conn.fetch( + "SELECT * FROM users LIMIT 1" + ), + (asyncpg.InsufficientPrivilegeError,), + ) + + await expect_failure( + f"{role} cannot create tables", + lambda: conn.execute( + "CREATE TABLE security_forbidden(id int)" + ), + (asyncpg.InsufficientPrivilegeError,), + ) + + finally: + await conn.close() + + await expect_failure( + f"{role}: plaintext rejected", + lambda: asyncpg.connect(**options, ssl=False), + (asyncpg.InvalidAuthorizationSpecificationError,), + ) + + await expect_failure( + f"{role}: untrusted CA rejected", + lambda: asyncpg.connect( + **options, + ssl=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), + ), + (ssl.SSLCertVerificationError,), + ) + + wrong_host = dict(options) + wrong_host["host"] = socket.gethostbyname("postgres") + + await expect_failure( + f"{role}: wrong hostname rejected", + lambda: asyncpg.connect( + **wrong_host, ssl=context + ), + (ssl.SSLCertVerificationError,), + ) + + +async def test_redis(): + print("\n========== REDIS ==========") + + url = read_secret("cache_url") + + client = Redis.from_url( + url, + decode_responses=True, + ssl_ca_certs=CA_FILE, + ssl_cert_reqs="required", + ssl_check_hostname=True, + socket_connect_timeout=5, + socket_timeout=5, + ) + + try: + assert await client.ping() + print("PASS: verified Redis TLS") + + await client.set( + "session:security-test", "test", ex=30 + ) + + assert await client.get( + "session:security-test" + ) == "test" + + await client.delete("session:security-test") + + print("PASS: session operations") + + result = await client.eval( + """ + local count = redis.call('INCR', KEYS[1]) + redis.call('EXPIRE', KEYS[1], 30) + return {count, redis.call('TTL', KEYS[1])} + """, + 1, + "rate:login:security-test", + ) + + assert result[0] >= 1 + assert 0 < result[1] <= 30 + + await client.delete("rate:login:security-test") + + print("PASS: rate limiter Lua and TTL") + + await expect_failure( + "forbidden Redis key", + lambda: client.get("forbidden:security-test"), + (NoPermissionError,), + ) + + await expect_failure( + "forbidden Redis admin command", + lambda: client.config_get("port"), + (NoPermissionError,), + ) + + finally: + await client.aclose() + + +async def main(): + await test_postgres() + await test_redis() + + print("\nPASS: DATA SECURITY TESTS") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/student-tests/test_grafana_security.py b/student-tests/test_grafana_security.py new file mode 100644 index 00000000..0cfb8381 --- /dev/null +++ b/student-tests/test_grafana_security.py @@ -0,0 +1,141 @@ +import base64 +import json +import ssl +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError +from urllib.parse import urlencode + +BASE_URL = "https://localhost:3000" + +CONTEXT = ssl.create_default_context( + cafile="certs/ca/ca.crt" +) + +password = None + +for line in Path(".env").read_text().splitlines(): + if line.startswith("GRAFANA_ADMIN_PASSWORD="): + password = line.split("=", 1)[1].strip() + password = password.strip("\"'") + +assert password, "Grafana admin password not configured" + +authorization = "Basic " + base64.b64encode( + f"admin:{password}".encode() +).decode() + + +def request(path, authenticated=True): + headers = {} + + if authenticated: + headers["Authorization"] = authorization + + req = Request( + BASE_URL + path, + headers=headers, + ) + + try: + with urlopen( + req, context=CONTEXT, timeout=20 + ) as response: + return response.status, json.loads(response.read()) + except HTTPError as exc: + body = exc.read().decode(errors="replace") + + print(f"HTTP {exc.code}: {path}") + print(f"Response: {body}") + + try: + return exc.code, json.loads(body) + except json.JSONDecodeError: + return exc.code, {"message": body} + + +status, body = request( + "/api/health", authenticated=False +) + +assert status == 200 +assert body["database"] == "ok" + +print("PASS: Grafana HTTPS health") + +status, _ = request( + "/api/datasources", authenticated=False +) + +assert status == 401, status + +print("PASS: anonymous datasource access denied") + +status, datasources = request("/api/datasources") + +assert status == 200 + +expected = { + "prometheus": "https://prometheus:9090", + "loki": "https://loki:3100", + "tempo": "https://tempo:3200", +} + +actual = { + item["uid"]: item + for item in datasources +} + +for uid, url in expected.items(): + item = actual[uid] + + assert item["url"] == url + assert item["basicAuth"] is True + + settings = item["jsonData"] + + assert settings.get("tlsAuthWithCACert") is True + assert not settings.get("tlsSkipVerify", False) + + print(f"PASS: {uid} HTTPS and CA verification configured") + + if uid == "tempo": + query = urlencode({ + "q": '{ resource.service.name = "lab7-security-test" }', + "limit": 20, + }) + + status, result = request( + f"/api/datasources/proxy/uid/{uid}/api/search?{query}" + ) + + assert status == 200, ( + f"Tempo query failed: HTTP {status}" + ) + + traces = result.get("traces", []) + + assert traces, "Expected test traces not found" + + print(f"PASS: Tempo returned {len(traces)} traces") + print(f"PASS: trace ID: {traces[0]['traceID']}") + print("PASS: Grafana -> tempo connection") + + continue + + status, result = request( + f"/api/datasources/uid/{uid}/health" + ) + + print( + f"Datasource {uid}: HTTP {status}, " + f"status={result.get('status')}, " + f"message={result.get('message')}" + ) + + assert status == 200, uid + assert result.get("status", "").lower() == "ok", uid + + print(f"PASS: Grafana -> {uid} connection") + +print("\nPASS: GRAFANA SECURITY TESTS") diff --git a/student-tests/test_minio_security.py b/student-tests/test_minio_security.py new file mode 100644 index 00000000..dfe95297 --- /dev/null +++ b/student-tests/test_minio_security.py @@ -0,0 +1,280 @@ +import socket +import ssl +import uuid +from pathlib import Path +from urllib.request import urlopen +from urllib.error import HTTPError + +import boto3 +from botocore.config import Config +from botocore.exceptions import ClientError + +CA_FILE = "/run/ca/ca.crt" +SECRET_DIR = Path("/test-secrets") + +HOST = "s3" +PORT = 9000 +BUCKET = "messenger-attachments" + +TEST_ID = f"security-test-{uuid.uuid4().hex}" + +STAGING = f"staging/{TEST_ID}/test.jpg" +ORIGINAL = f"attachments/{TEST_ID}/g1/original" +VARIANT = f"variants/{TEST_ID}/g1/thumbnail.jpg" + +BODY = b"lab7-minio-security-test" + + +def read_secret(name): + return (SECRET_DIR / name).read_text().strip() + + +def client(role): + return boto3.client( + "s3", + endpoint_url=f"https://{HOST}:{PORT}", + region_name="us-east-1", + aws_access_key_id=read_secret( + f"s3_{role}_access_key_id" + ), + aws_secret_access_key=read_secret( + f"s3_{role}_secret_access_key" + ), + verify=CA_FILE, + config=Config( + signature_version="s3v4", + connect_timeout=5, + read_timeout=5, + retries={"total_max_attempts": 1}, + s3={"addressing_style": "path"}, + ), + ) + + +def put(s3, key): + s3.put_object( + Bucket=BUCKET, + Key=key, + Body=BODY, + ) + + +def get(s3, key): + response = s3.get_object( + Bucket=BUCKET, + Key=key, + ) + + with response["Body"] as stream: + return stream.read() + + +def delete(s3, key): + s3.delete_object( + Bucket=BUCKET, + Key=key, + ) + + +def expect_denied(label, operation): + try: + operation() + except ClientError as exc: + status = exc.response[ + "ResponseMetadata" + ]["HTTPStatusCode"] + + assert status == 403, status + print(f"PASS: {label}: HTTP 403") + else: + raise AssertionError(f"FAIL: {label}") + + +def expect_tls_failure(context, hostname, label): + try: + with socket.create_connection( + (HOST, PORT), + timeout=5, + ) as raw: + with context.wrap_socket( + raw, + server_hostname=hostname, + ): + pass + except ssl.SSLCertVerificationError: + print(f"PASS: {label}") + else: + raise AssertionError(f"FAIL: {label}") + + +def test_tls(): + trusted = ssl.create_default_context( + cafile=CA_FILE + ) + + with socket.create_connection( + (HOST, PORT), + timeout=5, + ) as raw: + with trusted.wrap_socket( + raw, + server_hostname=HOST, + ) as connection: + print( + "PASS: verified MinIO TLS:", + connection.version(), + ) + + expect_tls_failure( + ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), + HOST, + "untrusted CA rejected", + ) + + expect_tls_failure( + trusted, + "wrong.s3.internal", + "wrong hostname rejected", + ) + + +def test_anonymous(): + context = ssl.create_default_context( + cafile=CA_FILE + ) + + for path in (BUCKET, f"{BUCKET}/{ORIGINAL}"): + try: + with urlopen( + f"https://{HOST}:{PORT}/{path}", + context=context, + timeout=5, + ): + pass + except HTTPError as exc: + assert exc.code == 403, exc.code + print("PASS: anonymous access denied") + else: + raise AssertionError( + "FAIL: anonymous access allowed" + ) + + +def test_permissions(): + api = client("api") + worker = client("worker") + + api.head_bucket(Bucket=BUCKET) + print("PASS: API can access bucket") + + put(api, STAGING) + print("PASS: API can write staging") + + assert get(api, STAGING) == BODY + print("PASS: API can read staging") + + assert get(worker, STAGING) == BODY + print("PASS: worker can read staging") + + put(worker, ORIGINAL) + print("PASS: worker can write attachments") + + put(worker, VARIANT) + print("PASS: worker can write variants") + + assert get(api, ORIGINAL) == BODY + print("PASS: API can read attachments") + + assert get(api, VARIANT) == BODY + print("PASS: API can read variants") + + expect_denied( + "API cannot write attachments", + lambda: put(api, ORIGINAL), + ) + + expect_denied( + "API cannot write variants", + lambda: put(api, VARIANT), + ) + + expect_denied( + "worker cannot write staging", + lambda: put(worker, STAGING), + ) + + expect_denied( + "worker cannot delete staging", + lambda: delete(worker, STAGING), + ) + + expect_denied( + "worker cannot read attachments", + lambda: get(worker, ORIGINAL), + ) + + expect_denied( + "worker cannot read variants", + lambda: get(worker, VARIANT), + ) + + for role, s3 in ( + ("API", api), + ("worker", worker), + ): + for key in (ORIGINAL, VARIANT): + expect_denied( + f"{role} cannot delete final object", + lambda: delete(s3, key), + ) + + expect_denied( + f"{role} cannot create bucket", + lambda: s3.create_bucket( + Bucket=TEST_ID, + ), + ) + + try: + response = s3.list_buckets() + except ClientError as exc: + status = exc.response[ + "ResponseMetadata" + ]["HTTPStatusCode"] + + assert status == 403, status + print(f"PASS: {role} bucket listing denied") + else: + names = { + item["Name"] + for item in response.get("Buckets", []) + } + + allowed = {BUCKET} if role == "API" else set() + + assert names <= allowed, ( + f"{role} unexpected buckets: {names}" + ) + + print( + f"PASS: {role} bucket listing restricted: " + f"{sorted(names)}" + ) + + delete(api, STAGING) + print("PASS: API can delete staging") + + test_anonymous() + + print(f"TEST_PREFIX={TEST_ID}") + + +def main(): + test_tls() + test_permissions() + + print("\nPASS: MINIO SECURITY TESTS") + + +if __name__ == "__main__": + main() diff --git a/student-tests/test_mtls.py b/student-tests/test_mtls.py new file mode 100644 index 00000000..13318c8b --- /dev/null +++ b/student-tests/test_mtls.py @@ -0,0 +1,70 @@ +import http.client +import ssl +import socket + +CA = "/test-certs/ca.crt" + + +def probe(host, identity=None): + context = ssl.create_default_context(cafile=CA) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + + if identity: + context.load_cert_chain( + f"/test-certs/{identity}/tls.crt", + f"/test-certs/{identity}/tls.key", + ) + + with socket.create_connection( + (host, 8443), timeout=5 + ) as raw: + with context.wrap_socket( + raw, server_hostname=host + ) as tls: + tls.sendall( + b"GET /health/ready HTTP/1.1\r\n" + b"Host: api.internal\r\n" + b"Connection: close\r\n\r\n" + ) + + response = http.client.HTTPResponse(tls) + response.begin() + response.read() + + return response.status + + +for host in ("api-1", "api-2"): + print(f"\n=== {host} ===") + + status = probe(host, "lb-client") + assert status == 200, status + + print("PASS: authorized LB certificate") + + for identity, label in ( + (None, "missing client certificate"), + ("foreign", "untrusted client certificate"), + ("unauthorized-client", "wrong trusted identity"), + ): + try: + status = probe(host, identity) + except ssl.SSLError as exc: + print(f"PASS: {label}: {type(exc).__name__}") + else: + assert status in (400, 403, 495, 496), ( + label, status + ) + print(f"PASS: {label}: HTTP {status}") + + try: + with socket.create_connection( + (host, 8080), timeout=3 + ): + pass + except ConnectionRefusedError: + print("PASS: direct HTTP bypass rejected") + else: + raise AssertionError("Direct HTTP port accessible") + +print("\nPASS: ALL MTLS SECURITY TESTS") diff --git a/student-tests/test_openbao_security.py b/student-tests/test_openbao_security.py new file mode 100644 index 00000000..b62f92dc --- /dev/null +++ b/student-tests/test_openbao_security.py @@ -0,0 +1,167 @@ +import json +import ssl +import sys +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +BASE_URL = "https://openbao:8200/v1" + +identity = sys.argv[1] +role = sys.argv[2] + +context = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +context.load_cert_chain( + certfile="/run/bao-client/tls.crt", + keyfile="/run/bao-client/tls.key", +) + + +def request(path, method="GET", data=None, token=None): + headers = {"Content-Type": "application/json"} + + if token: + headers["X-Vault-Token"] = token + + body = json.dumps(data).encode() if data is not None else None + + req = Request( + BASE_URL + path, + headers=headers, + data=body, + method=method, + ) + + try: + with urlopen( + req, context=context, timeout=10 + ) as response: + raw = response.read() + return response.status, json.loads(raw) if raw else {} + except HTTPError as exc: + return exc.code, {} + + +status, result = request( + "/auth/cert/login", + "POST", + {"name": identity}, +) + +assert status == 200, f"Cert login failed: HTTP {status}" + +auth = result["auth"] +token = auth["client_token"] + +assert 0 < auth["lease_duration"] <= 900 + +assert set(auth["policies"]) == { + f"messenger-{role}" +} + +print(f"PASS: {identity} certificate login") +print(f"PASS: token TTL={auth['lease_duration']} seconds") +print(f"PASS: scoped policy messenger-{role}") + +status, result = request( + f"/secret/data/messenger/{role}", + token=token, +) + +assert status == 200 + +expected = { + "api": { + "database_url", + "cache_url", + "s3_access_key_id", + "s3_secret_access_key", + "otel_password", + }, + "worker": { + "database_url", + "s3_access_key_id", + "s3_secret_access_key", + "rabbitmq_password", + "otel_password", + }, + "dispatcher": { + "database_url", + "rabbitmq_password", + "otel_password", + }, +} + +values = result["data"]["data"] + +assert set(values) == expected[role] +assert all(values.values()) + +print(f"PASS: own secrets readable ({len(values)})") + +for other in expected: + if other == role: + continue + + status, _ = request( + f"/secret/data/messenger/{other}", + token=token, + ) + + assert status == 403, (other, status) + + print(f"PASS: access to {other} denied") + +status, _ = request( + "/sys/policies/acl/messenger-api", + token=token, +) + +assert status == 403 + +print("PASS: administrative policy access denied") + +status, _ = request( + "/sys/policies/acl/security-test", + "PUT", + {"policy": ""}, + token=token, +) + +assert status == 403 + +print("PASS: policy modification denied") + +status, _ = request( + f"/secret/data/messenger/{role}", +) + +assert status == 403 + +print("PASS: unauthenticated secret access denied") + +for other_identity in ( + "bao-api-1", + "bao-api-2", + "bao-worker", + "bao-dispatcher", +): + if other_identity == identity: + continue + + status, _ = request( + "/auth/cert/login", + "POST", + {"name": other_identity}, + ) + + assert status in (400, 403), ( + other_identity, + status, + ) + + print(f"PASS: impersonation of {other_identity} denied") + +print(f"PASS: OPENBAO SECURITY TESTS: {identity}") diff --git a/student-tests/test_openbao_tls.py b/student-tests/test_openbao_tls.py new file mode 100644 index 00000000..66ef2c32 --- /dev/null +++ b/student-tests/test_openbao_tls.py @@ -0,0 +1,134 @@ +import json +import socket +import ssl +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +BASE = "https://openbao:8200/v1" + +ca = "/run/ca/ca.crt" + +trusted = ssl.create_default_context(cafile=ca) + +untrusted = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + + +def request(context, path, method="GET", data=None, token=None): + headers = {"Content-Type": "application/json"} + + if token: + headers["X-Vault-Token"] = token + + req = Request( + BASE + path, + data=json.dumps(data).encode() if data is not None else None, + headers=headers, + method=method, + ) + + try: + with urlopen(req, context=context, timeout=10) as response: + raw = response.read() + return response.status, json.loads(raw) if raw else {} + except HTTPError as exc: + return exc.code, {} + + +def handshake(context, hostname): + with socket.create_connection(("openbao", 8200), timeout=5) as sock: + with context.wrap_socket(sock, server_hostname=hostname) as tls: + return tls.version() + + +version = handshake(trusted, "openbao") + +assert version in {"TLSv1.2", "TLSv1.3"} + +print(f"PASS: trusted CA and hostname, {version}") + +for context, hostname, label in ( + (untrusted, "openbao", "untrusted CA"), + (trusted, "wrong-hostname", "wrong hostname"), +): + try: + handshake(context, hostname) + except ssl.SSLCertVerificationError: + print(f"PASS: {label} rejected") + else: + raise AssertionError(f"{label} accepted") + + +status, _ = request( + trusted, + "/auth/cert/login", + "POST", + {"name": "bao-api-1"}, +) + +assert status in (400, 403), status + +print("PASS: certificate login without client certificate denied") + +trusted.load_cert_chain( + "/run/bao-client/tls.crt", + "/run/bao-client/tls.key", +) + +status, result = request( + trusted, + "/auth/cert/login", + "POST", + {"name": "bao-api-1"}, +) + +assert status == 200 + +token = result["auth"]["client_token"] + +status, result = request( + trusted, + "/secret/data/messenger/api", + token=token, +) + +assert status == 200 + +values = result["data"]["data"] + +version_before = result["data"]["metadata"]["version"] + +status, _ = request( + trusted, + "/secret/data/messenger/api", + "POST", + {"data": values}, + token, +) + +assert status == 403 + +print("PASS: modification of own secrets denied") + +status, _ = request( + trusted, + "/secret/data/messenger/api", + "DELETE", + token=token, +) + +assert status == 403 + +print("PASS: deletion of own secrets denied") + +status, result = request( + trusted, + "/secret/data/messenger/api", + token=token, +) + +assert status == 200 +assert result["data"]["data"] == values +assert result["data"]["metadata"]["version"] == version_before + +print("PASS: secrets unchanged") +print("PASS: ALL OPENBAO TLS AND WRITE RESTRICTION TESTS") diff --git a/student-tests/test_prometheus_security.py b/student-tests/test_prometheus_security.py new file mode 100644 index 00000000..d2fd20d4 --- /dev/null +++ b/student-tests/test_prometheus_security.py @@ -0,0 +1,177 @@ +import base64 +import json +import socket +import ssl +import time +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +HOST = "prometheus" +PORT = 9090 + +CONTEXT = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +SECRET_DIR = Path("/test-secrets") + + +def auth(username, filename): + password = (SECRET_DIR / filename).read_text().strip() + + encoded = base64.b64encode( + f"{username}:{password}".encode() + ).decode() + + return f"Basic {encoded}" + + +def request(path, authorization=None): + headers = {} + + if authorization: + headers["Authorization"] = authorization + + req = Request( + f"https://{HOST}:{PORT}{path}", + headers=headers, + ) + + try: + with urlopen( + req, context=CONTEXT, timeout=10 + ) as response: + return response.status, response.read() + except HTTPError as exc: + return exc.code, exc.read() + + +def expect(label, actual, expected): + assert actual == expected, ( + f"{label}: expected {expected}, got {actual}" + ) + + print(f"PASS: {label}: {actual}") + + +with socket.create_connection( + (HOST, PORT), timeout=5 +) as raw: + with CONTEXT.wrap_socket( + raw, server_hostname=HOST + ) as connection: + print( + "PASS: Prometheus verified TLS", + connection.version(), + ) + +for context, hostname, label in ( + ( + ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), + HOST, + "untrusted CA", + ), + ( + CONTEXT, + "wrong.prometheus.internal", + "wrong hostname", + ), +): + try: + with socket.create_connection( + (HOST, PORT), timeout=5 + ) as raw: + with context.wrap_socket( + raw, server_hostname=hostname + ): + pass + except ssl.SSLCertVerificationError: + print(f"PASS: Prometheus rejects {label}") + else: + raise AssertionError(f"Accepted {label}") + + +grafana = auth( + "grafana", "grafana_datasource_password" +) + +prometheus = auth( + "prometheus", "prometheus_scrape_password" +) + +api = auth( + "messenger_api", "otel_api_password" +) + +expect( + "anonymous access denied", + request("/api/v1/targets")[0], + 401, +) + +expect( + "API credentials denied", + request("/api/v1/targets", api)[0], + 401, +) + +expect( + "Grafana query allowed", + request("/api/v1/query?query=up", grafana)[0], + 200, +) + +expect( + "Prometheus self-scrape allowed", + request("/metrics", prometheus)[0], + 200, +) + +expected_jobs = { + "otel-collector", + "otel-collector-internal", + "prometheus", +} + +for _ in range(15): + status, body = request( + "/api/v1/targets", grafana + ) + + assert status == 200 + + targets = json.loads(body)["data"]["activeTargets"] + + actual_jobs = { + target["labels"]["job"] + for target in targets + } + + assert actual_jobs == expected_jobs + + if all( + target["health"] == "up" + and target["scrapeUrl"].startswith("https://") + for target in targets + ): + for target in targets: + print( + "PASS: target UP:", + target["labels"]["job"], + target["scrapeUrl"], + ) + break + + time.sleep(3) +else: + for target in targets: + print( + target["labels"]["job"], + target["health"], + target["lastError"], + ) + + raise AssertionError("HTTPS scrape targets not ready") + +print("\nPASS: PROMETHEUS SECURITY TESTS") diff --git a/student-tests/test_public_tls.py b/student-tests/test_public_tls.py new file mode 100644 index 00000000..54a605cf --- /dev/null +++ b/student-tests/test_public_tls.py @@ -0,0 +1,36 @@ +import socket +import ssl +from pathlib import Path + + +ca = Path("certs/ca/ca.crt").resolve() + +trusted = ssl.create_default_context(cafile=str(ca)) + +untrusted = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + + +def connect(context, hostname): + with socket.create_connection( + ("127.0.0.1", 8443), timeout=5 + ) as sock: + with context.wrap_socket( + sock, server_hostname=hostname + ) as tls: + return tls.version() + + +print("PASS: trusted CA and hostname:", connect(trusted, "localhost")) + +for label, context, hostname in ( + ("wrong hostname", trusted, "wrong-host.invalid"), + ("empty trust store", untrusted, "localhost"), +): + try: + connect(context, hostname) + except ssl.SSLCertVerificationError as error: + print(f"PASS: {label}: {error.verify_message}") + else: + raise AssertionError(f"Unexpected TLS success: {label}") + +print("PASS: public TLS verification") diff --git a/student-tests/test_rabbitmq_security.py b/student-tests/test_rabbitmq_security.py new file mode 100644 index 00000000..8091a6ce --- /dev/null +++ b/student-tests/test_rabbitmq_security.py @@ -0,0 +1,234 @@ +import socket +import ssl +import uuid +from pathlib import Path + +import pika + +CA_FILE = "/run/ca/ca.crt" +SECRET_DIR = Path("/test-secrets") + +HOST = "rabbitmq" +PORT = 5671 +VHOST = "messenger" + +QUEUE = "attachment.process.v1" +DLQ = "attachment.failed.v1" + + +def connect(role): + password = ( + SECRET_DIR / f"rabbitmq_{role}_password" + ).read_text().strip() + + context = ssl.create_default_context(cafile=CA_FILE) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + + return pika.BlockingConnection( + pika.ConnectionParameters( + host=HOST, + port=PORT, + virtual_host=VHOST, + credentials=pika.PlainCredentials( + f"messenger_{role}", + password, + ), + ssl_options=pika.SSLOptions(context, HOST), + connection_attempts=1, + socket_timeout=5, + stack_timeout=10, + ) + ) + + +def expect_denied(role, label, operation): + connection = connect(role) + + try: + channel = connection.channel() + + try: + operation(channel) + except pika.exceptions.ChannelClosedByBroker as exc: + assert exc.reply_code == 403, exc.reply_code + print(f"PASS: {label}: ACCESS_REFUSED") + else: + raise AssertionError(f"FAIL: {label}") + + finally: + if connection.is_open: + connection.close() + + +def test_delivery(): + payload = f"security-test-{uuid.uuid4()}".encode() + + producer = connect("producer") + + try: + print("PASS: producer authenticated over AMQPS") + + channel = producer.channel() + channel.confirm_delivery() + + channel.basic_publish( + exchange="", + routing_key=QUEUE, + body=payload, + mandatory=True, + ) + + print("PASS: producer published message") + + finally: + producer.close() + + consumer = connect("consumer") + + try: + print("PASS: consumer authenticated over AMQPS") + + channel = consumer.channel() + + method, properties, body = channel.basic_get( + queue=QUEUE, + auto_ack=False, + ) + + assert method is not None, "Queue is empty" + + if body != payload: + channel.basic_nack( + method.delivery_tag, + requeue=True, + ) + raise AssertionError("Unexpected queue message") + + channel.basic_ack(method.delivery_tag) + + print("PASS: consumer received and acknowledged message") + + finally: + consumer.close() + + +def forbidden_publish(channel): + channel.confirm_delivery() + + channel.basic_publish( + exchange="", + routing_key=QUEUE, + body=b"forbidden", + mandatory=True, + ) + + +def test_permissions(): + expect_denied( + "producer", + "producer cannot consume", + lambda ch: ch.basic_get(queue=QUEUE), + ) + + expect_denied( + "consumer", + "consumer cannot publish", + forbidden_publish, + ) + + expect_denied( + "consumer", + "consumer cannot create queues", + lambda ch: ch.queue_declare( + queue="security.forbidden", + durable=False, + ), + ) + + expect_denied( + "consumer", + "consumer cannot read DLQ", + lambda ch: ch.basic_get(queue=DLQ), + ) + + expect_denied( + "producer", + "producer cannot create queues", + lambda ch: ch.queue_declare( + queue="security.forbidden", + durable=False, + ), + ) + + +def expect_tls_failure(context, hostname, label): + try: + with socket.create_connection( + (HOST, PORT), + timeout=5, + ) as raw: + with context.wrap_socket( + raw, + server_hostname=hostname, + ): + pass + + except ssl.SSLCertVerificationError: + print(f"PASS: {label}") + + else: + raise AssertionError(f"FAIL: {label}") + + +def test_tls(): + trusted = ssl.create_default_context(cafile=CA_FILE) + + with socket.create_connection( + (HOST, PORT), + timeout=5, + ) as raw: + with trusted.wrap_socket( + raw, + server_hostname=HOST, + ) as connection: + print( + "PASS: verified RabbitMQ TLS:", + connection.version(), + ) + + expect_tls_failure( + ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), + HOST, + "untrusted CA rejected", + ) + + expect_tls_failure( + trusted, + "wrong.rabbitmq.internal", + "wrong hostname rejected", + ) + + try: + with socket.create_connection( + (HOST, 5672), + timeout=5, + ): + pass + + except ConnectionRefusedError: + print("PASS: plaintext AMQP listener disabled") + + else: + raise AssertionError("FAIL: plaintext AMQP port open") + + +def main(): + test_tls() + test_delivery() + test_permissions() + + print("\nPASS: RABBITMQ SECURITY TESTS") + + +if __name__ == "__main__": + main() diff --git a/student-tests/test_rate_limit.py b/student-tests/test_rate_limit.py new file mode 100644 index 00000000..9cf6affd --- /dev/null +++ b/student-tests/test_rate_limit.py @@ -0,0 +1,97 @@ +import base64 +import json +import ssl +import time +import uuid + +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +BASE = "https://localhost:8443" + +context = ssl.create_default_context( + cafile=str(Path("certs/ca/ca.crt").resolve()) +) + +username = "ratetest" + uuid.uuid4().hex[:12] +password = "Lab7-Invalid-Password-2026!" + +instances = set() + + +def login(name): + credentials = base64.b64encode( + f"{name}:{password}".encode() + ).decode() + + request = Request( + BASE + "/api/v1/auth/sessions", + method="POST", + headers={ + "Authorization": f"Basic {credentials}" + }, + ) + + try: + with urlopen( + request, context=context, timeout=10 + ) as response: + return ( + response.status, + response.headers, + response.read(), + ) + except HTTPError as exc: + return exc.code, exc.headers, exc.read() + + +print("Testing username rate limit") + +for attempt in range(1, 7): + status, headers, body = login(username) + + instance = headers.get("X-Instance-Id") + + if instance: + instances.add(instance) + + print( + f"Attempt {attempt}: " + f"HTTP {status}, instance={instance}" + ) + + if attempt <= 5: + assert status == 401, (attempt, status) + else: + assert status == 429, (attempt, status) + + retry_after = int(headers["Retry-After"]) + + assert 1 <= retry_after <= 60 + + print("Retry-After:", retry_after) + print("Error response:", json.loads(body)) + +assert len(instances) >= 2, instances + +print("PASS: shared rate limit across both API replicas") + +other_username = "ratetest" + uuid.uuid4().hex[:12] + +status, _, _ = login(other_username) + +assert status == 401, status + +print("PASS: independent username counters") + +print("Waiting for rate limit expiration...") + +time.sleep(retry_after + 2) + +status, _, _ = login(username) + +assert status == 401, status + +print("PASS: rate limit expires") +print("PASS: USERNAME RATE LIMIT") diff --git a/student-tests/test_rate_limit_ip.py b/student-tests/test_rate_limit_ip.py new file mode 100644 index 00000000..5d10ec3e --- /dev/null +++ b/student-tests/test_rate_limit_ip.py @@ -0,0 +1,98 @@ +import base64 +import json +import ssl +import time +import uuid + +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +context = ssl.create_default_context( + cafile=str(Path("certs/ca/ca.crt").resolve()) +) + +BASE = "https://localhost:8443" + +instances = set() +started = time.monotonic() + + +def login(attempt): + username = "iptest" + uuid.uuid4().hex[:12] + + credentials = base64.b64encode( + f"{username}:Lab7-Invalid-Password!".encode() + ).decode() + + request = Request( + BASE + "/api/v1/auth/sessions", + method="POST", + headers={ + "Authorization": f"Basic {credentials}", + "X-Forwarded-For": f"192.0.2.{attempt}", + }, + ) + + try: + with urlopen( + request, context=context, timeout=10 + ) as response: + return ( + response.status, + response.headers, + response.read(), + ) + except HTTPError as exc: + return exc.code, exc.headers, exc.read() + + +for attempt in range(1, 62): + status, headers, body = login(attempt) + + instance = headers.get("X-Instance-Id") + + if instance: + instances.add(instance) + + expected = 401 if attempt <= 60 else 429 + + print( + f"Attempt {attempt}: " + f"HTTP {status}, instance={instance}" + ) + + assert status == expected, ( + attempt, status, expected + ) + + if attempt == 61: + retry_after = int(headers["Retry-After"]) + assert 1 <= retry_after <= 60 + + error = json.loads(body) + assert error["error"]["code"] == "rate_limited" + + print("Retry-After:", retry_after) + print("Error response:", error) + +elapsed = time.monotonic() - started + +assert elapsed < 60, elapsed +assert instances == {"api-1", "api-2"}, instances + +print(f"Elapsed: {elapsed:.2f} seconds") + +print("PASS: IP rate limit") +print("PASS: shared IP counter across API replicas") +print("PASS: spoofed X-Forwarded-For cannot bypass limit") + +print("Waiting for rate limit expiration...") + +time.sleep(retry_after + 2) + +status, _, _ = login(62) +assert status == 401, status + +print("PASS: IP rate limit expires") +print("PASS: ALL IP RATE LIMIT TESTS") diff --git a/student-tests/test_session_expiry.py b/student-tests/test_session_expiry.py new file mode 100644 index 00000000..5d9c0dbc --- /dev/null +++ b/student-tests/test_session_expiry.py @@ -0,0 +1,111 @@ +import json +import subprocess +import ssl +import sys +import time +import uuid + +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +sys.path.insert(0, "tests") + +from client import Client + +BASE = "https://localhost:8443" +CA = str(Path("certs/ca/ca.crt").resolve()) + +context = ssl.create_default_context(cafile=CA) + +c = Client(BASE, CA) +alice, bob, eve, chat = c.bootstrap() + + +def check_token(token, expected): + request = Request( + BASE + "/api/v1/users/me", + headers={"Authorization": f"Bearer {token}"}, + ) + + try: + with urlopen( + request, context=context, timeout=10 + ) as response: + status = response.status + headers = response.headers + body = json.loads(response.read()) + except HTTPError as exc: + status = exc.code + headers = exc.headers + body = json.loads(exc.read()) + + assert status == expected, (status, expected) + + if expected == 401: + assert body["error"]["code"] == "unauthorized" + assert headers["WWW-Authenticate"].startswith("Bearer") + + return body + + +check_token(uuid.uuid4().hex, 401) + +print("PASS: unknown Bearer token rejected") + +code = """ +import asyncio +import json +import sys + +from uuid import UUID +from src.sessions import create_session, redis_client + + +async def main(): + token, ttl = await create_session(UUID(sys.argv[1])) + + actual_ttl = await redis_client.ttl(f"session:{token}") + + print(json.dumps({ + "token": token, + "ttl": ttl, + "redis_ttl": actual_ttl, + })) + + await redis_client.aclose() + + +asyncio.run(main()) +""" + +result = subprocess.check_output( + [ + "docker", "compose", "exec", "-T", + "-e", "SESSION_TTL_SECONDS=10", + "api-1", "python", "-c", code, + alice["id"], + ], + text=True, +) + +session = json.loads(result) + +assert session["ttl"] == 10 +assert 1 <= session["redis_ttl"] <= 10 + +print("PASS: Redis session TTL configured") +print("Session TTL:", session["redis_ttl"]) + +me = check_token(session["token"], 200) + +assert me["id"] == alice["id"] + +print("PASS: session accepted before expiry") + +time.sleep(12) + +check_token(session["token"], 401) + +print("PASS: expired session rejected") +print("PASS: ALL SESSION EXPIRY TESTS") diff --git a/student-tests/test_telemetry_backends.py b/student-tests/test_telemetry_backends.py new file mode 100644 index 00000000..08918ef4 --- /dev/null +++ b/student-tests/test_telemetry_backends.py @@ -0,0 +1,269 @@ +import uuid +from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest +from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest + +import base64 +import socket +import ssl +import time +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +CA_FILE = "/run/ca/ca.crt" +SECRET_DIR = Path("/test-secrets") + +CONTEXT = ssl.create_default_context(cafile=CA_FILE) + + +def credentials(username, filename): + password = (SECRET_DIR / filename).read_text().strip() + + encoded = base64.b64encode( + f"{username}:{password}".encode() + ).decode() + + return f"Basic {encoded}" + + + + + +def request(url, authorization=None, method="GET", body=None): + headers = {} + + if authorization: + headers["Authorization"] = authorization + + if body is not None: + headers["Content-Type"] = "application/x-protobuf" + + req = Request( + url, + headers=headers, + method=method, + data=body, + ) + + try: + with urlopen( + req, + context=CONTEXT, + timeout=5, + ) as response: + return response.status + except HTTPError as exc: + if exc.code not in (401, 403, 503): + print( + f"HTTP {exc.code}: " + f"{exc.read(2048).decode(errors='replace')}" + ) + + return exc.code + + +def expect(label, actual, expected): + assert actual == expected, ( + f"{label}: expected {expected}, got {actual}" + ) + + print(f"PASS: {label}: {actual}") + + +def test_tls(host, port): + with socket.create_connection( + (host, port), timeout=5 + ) as raw: + with CONTEXT.wrap_socket( + raw, server_hostname=host + ) as connection: + print( + f"PASS: {host} verified TLS " + f"{connection.version()}" + ) + + for context, hostname, label in ( + ( + ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), + host, + "untrusted CA", + ), + ( + CONTEXT, + "wrong.telemetry.internal", + "wrong hostname", + ), + ): + try: + with socket.create_connection( + (host, port), timeout=5 + ) as raw: + with context.wrap_socket( + raw, server_hostname=hostname + ): + pass + except ssl.SSLCertVerificationError: + print(f"PASS: {host} rejects {label}") + else: + raise AssertionError( + f"{host}: {label} accepted" + ) + + +def expect_closed(host, port): + try: + with socket.create_connection( + (host, port), timeout=3 + ): + pass + except ConnectionRefusedError: + print(f"PASS: {host}:{port} direct access refused") + else: + raise AssertionError( + f"{host}:{port} is accessible" + ) + + +def make_otlp_payload(host): + now = time.time_ns() + + if host == "loki": + message = ExportLogsServiceRequest() + + resource_logs = message.resource_logs.add() + + attribute = resource_logs.resource.attributes.add() + attribute.key = "service.name" + attribute.value.string_value = "lab7-security-test" + + scope_logs = resource_logs.scope_logs.add() + scope_logs.scope.name = "security-tests" + + record = scope_logs.log_records.add() + record.time_unix_nano = now + record.observed_time_unix_nano = now + record.severity_number = 9 + record.severity_text = "INFO" + record.body.string_value = "Lab7 TLS security test" + + elif host == "tempo": + message = ExportTraceServiceRequest() + + resource_spans = message.resource_spans.add() + + attribute = resource_spans.resource.attributes.add() + attribute.key = "service.name" + attribute.value.string_value = "lab7-security-test" + + scope_spans = resource_spans.scope_spans.add() + scope_spans.scope.name = "security-tests" + + span = scope_spans.spans.add() + span.trace_id = uuid.uuid4().bytes + span.span_id = uuid.uuid4().bytes[:8] + span.name = "lab7-security-test" + span.kind = 1 + span.start_time_unix_nano = now - 1000000 + span.end_time_unix_nano = now + + else: + raise ValueError(host) + + return message.SerializeToString() + + +def test_backend(host, port, internal_ports, ingest): + base = f"https://{host}:{port}" + + test_tls(host, port) + + for _ in range(30): + if request(base + "/ready", GRAFANA) == 200: + break + + time.sleep(2) + else: + raise AssertionError(f"{host} not ready") + + expect( + f"{host} authenticated readiness", + request(base + "/ready", GRAFANA), + 200, + ) + + expect( + f"{host} anonymous query denied", + request(base + "/ready"), + 401, + ) + + expect( + f"{host} collector query denied", + request(base + "/ready", COLLECTOR), + 401, + ) + + expect( + f"{host} anonymous ingestion denied", + request(base + ingest, method="POST", body=make_otlp_payload(host)), + 401, + ) + + expect( + f"{host} Grafana ingestion denied", + request( + base + ingest, + GRAFANA, + method="POST", + body=make_otlp_payload(host), + ), + 401, + ) + + expect( + f"{host} collector ingestion allowed", + request( + base + ingest, + COLLECTOR, + method="POST", + body=make_otlp_payload(host), + ), + 204 if host == "loki" else 200, + ) + + expect( + f"{host} administrative endpoint denied", + request(base + "/config", GRAFANA), + 403, + ) + + for internal_port in internal_ports: + expect_closed(host, internal_port) + + +def main(): + global COLLECTOR, GRAFANA + + COLLECTOR = credentials( + "collector", "otel_backend_password" + ) + + GRAFANA = credentials( + "grafana", "grafana_datasource_password" + ) + + test_backend( + "loki", 3100, [13100, 9095], + "/otlp/v1/logs", + ) + + test_backend( + "tempo", 3200, [13200, 14318, 4317, 4318, 9095], + "/v1/traces", + ) + + print("\nPASS: TELEMETRY BACKEND SECURITY TESTS") + + +if __name__ == "__main__": + main() diff --git a/student-tests/test_telemetry_queries.py b/student-tests/test_telemetry_queries.py new file mode 100644 index 00000000..a50a3574 --- /dev/null +++ b/student-tests/test_telemetry_queries.py @@ -0,0 +1,91 @@ +import base64 +import json +import ssl +import time +from pathlib import Path +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +context = ssl.create_default_context( + cafile="/run/ca/ca.crt" +) + +password = Path( + "/test-secrets/grafana_datasource_password" +).read_text().strip() + +authorization = base64.b64encode( + f"grafana:{password}".encode() +).decode() + + +def query(base, params): + request = Request( + base + "?" + urlencode(params), + headers={ + "Authorization": f"Basic {authorization}" + }, + ) + + with urlopen( + request, + context=context, + timeout=10, + ) as response: + assert response.status == 200 + return json.load(response) + + +def test_loki(): + for _ in range(15): + result = query( + "https://loki:3100/loki/api/v1/query_range", + { + "query": '{service_name="lab7-security-test"}', + "start": str(time.time_ns() - 3600 * 10**9), + "end": str(time.time_ns()), + "limit": 20, + }, + ) + + streams = result["data"]["result"] + + if any( + "Lab7 TLS security test" in entry[1] + for stream in streams + for entry in stream.get("values", []) + ): + print("PASS: Loki stored log retrieved via HTTPS") + return + + time.sleep(2) + + raise AssertionError("Loki test log not found") + + +def test_tempo(): + for _ in range(15): + result = query( + "https://tempo:3200/api/search", + { + "q": '{ resource.service.name = "lab7-security-test" }', + "limit": 20, + }, + ) + + traces = result.get("traces", []) + + if traces: + print("PASS: Tempo stored trace found via HTTPS") + print("Trace ID:", traces[0]["traceID"]) + return + + time.sleep(2) + + raise AssertionError("Tempo test trace not found") + + +test_loki() +test_tempo() + +print("PASS: TELEMETRY QUERY TESTS") diff --git a/student-tests/test_upload_limits.py b/student-tests/test_upload_limits.py new file mode 100644 index 00000000..3836b62f --- /dev/null +++ b/student-tests/test_upload_limits.py @@ -0,0 +1,110 @@ +import base64 +import json +import ssl +import sys + +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import HTTPError + +sys.path.insert(0, "tests") + +from client import Client + +BASE = "https://localhost:8443" +CA = str(Path("certs/ca/ca.crt").resolve()) + +context = ssl.create_default_context(cafile=CA) + +c = Client(BASE, CA) +alice, bob, eve, chat = c.bootstrap() + +registration = alice["registration"] + +credentials = base64.b64encode( + ( + registration["username"] + + ":" + + registration["password"] + ).encode() +).decode() + +login = Request( + BASE + "/api/v1/auth/sessions", + method="POST", + headers={ + "Authorization": f"Basic {credentials}", + }, +) + +with urlopen( + login, context=context, timeout=10 +) as response: + assert response.status == 201 + token = json.loads(response.read())["token"] + +path = ( + BASE + + "/api/v1/chats/" + + chat["id"] + + "/attachments?filename=security-test.png" +) + + +def upload(body, content_type): + request = Request( + path, + method="POST", + data=body, + headers={ + "Authorization": f"Bearer {token}", + "Content-Type": content_type, + }, + ) + + try: + with urlopen( + request, context=context, timeout=30 + ) as response: + return ( + response.status, + response.headers, + response.read(), + ) + except HTTPError as exc: + return exc.code, exc.headers, exc.read() + + +status, headers, body = upload( + b"x" * (10 * 1024 * 1024 + 1), + "image/png", +) + +print("Response status:", status) +print("Response body:", body[:1000].decode(errors="replace")) +assert status == 413, status + +error = json.loads(body) +assert error["error"]["code"] == "payload_too_large" + +print("PASS: application rejects upload above 10 MiB") + +status, headers, body = upload( + b"x" * (12 * 1024 * 1024 + 1), + "image/png", +) + +assert status == 413, status +assert headers.get("X-Instance-Id") is None + +print("PASS: Nginx rejects request above 12 MiB") + +status, _, body = upload( + b"invalid content", + "text/plain", +) + +assert status == 415, status + +print("PASS: unsupported media type rejected") +print("PASS: ALL UPLOAD LIMIT TESTS")