diff --git a/compose.yaml b/compose.yaml index aefc64d..ff54fc1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,26 +1,31 @@ -# Lab 6 stand = lab 5 + observability (docs/OBSERVABILITY.md): -# api x2 / relay / worker --OTLP/HTTP--> otel-collector --> prometheus (metrics, + alert rules) -# --> loki (logs) --> tempo (traces) -# grafana (127.0.0.1:3000): provisioned datasources + dashboard + Prometheus alert view. -# The application never waits for telemetry: no depends_on on it, bounded SDK queues. -# Network `telemetry` (internal) joins only the apps and these five services. +# Lab 7 stand = lab 6 + security on every trust boundary (contracts/trust-matrix.md): +# client --HTTPS :8443 (public CA)--> lb (HAProxy) --mTLS (internal CA, SAN allowlist lb)--> api x2 +# api/relay/worker --TLS verify-full--> postgres (own role per service, GRANT only what it does) +# api --TLS (rediss)--> valkey (ACL user api) api/worker --HTTPS--> s3 (own key pair each) +# relay/worker --AMQPS 5671--> broker (publish-only / consume-only users) +# api/relay/worker --OTLP/HTTPS + client cert--> otel-collector --mTLS--> prometheus/loki/tempo +# grafana (https://localhost:3000, public CA) --mTLS--> the three datasources +# Nothing speaks plaintext over a container network. Plaintext remains only on a container's own +# loopback (healthchecks, the internal hops of SeaweedFS/Loki/Tempo): closed local hops. # -# Lab 5 part: client -> HAProxy (lb) -> API x N (scalable service `api`) -# -> PostgreSQL (metadata, jobs, outbox: source of truth) + Valkey (sessions) -# + SeaweedFS S3 (staging bucket and final bucket, both private) +# Lab 6 part: api x2 / relay / worker --OTLP--> otel-collector --> prometheus (metrics + alert rules) +# --> loki (logs) --> tempo (traces); grafana: provisioned datasources + dashboard. +# The application never waits for telemetry: no depends_on on it, bounded SDK queues. +# Lab 5 part: PostgreSQL (metadata, jobs, outbox: source of truth) + Valkey (sessions) +# + SeaweedFS S3 (staging bucket and final bucket, both private) # relay : outbox in PostgreSQL -> RabbitMQ (publisher confirms) [service `relay`] # broker : RabbitMQ 4.3, durable quorum queue + dead-letter queue [service `broker`] # worker : RabbitMQ -> variants -> final bucket + PostgreSQL, then ack [service `worker`] -# From a clean clone (details and Windows notes: REPORT.md, docs/WINDOWS.md): -# python scripts/init_secrets.py # once: random local credentials into ./secrets (git-ignored) -# cp .env.example .env # optional overrides (API_REPLICAS, limits, ...) -# docker compose --env-file .env up -d --build --wait +# From a clean clone: docs/OPERATOR.md (Windows: docs/WINDOWS.md). +# .venv/Scripts/python scripts/init_secrets.py # once: credentials + PKI into ./secrets (git-ignored) +# docker compose up -d --build --wait # Order: postgres/valkey/s3/broker healthy -> migrate + s3-init (ONE run each, exit 0) # -> api healthy -> lb; relay and worker start after migrate/s3-init. # Images are pinned by version AND digest. Passwords/keys are passed only as secret files, and -# every service gets only the secrets it needs. Only the LB publishes ports (loopback only). +# every service gets only the secrets it needs. Only the LB (8443) and Grafana (3000) publish +# ports, both HTTPS, both on loopback only. # Networks: `edge` (lb <-> api); internal (no route outside): `data` (postgres/valkey), -# `storage` (s3), `queue` (broker). The API is NOT on `queue`: it never talks to the broker. +# `storage` (s3), `queue` (broker), `telemetry`. The API is NOT on `queue`. name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} x-api-env: &api-env @@ -42,7 +47,7 @@ x-api-env: &api-env DOCS_ENABLED: ${DOCS_ENABLED:-true} MESSAGE_WRITE_PATH: ${MESSAGE_WRITE_PATH:-function} # S3: the API's own key pair (Write staging + Read final, see infra/seaweedfs/start.sh). - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} @@ -62,18 +67,23 @@ x-api-env: &api-env # Lab 5: pipeline version and attempt budget of the jobs created by uploads. PIPELINE_VERSION: ${PIPELINE_VERSION:-1} JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} - # Failure experiments only (student-tests, bench/); empty = no injected failures. + # Failure experiments only (student-tests); empty = no injected failures. FAULT_POINTS: ${API_FAULT_POINTS:-} + # Lab 7: the CA every outgoing TLS connection (S3, Valkey) verifies the server with. + TLS_CA_FILE: /run/secrets/internal-ca.crt # Lab 6: OpenTelemetry SDK settings shared by api, relay and worker (src/messenger/telemetry.py). -# OTEL_SDK_DISABLED=true = telemetry off (track 1 baseline). Sampler: head sampling in the SDK -# (parentbased_always_on | parentbased_traceidratio + OTEL_TRACES_SAMPLER_ARG). Exporter timeout -# 3 s and bounded batch queues (2048 spans / log records): a dead Collector costs dropped telemetry, -# not memory or request latency. +# Exporter timeout 3 s and bounded batch queues (2048 spans / log records): a dead Collector costs +# dropped telemetry, not memory or request latency. +# Lab 7: OTLP over HTTPS; the SDK verifies the Collector (internal CA, hostname otel-collector) and +# presents the service's own certificate (/run/secrets/service.crt: SAN api / relay / worker). x-otel-env: &otel-env OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} - OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/internal-ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/service.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/service.key OTEL_EXPORTER_OTLP_TIMEOUT: ${OTEL_EXPORTER_OTLP_TIMEOUT:-3} OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_always_on} @@ -92,7 +102,7 @@ x-pipeline-env: &pipeline-env BROKER_URL_FILE: /run/secrets/broker_url DB_POOL_MAX: ${PIPELINE_DB_POOL_MAX:-6} DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} @@ -105,21 +115,46 @@ x-pipeline-env: &pipeline-env JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2} JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60} QUEUED_REPUBLISH_SECONDS: ${QUEUED_REPUBLISH_SECONDS:-300} + TLS_CA_FILE: /run/secrets/internal-ca.crt services: + # PostgreSQL 18. Lab 7: TLS (internal CA, SAN postgres), pg_hba accepts ONLY hostssl logins of the + # service roles; the superuser `postgres` exists for initdb and the operator (local socket). + # The server key must be 0600 and owned by postgres: it is copied from the secret into a tmpfs + # at start (the bind-mounted secret cannot be chowned), then the image's entrypoint drops root. postgres: image: postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c environment: - POSTGRES_USER: messenger POSTGRES_DB: messenger POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password - # pg_stat_statements: per-statement counters for the experiments. - command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"] - secrets: [postgres_password] + command: + - sh + - -c + - >- + install -o postgres -g postgres -m 600 /run/secrets/postgres.key /run/pgtls/server.key && + exec docker-entrypoint.sh postgres + -c ssl=on -c ssl_cert_file=/run/secrets/postgres.crt -c ssl_key_file=/run/pgtls/server.key + -c ssl_min_protocol_version=TLSv1.2 -c hba_file=/etc/postgresql/pg_hba.conf + -c password_encryption=scram-sha-256 + -c shared_preload_libraries=pg_stat_statements -c max_connections=${PG_MAX_CONNECTIONS:-100} + secrets: + - postgres_password + - pg_migrate_password + - pg_api_password + - pg_relay_password + - pg_worker_password + - pg_jobctl_password + - pg_auditor_password + - {source: pki_postgres_crt, target: postgres.crt} + - {source: pki_postgres_key, target: postgres.key} + tmpfs: + - /run/pgtls:size=1m,mode=0755 volumes: - pgdata:/var/lib/postgresql # PostgreSQL 18 image keeps PGDATA under this path + - ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro + - ./infra/postgres/initdb:/docker-entrypoint-initdb.d:ro healthcheck: - test: ["CMD-SHELL", "pg_isready -U messenger -d messenger -q"] + test: ["CMD-SHELL", "pg_isready -U postgres -d messenger -q"] interval: 2s timeout: 3s retries: 30 @@ -131,24 +166,22 @@ services: resources: limits: {cpus: "${PG_CPUS:-2.0}", memory: "${PG_MEMORY:-1g}"} + # Valkey: sessions + login rate limit. Lab 7: TLS only (port 0, tls-port 6379), ACL user `api` + # (infra/valkey/start.sh), `default` user off. valkey: image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 - # The password goes into a config include readable only by the valkey user, - # so it never appears in the process arguments. docker-entrypoint.sh drops root. - command: - - sh - - -c - - >- - umask 077 && - printf 'requirepass %s\n' "$$(cat /run/secrets/valkey_password)" > /tmp/requirepass.conf && - chown valkey /tmp/requirepass.conf && - exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf - secrets: [valkey_password] + entrypoint: ["/bin/sh", "/etc/valkey/start.sh"] + secrets: + - valkey_api_password + - {source: pki_valkey_crt, target: valkey.crt} + - {source: pki_valkey_key, target: valkey.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/valkey/valkey.conf:/etc/valkey/valkey.conf:ro + - ./infra/valkey/start.sh:/etc/valkey/start.sh:ro - valkeydata:/data healthcheck: - test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/valkey_password)\" valkey-cli ping | grep -q PONG"] + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/valkey_api_password)\" valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api ping | grep -q PONG"] interval: 2s timeout: 3s retries: 30 @@ -160,8 +193,8 @@ services: limits: {cpus: "${VALKEY_CPUS:-0.5}", memory: 256m} # S3-compatible object storage (SeaweedFS: master + volume + filer + S3 gateway in one process). - # Bytes live ONLY here, on the named volume s3data: staging bucket (originals accepted before - # 202) and final bucket (published originals and variants). Identities: infra/seaweedfs/start.sh. + # Bytes live ONLY here, on the named volume s3data. Identities: infra/seaweedfs/start.sh. + # Lab 7: the S3 port is HTTPS only (internal CA, SAN s3). s3: image: chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 entrypoint: ["/bin/sh", "/etc/seaweedfs/start.sh"] @@ -179,12 +212,15 @@ services: - s3_worker_secret_access_key - s3_auditor_access_key_id - s3_auditor_secret_access_key + - {source: pki_s3_crt, target: s3.crt} + - {source: pki_s3_key, target: s3.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/seaweedfs/start.sh:/etc/seaweedfs/start.sh:ro - s3data:/data healthcheck: - # Unauthenticated health endpoint of the S3 gateway (200 once it serves requests). - test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8333/healthz"] + # Unauthenticated health endpoint of the S3 gateway, over HTTPS with full verification. + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "--cacert", "/run/secrets/internal-ca.crt", "https://localhost:8333/healthz"] interval: 2s timeout: 3s retries: 30 @@ -196,22 +232,24 @@ services: resources: limits: {cpus: "${S3_CPUS:-1.0}", memory: "${S3_MEMORY:-1g}"} - # Lab 5: RabbitMQ. Topology (exchange, quorum queue, DLX/DLQ) and users come from definition - # files imported at boot (infra/rabbitmq, secrets/rabbitmq_users.json). Messages of the quorum - # queue live on the named volume rabbitmqdata. No management UI, no host port. + # RabbitMQ. Topology (exchange, quorum queue, DLX/DLQ) and users come from definition files + # imported at boot (infra/rabbitmq, secrets/rabbitmq_users.json). Lab 7: AMQPS 5671 only. broker: image: rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 hostname: broker # node name rabbit@broker: stable across container re-creation secrets: - source: rabbitmq_users target: /etc/rabbitmq/definitions.d/users.json + - {source: pki_broker_crt, target: broker.crt} + - {source: pki_broker_key, target: broker.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-lab5.conf:ro + - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-lab.conf:ro - ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro - ./infra/rabbitmq/topology.json:/etc/rabbitmq/definitions.d/topology.json:ro - rabbitmqdata:/var/lib/rabbitmq healthcheck: - # The node runs and the AMQP listener accepts connections. + # The node runs and its (TLS) listener accepts connections. test: ["CMD-SHELL", "rabbitmq-diagnostics -q ping && rabbitmq-diagnostics -q check_port_connectivity"] interval: 5s timeout: 10s @@ -224,8 +262,8 @@ services: resources: limits: {cpus: "${BROKER_CPUS:-1.0}", memory: "${BROKER_MEMORY:-512m}"} - # One-shot schema migration: runs ONCE per `up`, before any API replica starts - # (api depends_on service_completed_successfully). Replicas never migrate themselves. + # One-shot schema migration as the schema OWNER messenger_migrate (not a superuser): runs ONCE + # per `up`, before any API replica starts. Replicas never migrate themselves. migrate: build: context: . @@ -235,7 +273,9 @@ services: command: ["python", "-m", "messenger.migrate"] environment: DATABASE_URL_FILE: /run/secrets/database_url - secrets: [database_url] + secrets: + - {source: database_url_migrate, target: database_url} + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: postgres: condition: service_healthy @@ -253,7 +293,7 @@ services: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.s3_bootstrap"] environment: - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} @@ -265,6 +305,7 @@ services: S3_WORKER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key S3_AUDITOR_ACCESS_KEY_ID_FILE: /run/secrets/s3_auditor_access_key_id S3_AUDITOR_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_auditor_secret_access_key + TLS_CA_FILE: /run/secrets/internal-ca.crt secrets: - s3_admin_access_key_id - s3_admin_secret_access_key @@ -274,6 +315,7 @@ services: - s3_worker_secret_access_key - s3_auditor_access_key_id - s3_auditor_secret_access_key + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: s3: condition: service_healthy @@ -299,19 +341,17 @@ services: # Lab 7: the only network listener is mTLS on 8443 (tls.py); plaintext health on loopback. APP_PORT: 8443 APP_HEALTH_PORT: 8081 - TLS_CERT_FILE: /run/secrets/api.crt - TLS_KEY_FILE: /run/secrets/api.key + TLS_CERT_FILE: /run/secrets/service.crt + TLS_KEY_FILE: /run/secrets/service.key TLS_CLIENT_CA_FILE: /run/secrets/internal-ca.crt MTLS_ALLOWED_CLIENTS: ${MTLS_ALLOWED_CLIENTS:-lb} secrets: - - database_url + - {source: database_url_api, target: database_url} - cache_url - - source: s3_api_access_key_id - target: s3_access_key_id - - source: s3_api_secret_access_key - target: s3_secret_access_key - - {source: pki_api_crt, target: api.crt} - - {source: pki_api_key, target: api.key} + - {source: s3_api_access_key_id, target: s3_access_key_id} + - {source: s3_api_secret_access_key, target: s3_secret_access_key} + - {source: pki_api_crt, target: service.crt} + - {source: pki_api_key, target: service.key} - {source: pki_internal_ca, target: internal-ca.crt} # No `ports` and no container_name: replicas are reachable only through `lb`, # and `--scale api=N` / deploy.replicas works. @@ -340,10 +380,9 @@ services: replicas: ${API_REPLICAS:-2} resources: # 512m: UPLOAD_CONCURRENCY (4) x 10 MiB bodies + one djpeg (<= JPEG_MAX_MEMORY_MB) + runtime; - # measured in lab 4 (bench/upload_memory.py). No resizing happens in the API. + # measured in lab 4. No resizing happens in the API. limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512m}"} - # No swap on top of the limit (Docker's default would allow as much swap again): the RAM bound - # of the experiments is a real bound, and running out of it is visible, not hidden in swap. + # No swap on top of the limit: the RAM bound is a real bound. memswap_limit: ${API_MEMORY:-512m} lb: @@ -378,8 +417,7 @@ services: resources: limits: {cpus: "${LB_CPUS:-1.0}", memory: 128m} - # Lab 5: outbox relay + lease reaper (src/messenger/relay.py). One process; a second one would - # be safe (SKIP LOCKED) but is not needed. Database + broker only, no S3 keys. + # Outbox relay + lease reaper (src/messenger/relay.py). Database + broker only, no S3 keys. relay: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.relay"] @@ -389,9 +427,11 @@ services: RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-0.5} FAULT_POINTS: ${RELAY_FAULT_POINTS:-} secrets: - - database_url - - source: broker_url_relay - target: broker_url + - {source: database_url_relay, target: database_url} + - {source: broker_url_relay, target: broker_url} + - {source: pki_relay_crt, target: service.crt} + - {source: pki_relay_key, target: service.key} + - {source: pki_internal_ca, target: internal-ca.crt} healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] interval: 5s @@ -412,8 +452,8 @@ services: resources: limits: {cpus: "${RELAY_CPUS:-0.5}", memory: 256m} - # Lab 5: image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing - # consumers of one queue; the database lease decides who works on a job. + # Image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing consumers of + # one queue; the database lease decides who works on a job. worker: image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.worker"] @@ -430,13 +470,13 @@ services: CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30} FAULT_POINTS: ${WORKER_FAULT_POINTS:-} secrets: - - database_url - - source: broker_url_worker - target: broker_url - - source: s3_worker_access_key_id - target: s3_access_key_id - - source: s3_worker_secret_access_key - target: s3_secret_access_key + - {source: database_url_worker, target: database_url} + - {source: broker_url_worker, target: broker_url} + - {source: s3_worker_access_key_id, target: s3_access_key_id} + - {source: s3_worker_secret_access_key, target: s3_secret_access_key} + - {source: pki_worker_crt, target: service.crt} + - {source: pki_worker_key, target: service.key} + - {source: pki_internal_ca, target: internal-ca.crt} healthcheck: test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"] interval: 5s @@ -464,7 +504,7 @@ services: limits: {cpus: "${WORKER_CPUS:-2.0}", memory: "${WORKER_MEMORY:-1536m}"} memswap_limit: ${WORKER_MEMORY:-1536m} - # Track 2: read-only checker of the pipeline invariants (database in read-only transactions, + # Read-only checker of the pipeline invariants (database role messenger_auditor: SELECT only, # S3 auditor key: Read + List, no Write). On demand: docker compose run --rm auditor auditor: profiles: ["tools"] @@ -474,19 +514,19 @@ services: environment: DATABASE_URL_FILE: /run/secrets/database_url DB_TIMEOUT_SECONDS: ${AUDIT_DB_TIMEOUT_SECONDS:-30} - S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} + S3_ENDPOINT: ${S3_ENDPOINT:-https://s3:8333} S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging} S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3} + TLS_CA_FILE: /run/secrets/internal-ca.crt secrets: - - database_url - - source: s3_auditor_access_key_id - target: s3_access_key_id - - source: s3_auditor_secret_access_key - target: s3_secret_access_key + - {source: database_url_auditor, target: database_url} + - {source: s3_auditor_access_key_id, target: s3_access_key_id} + - {source: s3_auditor_secret_access_key, target: s3_secret_access_key} + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: postgres: condition: service_healthy @@ -500,7 +540,6 @@ services: # Operator CLI (replay of failed jobs, reprocess with a newer pipeline, failed registry): # docker compose run --rm jobctl list-failed - # docker compose run --rm jobctl replay --operator alice --reason "..." jobctl: profiles: ["tools"] image: ${API_IMAGE:-mtusi-messenger:lab7} @@ -509,7 +548,9 @@ services: environment: DATABASE_URL_FILE: /run/secrets/database_url JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} - secrets: [database_url] + secrets: + - {source: database_url_jobctl, target: database_url} + - {source: pki_internal_ca, target: internal-ca.crt} depends_on: postgres: condition: service_healthy @@ -544,17 +585,21 @@ services: resources: limits: {cpus: "0.5", memory: 128m} - # ------------------------------------------------------------------ lab 6: observability + # ------------------------------------------------------------------ observability (lab 6) # Receives OTLP from api/relay/worker, limits memory, batches, forwards to the three stores. - # Distroless image (no shell): its health is the `up{job="otel-collector"}` scrape of :8888. + # Distroless image (no shell). Lab 7: receiver HTTPS + client certificate required, exporters mTLS. otel-collector: image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea command: - --config=/etc/otelcol/collector.yaml - # traces-all (keep every span) | traces-tail (tail sampling, track 1) + # traces-all (keep every span) | traces-tail (tail sampling, lab 6 track 1) - --config=/etc/otelcol/${OTEL_COLLECTOR_TRACES:-traces-all}.yaml environment: GOMEMLIMIT: 360MiB # Go heap target under the 512 MiB container limit + secrets: + - {source: pki_otel_collector_crt, target: otel-collector.crt} + - {source: pki_otel_collector_key, target: otel-collector.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/otel:/etc/otelcol:ro restart: unless-stopped @@ -564,22 +609,29 @@ services: limits: {cpus: "${COLLECTOR_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # Metrics store + alert rules (OTLP receiver for the Collector's pushes; scrapes otelcol_*). + # Metrics store + alert rules. Lab 7: HTTPS + client certificate + SAN allowlist (web-config.yml). prometheus: image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 command: - --config.file=/etc/prometheus/prometheus.yml + - --web.config.file=/etc/prometheus/web-config.yml - --storage.tsdb.path=/prometheus - --storage.tsdb.retention.time=15d - --storage.tsdb.retention.size=2GB - --web.enable-otlp-receiver - --web.listen-address=:9090 + secrets: + - {source: pki_prometheus_crt, target: prometheus.crt} + - {source: pki_prometheus_key, target: prometheus.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/web-config.yml:/etc/prometheus/web-config.yml:ro + - ./infra/prometheus/promtool-http.yml:/etc/prometheus/promtool-http.yml:ro - ./infra/prometheus/rules:/etc/prometheus/rules:ro - promdata:/prometheus healthcheck: - test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"] + test: ["CMD", "promtool", "check", "ready", "--url=https://localhost:9090", "--http.config.file=/etc/prometheus/promtool-http.yml"] interval: 5s timeout: 3s retries: 30 @@ -592,12 +644,16 @@ services: limits: {cpus: "${PROMETHEUS_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # Logs store (OTLP endpoint /otlp). Distroless: health = up{job="loki"} + /ready via Grafana. + # Logs store (OTLP endpoint /otlp). Distroless. Lab 7: HTTPS + client certificate required. loki: image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 - command: ["-config.file=/etc/loki/lab6.yaml"] + command: ["-config.file=/etc/loki/lab.yaml"] + secrets: + - {source: pki_loki_crt, target: loki.crt} + - {source: pki_loki_key, target: loki.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - - ./infra/loki/loki.yaml:/etc/loki/lab6.yaml:ro + - ./infra/loki/loki.yaml:/etc/loki/lab.yaml:ro - lokidata:/loki stop_grace_period: 30s restart: unless-stopped @@ -607,12 +663,16 @@ services: limits: {cpus: "${LOKI_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # Traces store (OTLP/HTTP :4318, query API :3200). Distroless: health = up{job="tempo"}. + # Traces store (OTLP/HTTPS :4318, query API :3200). Distroless. Lab 7: both listeners mTLS. tempo: image: grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38 - command: ["-config.file=/etc/tempo/lab6.yaml"] + command: ["-config.file=/etc/tempo/lab.yaml"] + secrets: + - {source: pki_tempo_crt, target: tempo.crt} + - {source: pki_tempo_key, target: tempo.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - - ./infra/tempo/tempo.yaml:/etc/tempo/lab6.yaml:ro + - ./infra/tempo/tempo.yaml:/etc/tempo/lab.yaml:ro - tempodata:/var/tempo stop_grace_period: 30s restart: unless-stopped @@ -622,13 +682,20 @@ services: limits: {cpus: "${TEMPO_CPUS:-1.0}", memory: 512m} memswap_limit: 512m - # UI: datasources (fixed UIDs) and the dashboard are provisioned from Git; only this port and the - # LB are published, on loopback. Admin password = secrets/grafana_admin_password (init_secrets.py). + # UI: datasources (fixed UIDs) and the dashboard are provisioned from Git. Lab 7: HTTPS on + # 127.0.0.1/[::1]:3000 with a public-CA certificate (SAN localhost), datasources over mTLS. + # Admin password = secrets/grafana_admin_password (init_secrets.py). grafana: image: grafana/grafana:13.2.6@sha256:b21409d7951ddcfd63a4b49083e4ef2cc35bc1437d071813bf82bfb238b00bca environment: GF_SECURITY_ADMIN_USER: admin GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /run/secrets/grafana-ui.crt + GF_SERVER_CERT_KEY: /run/secrets/grafana-ui.key + GF_SERVER_MIN_TLS_VERSION: TLS1.2 + GF_SERVER_DOMAIN: localhost + GF_SECURITY_COOKIE_SECURE: "true" GF_USERS_ALLOW_SIGN_UP: "false" GF_AUTH_ANONYMOUS_ENABLED: "false" GF_ANALYTICS_REPORTING_ENABLED: "false" @@ -638,8 +705,15 @@ services: GF_PLUGINS_PREINSTALL_DISABLED: "true" # no plugin downloads at start: works offline GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH: /var/lib/grafana/dashboards/messenger.json GF_LOG_LEVEL: warn - GOMEMLIMIT: 700MiB # Go heap target under the 1 GiB limit (512 MiB was not enough: GC thrashing) - secrets: [grafana_admin_password] + GOMEMLIMIT: 700MiB # Go heap target under the 1 GiB limit + secrets: + - grafana_admin_password + - {source: pki_grafana_ui_crt, target: grafana-ui.crt} + - {source: pki_grafana_ui_key, target: grafana-ui.key} + - {source: pki_public_ca, target: public-ca.crt} + - {source: pki_grafana_crt, target: grafana.crt} + - {source: pki_grafana_key, target: grafana.key} + - {source: pki_internal_ca, target: internal-ca.crt} volumes: - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro @@ -648,7 +722,7 @@ services: - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" - "[::1]:${GRAFANA_PORT:-3000}:3000" healthcheck: - test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:3000/api/health"] + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "--cacert", "/run/secrets/public-ca.crt", "https://localhost:3000/api/health"] interval: 5s timeout: 3s retries: 30 @@ -689,13 +763,37 @@ volumes: tempodata: grafanadata: +# Every value is a file in ./secrets (scripts/init_secrets.py, git-ignored), mounted read-only +# under /run/secrets ONLY into the services listed above. secrets: postgres_password: file: ./secrets/postgres_password - valkey_password: - file: ./secrets/valkey_password - database_url: - file: ./secrets/database_url + pg_migrate_password: + file: ./secrets/pg_migrate_password + pg_api_password: + file: ./secrets/pg_api_password + pg_relay_password: + file: ./secrets/pg_relay_password + pg_worker_password: + file: ./secrets/pg_worker_password + pg_jobctl_password: + file: ./secrets/pg_jobctl_password + pg_auditor_password: + file: ./secrets/pg_auditor_password + database_url_migrate: + file: ./secrets/database_url_migrate + database_url_api: + file: ./secrets/database_url_api + database_url_relay: + file: ./secrets/database_url_relay + database_url_worker: + file: ./secrets/database_url_worker + database_url_jobctl: + file: ./secrets/database_url_jobctl + database_url_auditor: + file: ./secrets/database_url_auditor + valkey_api_password: + file: ./secrets/valkey_api_password cache_url: file: ./secrets/cache_url s3_admin_access_key_id: @@ -724,24 +822,70 @@ secrets: file: ./secrets/grafana_admin_password # Lab 7 PKI (scripts/init_pki.py). Each service mounts only its own certificate/key and the CA it # verifies peers with; the CA private keys are mounted nowhere. + pki_public_ca: + file: ./secrets/pki/public-ca.crt + pki_internal_ca: + file: ./secrets/pki/internal-ca.crt pki_ingress_pem: file: ./secrets/pki/ingress.pem pki_lb_pem: file: ./secrets/pki/lb.pem - pki_internal_ca: - file: ./secrets/pki/internal-ca.crt - pki_api_crt: - file: ./secrets/pki/api.crt - pki_api_key: - file: ./secrets/pki/api.key pki_lb_crt: file: ./secrets/pki/lb.crt pki_lb_key: file: ./secrets/pki/lb.key + pki_api_crt: + file: ./secrets/pki/api.crt + pki_api_key: + file: ./secrets/pki/api.key + pki_relay_crt: + file: ./secrets/pki/relay.crt + pki_relay_key: + file: ./secrets/pki/relay.key pki_worker_crt: file: ./secrets/pki/worker.crt pki_worker_key: file: ./secrets/pki/worker.key + pki_postgres_crt: + file: ./secrets/pki/postgres.crt + pki_postgres_key: + file: ./secrets/pki/postgres.key + pki_valkey_crt: + file: ./secrets/pki/valkey.crt + pki_valkey_key: + file: ./secrets/pki/valkey.key + pki_s3_crt: + file: ./secrets/pki/s3.crt + pki_s3_key: + file: ./secrets/pki/s3.key + pki_broker_crt: + file: ./secrets/pki/broker.crt + pki_broker_key: + file: ./secrets/pki/broker.key + pki_otel_collector_crt: + file: ./secrets/pki/otel-collector.crt + pki_otel_collector_key: + file: ./secrets/pki/otel-collector.key + pki_prometheus_crt: + file: ./secrets/pki/prometheus.crt + pki_prometheus_key: + file: ./secrets/pki/prometheus.key + pki_loki_crt: + file: ./secrets/pki/loki.crt + pki_loki_key: + file: ./secrets/pki/loki.key + pki_tempo_crt: + file: ./secrets/pki/tempo.crt + pki_tempo_key: + file: ./secrets/pki/tempo.key + pki_grafana_crt: + file: ./secrets/pki/grafana.crt + pki_grafana_key: + file: ./secrets/pki/grafana.key + pki_grafana_ui_crt: + file: ./secrets/pki/grafana-ui.crt + pki_grafana_ui_key: + file: ./secrets/pki/grafana-ui.key pki_foreign_lb_crt: # test only: foreign CA, SAN lb file: ./secrets/pki/foreign-lb.crt pki_foreign_lb_key: diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json index 43d487c..7f05f17 100644 --- a/infra/grafana/dashboards/messenger.json +++ b/infra/grafana/dashboards/messenger.json @@ -1047,7 +1047,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "rate(otelcol_process_cpu_seconds[$__rate_interval])", + "expr": "rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "legendFormat": "otel-collector", "range": true } @@ -1112,7 +1112,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "otelcol_process_memory_rss", + "expr": "otelcol_process_memory_rss_bytes", "legendFormat": "otel-collector RSS", "range": true } @@ -1445,7 +1445,7 @@ "type": "prometheus", "uid": "prometheus" }, - "description": "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).\n\nUnit: ops.", + "description": "otelcol_* self-metrics, pushed over OTLP/HTTPS (lab 7). sent < accepted with tail sampling (dropped by policy).\n\nUnit: ops.", "gridPos": { "h": 8, "w": 8, @@ -1486,7 +1486,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "legendFormat": "accepted", "range": true }, @@ -1496,7 +1496,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))", "legendFormat": "refused (memory_limiter)", "range": true }, @@ -1506,7 +1506,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", "legendFormat": "sent to Tempo", "range": true }, @@ -1516,7 +1516,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))", "legendFormat": "send failed (dropped)", "range": true } @@ -1571,7 +1571,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "legendFormat": "logs accepted", "range": true }, @@ -1581,7 +1581,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", "legendFormat": "logs failed", "range": true }, @@ -1591,7 +1591,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", + "expr": "sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "legendFormat": "metric points accepted", "range": true }, @@ -1601,7 +1601,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", + "expr": "sum(rate(otelcol_exporter_send_failed_metric_points_total[$__rate_interval]))", "legendFormat": "metric points failed", "range": true } @@ -1787,7 +1787,7 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", + "expr": "up{job=~\"prometheus|loki|tempo\"}", "legendFormat": "{{job}}", "range": true } diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml index a788578..d286773 100644 --- a/infra/grafana/provisioning/datasources/datasources.yaml +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -2,6 +2,10 @@ # the dashboard JSON, the trace->logs and logs->trace links refer to exactly these UIDs # (prometheus / loki / tempo). A datasource without a fixed uid gets a random one and every # reference to it breaks ("data source not found"). +# Lab 7: every datasource is HTTPS with server verification (internal CA, serverName = the SAN) +# and Grafana's own client certificate (SAN grafana): the three backends require one, Prometheus +# also checks the SAN allowlist. The PEM files are read at provisioning time ($__file{}), from +# Docker secrets mounted only into Grafana. apiVersion: 1 deleteDatasources: @@ -14,10 +18,17 @@ datasources: uid: prometheus type: prometheus access: proxy - url: http://prometheus:9090 + url: https://prometheus:9090 isDefault: true editable: false + secureJsonData: &tls_files + tlsCACert: $__file{/run/secrets/internal-ca.crt} + tlsClientCert: $__file{/run/secrets/grafana.crt} + tlsClientKey: $__file{/run/secrets/grafana.key} jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: prometheus httpMethod: POST timeInterval: 15s # = scrape/evaluation interval: $__rate_interval >= 4 x 15 s prometheusType: Prometheus @@ -29,9 +40,13 @@ datasources: uid: loki type: loki access: proxy - url: http://loki:3100 + url: https://loki:3100 editable: false + secureJsonData: *tls_files jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: loki maxLines: 1000 # log line -> its trace in Tempo (trace_id is structured metadata of the OTLP record) derivedFields: @@ -46,9 +61,13 @@ datasources: uid: tempo type: tempo access: proxy - url: http://tempo:3200 + url: https://tempo:3200 editable: false + secureJsonData: *tls_files jsonData: + tlsAuth: true + tlsAuthWithCACert: true + serverName: tempo # span -> the log records of the same trace (and service) in Loki tracesToLogsV2: datasourceUid: loki diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml index c4b8f29..053a4b4 100644 --- a/infra/loki/loki.yaml +++ b/infra/loki/loki.yaml @@ -12,7 +12,15 @@ auth_enabled: false server: http_listen_port: 3100 grpc_listen_port: 9096 + grpc_listen_address: 127.0.0.1 log_level: warn + # Lab 7: HTTPS + mandatory client certificate of the internal CA (otel-collector pushes, + # grafana queries, prometheus scrapes). gRPC is internal to the single binary: loopback only. + http_tls_config: + cert_file: /run/secrets/loki.crt + key_file: /run/secrets/loki.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt common: instance_addr: 127.0.0.1 diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index c034934..ccbe005 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -1,24 +1,29 @@ -# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), lab 6. +# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), labs 6-7. # -# API x2 / relay / worker --OTLP/HTTP protobuf :4318--> [receiver otlp] -# -> memory_limiter -> batch -> exporters: -# traces -> Tempo (otlp_http/tempo, http://tempo:4318/v1/traces) -# metrics -> Prometheus (otlp_http/prometheus, http://prometheus:9090/api/v1/otlp/v1/metrics) -# logs -> Loki (otlp_http/loki, http://loki:3100/otlp/v1/logs) +# API x2 / relay / worker --OTLP/HTTPS (mTLS) :4318--> [receiver otlp] +# -> memory_limiter -> batch -> exporters (all HTTPS + client certificate otel-collector): +# traces -> Tempo (otlp_http/tempo, https://tempo:4318/v1/traces) +# metrics -> Prometheus (otlp_http/prometheus, https://prometheus:9090/api/v1/otlp/v1/metrics) +# logs -> Loki (otlp_http/loki, https://loki:3100/otlp/v1/logs) # +# Lab 7 (contracts/trust-matrix.md): the receiver speaks TLS only and REQUIRES a client certificate +# of the internal CA (client_ca_file): a process on the `telemetry` network without such a +# certificate cannot ingest anything. Every exporter verifies the backend (internal CA + hostname) +# and authenticates with the Collector's own certificate (SAN otel-collector); Prometheus also +# checks that SAN against its allowlist. # The Collector stores nothing for long: it receives, limits, batches and forwards. When a backend # is down, each exporter keeps a BOUNDED queue (sending_queue) and retries for at most # max_elapsed_time; then the data is dropped and counted (otelcol_exporter_send_failed_*, -# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit (the SDKs -# get a retryable error and drop after their own bounded queue) instead of growing until OOM. -# Its own metrics: Prometheus scrapes :8888 (otelcol_*). Only on the internal `telemetry` network. +# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit. +# Its own metrics: PUSHED over OTLP/HTTPS to Prometheus (lab 7; the lab 6 pull endpoint :8888 had no +# TLS). health_check listens on the container's loopback only. # -# Traces pipeline variants (track 1, docs/TRACK1.md): this file keeps EVERY span; the overlay +# Traces pipeline variants (lab 6 track 1): this file keeps EVERY span; the overlay # traces-tail.yaml (passed as a second --config, compose OTEL_COLLECTOR_TRACES) adds tail sampling. extensions: health_check: - endpoint: 0.0.0.0:13133 + endpoint: 127.0.0.1:13133 receivers: otlp: @@ -26,11 +31,15 @@ receivers: http: endpoint: 0.0.0.0:4318 max_request_body_size: 8388608 # 8 MiB per export request + tls: + cert_file: /run/secrets/otel-collector.crt + key_file: /run/secrets/otel-collector.key + client_ca_file: /run/secrets/internal-ca.crt # = RequireAndVerifyClientCert + min_version: "1.2" processors: # First in every pipeline. Container limit 512 MiB: soft limit = 400 - 80 = 320 MiB (start - # refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS; - # 256 MiB of container memory left the limiter refusing data at idle. GOMEMLIMIT = 360 MiB. + # refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS. memory_limiter: check_interval: 1s limit_mib: 400 @@ -43,8 +52,13 @@ processors: exporters: otlp_http/tempo: - endpoint: http://tempo:4318 + endpoint: https://tempo:4318 timeout: 5s + tls: &mtls + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/otel-collector.crt + key_file: /run/secrets/otel-collector.key + min_version: "1.2" sending_queue: &queue enabled: true num_consumers: 2 @@ -55,29 +69,37 @@ exporters: max_interval: 10s max_elapsed_time: 60s # then the batch is dropped (counted), never retried forever otlp_http/prometheus: - endpoint: http://prometheus:9090/api/v1/otlp + endpoint: https://prometheus:9090/api/v1/otlp timeout: 5s + tls: *mtls sending_queue: *queue retry_on_failure: *retry otlp_http/loki: - endpoint: http://loki:3100/otlp + endpoint: https://loki:3100/otlp timeout: 5s + tls: *mtls sending_queue: *queue retry_on_failure: *retry service: extensions: [health_check] telemetry: + resource: + service.name: otel-collector logs: level: warn metrics: level: normal readers: - - pull: + - periodic: + interval: 15000 exporter: - prometheus: - host: 0.0.0.0 - port: 8888 + otlp: + protocol: http/protobuf + endpoint: https://prometheus:9090/api/v1/otlp/v1/metrics + certificate: /run/secrets/internal-ca.crt + client_certificate: /run/secrets/otel-collector.crt + client_key: /run/secrets/otel-collector.key pipelines: traces: receivers: [otlp] diff --git a/infra/postgres/initdb/10-roles.sh b/infra/postgres/initdb/10-roles.sh new file mode 100644 index 0000000..e8514ee --- /dev/null +++ b/infra/postgres/initdb/10-roles.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Runs ONCE, when the volume pgdata is initialised (docker-entrypoint-initdb.d), as OS user postgres +# over the local socket. Creates one login role per service; the passwords come from Docker secret +# files and are passed to psql as variables (never on a command line, never printed). +# messenger_migrate owns the database objects (applies migrations, service `migrate`) +# messenger_api / messenger_relay / messenger_worker GRANTs in migrations/0007_least_privilege.sql +# messenger_jobctl / messenger_auditor operator tools (profile tools) +# Nobody but `postgres` (no network login, see pg_hba.conf) is a superuser. +set -eu +for role in migrate api relay worker jobctl auditor; do + pw="$(tr -d '\r\n' < "/run/secrets/pg_${role}_password")" + psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres -v role="messenger_${role}" -v pw="$pw" <<'SQL' +CREATE ROLE :"role" LOGIN PASSWORD :'pw' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; +SQL +done +psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres <<'SQL' +ALTER DATABASE messenger OWNER TO messenger_migrate; +-- Only the service roles may connect to the application database. +REVOKE ALL ON DATABASE messenger FROM PUBLIC; +GRANT CONNECT ON DATABASE messenger TO messenger_migrate, messenger_api, messenger_relay, messenger_worker, + messenger_jobctl, messenger_auditor; +SQL +psql -v ON_ERROR_STOP=1 --username postgres --dbname messenger <<'SQL' +-- PostgreSQL 15+: schema public belongs to pg_database_owner (= messenger_migrate now), and +-- PUBLIC has no CREATE on it. Make it explicit: only the owner creates objects. +REVOKE CREATE ON SCHEMA public FROM PUBLIC; +GRANT USAGE ON SCHEMA public TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl, messenger_auditor; +SQL +echo "initdb: service roles created" diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..5930bf8 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,18 @@ +# PostgreSQL client authentication, lab 7 (passed with -c hba_file=..., compose service postgres). +# First matching line wins. +# +# Unix socket inside the container only (docker compose exec): the superuser `postgres` by peer +# (OS user postgres), everyone else by password. initdb scripts and the operator use this path. +# TYPE DATABASE USER ADDRESS METHOD +local all postgres peer +local all all scram-sha-256 +# Network: TLS ONLY and only the service roles, password = SCRAM. The superuser never logs in +# over the network. Clients verify the server with sslmode=verify-full (internal CA, SAN postgres). +hostssl messenger messenger_migrate all scram-sha-256 +hostssl messenger messenger_api all scram-sha-256 +hostssl messenger messenger_relay all scram-sha-256 +hostssl messenger messenger_worker all scram-sha-256 +hostssl messenger messenger_jobctl all scram-sha-256 +hostssl messenger messenger_auditor all scram-sha-256 +# Everything else - any plaintext connection, any other role/database - is refused. +host all all all reject diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml index 4c4591c..32bdc46 100644 --- a/infra/prometheus/prometheus.yml +++ b/infra/prometheus/prometheus.yml @@ -1,11 +1,15 @@ -# Prometheus 3.16 (prom/prometheus:v3.16.0), lab 6: the METRICS store. +# Prometheus 3.16 (prom/prometheus:v3.16.0), labs 6-7: the METRICS store. # -# Application metrics are PUSHED by the Collector over OTLP (flag --web.enable-otlp-receiver, -# endpoint /api/v1/otlp/v1/metrics). Prometheus derives `job` = service.name and -# `instance` = service.instance.id from the OTLP resource, and translates the OTel names with -# suffixes: http.server.request.duration (unit s) -> http_server_request_duration_seconds_bucket, -# messenger.jobs.processed -> messenger_jobs_processed_total (mapping: docs/OBSERVABILITY.md). -# The telemetry components themselves are SCRAPED (pull) below. +# Application metrics AND the Collector's own metrics are PUSHED by the Collector over OTLP/HTTPS +# (flag --web.enable-otlp-receiver, endpoint /api/v1/otlp/v1/metrics). Prometheus derives +# `job` = service.name and `instance` = service.instance.id from the OTLP resource, and translates +# the OTel names with suffixes: http.server.request.duration (unit s) -> +# http_server_request_duration_seconds_bucket (mapping: docs/OBSERVABILITY.md). +# +# Lab 7: the web listener is HTTPS with a REQUIRED client certificate of the internal CA and a SAN +# allowlist (web-config.yml): only otel-collector (push), grafana (queries) and prometheus itself +# (self-scrape, promtool healthcheck) get in. Scrapes of Loki/Tempo use HTTPS + this server's +# own client certificate (they require one too). global: scrape_interval: 15s evaluation_interval: 15s # alert rules: detection delay = condition + `for` + <= 15 s @@ -24,13 +28,19 @@ rule_files: - /etc/prometheus/rules/*.yml scrape_configs: - - job_name: otel-collector # otelcol_* : accepted/refused/sent/failed, queue size, RSS - static_configs: [{targets: ["otel-collector:8888"]}] - job_name: prometheus + scheme: https + tls_config: &mtls + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/prometheus.crt + key_file: /run/secrets/prometheus.key + min_version: TLS12 static_configs: [{targets: ["localhost:9090"]}] - job_name: loki + scheme: https + tls_config: *mtls static_configs: [{targets: ["loki:3100"]}] - job_name: tempo + scheme: https + tls_config: *mtls static_configs: [{targets: ["tempo:3200"]}] - - job_name: grafana - static_configs: [{targets: ["grafana:3000"]}] diff --git a/infra/prometheus/promtool-http.yml b/infra/prometheus/promtool-http.yml new file mode 100644 index 0000000..7b47720 --- /dev/null +++ b/infra/prometheus/promtool-http.yml @@ -0,0 +1,7 @@ +# HTTP client config of the container healthcheck (`promtool check healthy`): the same mTLS as any +# other client - Prometheus' own client certificate (SAN prometheus, in the allowlist). +tls_config: + ca_file: /run/secrets/internal-ca.crt + cert_file: /run/secrets/prometheus.crt + key_file: /run/secrets/prometheus.key + server_name: localhost diff --git a/infra/prometheus/rules/alerts.yml b/infra/prometheus/rules/alerts.yml index aa9f628..c438dd6 100644 --- a/infra/prometheus/rules/alerts.yml +++ b/infra/prometheus/rules/alerts.yml @@ -78,9 +78,9 @@ groups: # in its bounded queue and then dropped. The application itself is not affected. expr: | sum by (exporter) ( - rate(otelcol_exporter_send_failed_spans[2m]) - or rate(otelcol_exporter_send_failed_log_records[2m]) - or rate(otelcol_exporter_send_failed_metric_points[2m]) + rate(otelcol_exporter_send_failed_spans_total[2m]) + or rate(otelcol_exporter_send_failed_log_records_total[2m]) + or rate(otelcol_exporter_send_failed_metric_points_total[2m]) ) > 0 for: 30s labels: diff --git a/infra/prometheus/web-config.yml b/infra/prometheus/web-config.yml new file mode 100644 index 0000000..de436ea --- /dev/null +++ b/infra/prometheus/web-config.yml @@ -0,0 +1,10 @@ +# Prometheus web listener (--web.config.file), lab 7: HTTPS + mandatory client certificate of the +# internal CA + allowlist of client identities (SAN). A certificate of the same CA with another +# name (api, worker, loki, ...) is refused in the TLS handshake. +tls_server_config: + cert_file: /run/secrets/prometheus.crt + key_file: /run/secrets/prometheus.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt + client_allowed_sans: [otel-collector, grafana, prometheus] + min_version: TLS12 diff --git a/infra/rabbitmq/rabbitmq.conf b/infra/rabbitmq/rabbitmq.conf index 05165e0..aae31b2 100644 --- a/infra/rabbitmq/rabbitmq.conf +++ b/infra/rabbitmq/rabbitmq.conf @@ -1,7 +1,18 @@ -# RabbitMQ 4.3 of the lab 5 stand (compose service `broker`), mounted as conf.d/20-lab5.conf. -# Only AMQP 0-9-1 on 5672 inside the internal network `queue`: no management UI, no Prometheus -# listener (enabled_plugins is empty), nothing published on the host. -listeners.tcp.default = 5672 +# RabbitMQ 4.3 of the stand (compose service `broker`), mounted as conf.d/20-lab.conf. +# Lab 7: AMQP 0-9-1 over TLS ONLY (amqps, 5671) inside the internal network `queue`. The plaintext +# listener is off, there is no management UI and no Prometheus listener (enabled_plugins is +# empty), nothing is published on the host. Clients verify the server certificate (internal CA, +# SAN broker); their identity is the user relay / worker with its own permissions (grade 3: no +# client certificates; mTLS to the broker is grade 4). +listeners.tcp = none +listeners.ssl.default = 5671 +ssl_options.cacertfile = /run/secrets/internal-ca.crt +ssl_options.certfile = /run/secrets/broker.crt +ssl_options.keyfile = /run/secrets/broker.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 # Users, permissions and topology are imported from files at every boot (idempotent): # /etc/rabbitmq/definitions.d/topology.json exchanges, quorum queues, bindings (this repo) diff --git a/infra/seaweedfs/start.sh b/infra/seaweedfs/start.sh index f496154..78c3699 100644 --- a/infra/seaweedfs/start.sh +++ b/infra/seaweedfs/start.sh @@ -14,6 +14,9 @@ # Exposure: master (9333), volume (8080), filer (8888) with their web UIs and gRPC listen on # 127.0.0.1 INSIDE the container only (-ip.bind); only the S3 API port 8333 listens on the # container network `storage` (internal, not published on the host). Telemetry is off. +# Lab 7: the S3 port speaks HTTPS only (-s3.cert.file/-s3.key.file: internal CA, SAN s3); the +# clients verify chain + hostname (aiobotocore verify=TLS_CA_FILE). The plaintext master/volume/filer +# hops stay on the container's own loopback (closed local hop, not reachable from the network). set -eu umask 077 secret() { tr -d '\r\n' < "/run/secrets/$1"; } @@ -49,4 +52,5 @@ exec weed server \ -filer -filer.disableDirListing -filer.concurrentUploadLimitMB=128 \ -volume.concurrentUploadLimitMB=128 \ -s3 -s3.ip.bind=0.0.0.0 -s3.port=8333 -s3.config=/tmp/s3.json -s3.concurrentUploadLimitMB=128 \ + -s3.cert.file=/run/secrets/s3.crt -s3.key.file=/run/secrets/s3.key \ -s3.iam=false -s3.autoCreateBucket=false -s3.port.iceberg=0 -s3.port.lance=0 diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml index a268041..dbac002 100644 --- a/infra/tempo/tempo.yaml +++ b/infra/tempo/tempo.yaml @@ -6,7 +6,15 @@ stream_over_http_enabled: true server: http_listen_port: 3200 + grpc_listen_address: 127.0.0.1 log_level: warn + # Lab 7: HTTPS + mandatory client certificate of the internal CA (otel-collector pushes, + # grafana queries, prometheus scrapes). gRPC is internal to the single binary: loopback only. + http_tls_config: + cert_file: /run/secrets/tempo.crt + key_file: /run/secrets/tempo.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/secrets/internal-ca.crt distributor: receivers: @@ -14,6 +22,11 @@ distributor: protocols: http: endpoint: 0.0.0.0:4318 + tls: # only the Collector (client certificate of the internal CA) + cert_file: /run/secrets/tempo.crt + key_file: /run/secrets/tempo.key + client_ca_file: /run/secrets/internal-ca.crt + min_version: "1.2" ingester: max_block_duration: 5m # small blocks: a restart loses at most the WAL replay time diff --git a/infra/valkey/start.sh b/infra/valkey/start.sh new file mode 100644 index 0000000..55b7010 --- /dev/null +++ b/infra/valkey/start.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Entry point of the compose service `valkey` (lab 7). Writes the ACL file from the Docker secret and +# starts Valkey through the image's entrypoint (which drops root to the valkey user). +# user default off no anonymous/shared-password access at all +# user api SHA-256 of its password only (the plain password never lands in a file here), +# keys session:* (sessions.py) and ratelimit:* (login limit), commands it uses: +# GET/SET/DEL (sessions), INCR/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING +# (readiness), CLIENT SETINFO (sent by redis-py on connect). FLUSHALL, CONFIG, +# KEYS, DEBUG, ACL, ... are refused with NOPERM. +set -eu +umask 077 +mkdir -p /tmp/valkey +hash="$(tr -d '\r\n' < /run/secrets/valkey_api_password | sha256sum | cut -d' ' -f1)" +printf 'user default off\n' > /tmp/valkey/users.acl +printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \ + "$hash" >> /tmp/valkey/users.acl +chown -R valkey /tmp/valkey +exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf diff --git a/infra/valkey/valkey.conf b/infra/valkey/valkey.conf index 510785b..5da25db 100644 --- a/infra/valkey/valkey.conf +++ b/infra/valkey/valkey.conf @@ -8,10 +8,20 @@ appenddirname "appendonlydir" # RDB snapshots are not needed on top of AOF. save "" dir /data -port 6379 protected-mode yes +# Lab 7: TLS only. The plaintext port is closed (port 0); clients verify the server certificate +# (internal CA, SAN valkey). No client certificates at grade 3 (tls-auth-clients no): the client +# identity is the ACL user + password below. +port 0 +tls-port 6379 +tls-cert-file /run/secrets/valkey.crt +tls-key-file /run/secrets/valkey.key +tls-ca-cert-file /run/secrets/internal-ca.crt +tls-auth-clients no +tls-protocols "TLSv1.2 TLSv1.3" # Sessions are never evicted silently: if memory is full, writes fail and login returns 503. maxmemory 128mb maxmemory-policy noeviction -# Password, generated by scripts/init_secrets.py and written here at container start. -include /tmp/requirepass.conf +# Lab 7: ACL users instead of one shared password (file written by infra/valkey/start.sh at start): +# `default` is off, `api` may touch only session:* / ratelimit:* keys with the commands it uses. +aclfile /tmp/valkey/users.acl diff --git a/migrations/0007_least_privilege.sql b/migrations/0007_least_privilege.sql new file mode 100644 index 0000000..2d951e3 --- /dev/null +++ b/migrations/0007_least_privilege.sql @@ -0,0 +1,48 @@ +-- Lab 7: least privilege in PostgreSQL. The roles are created once by +-- infra/postgres/initdb/10-roles.sh; this migration (run by the owner messenger_migrate) gives +-- every service exactly the table privileges its code uses (src/messenger/*.py) and nothing else: +-- no DDL, no TRUNCATE, no DELETE where the service never deletes, no access to other services' +-- tables. Matrix with the reasons: contracts/trust-matrix.md ("PostgreSQL"). + +-- API: users, chats, messages, idempotency, sessions (SESSION_STORE=postgres), upload intents, +-- the job + outbox row of an accepted upload (one transaction with the attachment, lab 5). +GRANT SELECT, INSERT ON users TO messenger_api; +GRANT SELECT, INSERT, UPDATE ON chats TO messenger_api; -- per-chat clock (0001) +GRANT SELECT, INSERT ON chat_members TO messenger_api; +GRANT SELECT, INSERT ON messages TO messenger_api; +GRANT SELECT, INSERT ON message_attachments TO messenger_api; +GRANT SELECT, INSERT, UPDATE, DELETE ON idempotency_keys TO messenger_api; -- purge after 24 h +GRANT SELECT, INSERT, DELETE ON sessions TO messenger_api; -- logout = DELETE +GRANT SELECT, INSERT, UPDATE, DELETE ON attachments TO messenger_api; -- janitor: stale intents +GRANT SELECT ON attachment_variants TO messenger_api; +GRANT SELECT, INSERT ON jobs TO messenger_api; +GRANT INSERT ON outbox, job_events TO messenger_api; + +-- Relay: outbox -> broker, lease reaper, republish of stale jobs, queue statistics. +GRANT SELECT, INSERT, UPDATE, DELETE ON outbox TO messenger_relay; -- purge published rows +GRANT SELECT, UPDATE ON jobs, job_attempts, attachments TO messenger_relay; +GRANT INSERT ON job_events TO messenger_relay; + +-- Worker: claim/lease/complete/retry of jobs, variants, staging/attempt cleanup bookkeeping. +-- No access to users, chats, messages, sessions or idempotency keys. +GRANT SELECT, UPDATE ON jobs, attachments TO messenger_worker; +GRANT SELECT, INSERT, UPDATE ON job_attempts TO messenger_worker; +GRANT SELECT, INSERT ON attachment_variants TO messenger_worker; +GRANT INSERT ON outbox, job_events TO messenger_worker; + +-- Operator CLI (jobctl): failed registry, replay/reprocess = new job + outbox row + audit event. +GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants, failed_jobs TO messenger_jobctl; +GRANT INSERT ON jobs, outbox, job_events TO messenger_jobctl; +GRANT UPDATE ON jobs, attachments TO messenger_jobctl; + +-- Auditor: read-only checker of the pipeline invariants. +GRANT SELECT ON jobs, job_attempts, job_events, outbox, attachments, attachment_variants TO messenger_auditor; + +-- Identity columns of outbox/job_events: inserting roles need the sequences. +GRANT USAGE ON SEQUENCE outbox_id_seq, job_events_id_seq + TO messenger_api, messenger_relay, messenger_worker, messenger_jobctl; + +-- Functions are executable by PUBLIC by default; only the API sends messages. +REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC; +GRANT EXECUTE ON FUNCTION post_message, post_message_v2, post_message_v3 TO messenger_api; +ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; diff --git a/scripts/build_dashboard.py b/scripts/build_dashboard.py index 865b8bb..095dbcc 100644 --- a/scripts/build_dashboard.py +++ b/scripts/build_dashboard.py @@ -180,11 +180,11 @@ ts("DB pool wait p95 by service", "s", "db.client.connection.wait_time: time to get a connection from the pool.") ts("Container CPU (cores)", [("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"), - ("rate(otelcol_process_cpu_seconds[$__rate_interval])", "otel-collector")], + ("rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "otel-collector")], "short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12) ts("Container memory", [("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"), - ("otelcol_process_memory_rss", "otel-collector RSS")], + ("otelcol_process_memory_rss_bytes", "otel-collector RSS")], "bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12) grid.end() @@ -216,16 +216,16 @@ grid.end() # =============================================================================== telemetry pipeline row("Telemetry pipeline (Collector, SDK)") ts("Collector: spans accepted / sent / failed per second", - [("sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "accepted"), - ("sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", "refused (memory_limiter)"), - ("sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "sent to Tempo"), - ("sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", "send failed (dropped)")], - "ops", "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).") + [("sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "accepted"), + ("sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))", "refused (memory_limiter)"), + ("sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", "sent to Tempo"), + ("sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))", "send failed (dropped)")], + "ops", "otelcol_* self-metrics, pushed over OTLP/HTTPS (lab 7). sent < accepted with tail sampling (dropped by policy).") ts("Collector: logs and metric points per second", - [("sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", "logs accepted"), - ("sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", "logs failed"), - ("sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", "metric points accepted"), - ("sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", "metric points failed")], + [("sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "logs accepted"), + ("sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", "logs failed"), + ("sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "metric points accepted"), + ("sum(rate(otelcol_exporter_send_failed_metric_points_total[$__rate_interval]))", "metric points failed")], "ops", "Same for the logs and metrics pipelines.") ts("Collector: exporter queues", [("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"), @@ -237,7 +237,7 @@ ts("SDK: spans recorded vs exported (all processes)", "ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).", w=12) ts("Telemetry components up", - [("up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", "{{job}}")], + [("up{job=~\"prometheus|loki|tempo\"}", "{{job}}")], "short", "1 = the scrape succeeded.", w=12, maximum=1) grid.end() diff --git a/scripts/init_secrets.py b/scripts/init_secrets.py index 7605794..1d9970c 100644 --- a/scripts/init_secrets.py +++ b/scripts/init_secrets.py @@ -1,11 +1,22 @@ #!/usr/bin/env python3 -"""Create local synthetic credentials for the stand in ./secrets (ignored by Git). +"""Create local synthetic credentials and the PKI of the stand in ./secrets (ignored by Git). - python scripts/init_secrets.py + .venv/Scripts/python scripts/init_secrets.py (Linux/macOS: .venv/bin/python) Idempotent: existing files are kept, so re-running never changes passwords of a database that already has data. Prints only file names, never values. Delete ./secrets together with the volumes (`docker compose down -v`) to start over. + +Lab 7: one credential per service and role (contracts/trust-matrix.md): + PostgreSQL postgres (superuser: initdb + operator via `docker compose exec`, never over the + network), messenger_migrate (owner of the schema), messenger_api / _relay / _worker + (GRANT only what the service does, migrations/0007_least_privilege.sql), + messenger_jobctl / _auditor (operator tools). Every URL has sslmode=verify-full. + Valkey ACL user `api` (session:* and ratelimit:* keys, a few commands), `default` user off. + S3 admin (s3-init only) / api / worker / auditor key pairs. + RabbitMQ relay (publish only) / worker (consume only), amqps:// (TLS 5671). +The application services do not mount these files from lab 7 step 5 on: they read their own +values from OpenBao (scripts/bao_operator.py copies them there), see docs/OPERATOR.md. """ from __future__ import annotations @@ -19,6 +30,8 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SECRETS = ROOT / "secrets" +CA = "/run/secrets/internal-ca.crt" # path INSIDE the containers +DB_ROLES = ("migrate", "api", "relay", "worker", "jobctl", "auditor") def write(name: str, value: str) -> None: @@ -28,7 +41,7 @@ def write(name: str, value: str) -> None: return path.write_text(value + "\n", encoding="utf-8", newline="\n") # Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001) - # through the compose bind mount. Local synthetic lab credentials only. + # through the compose bind mount; the folder ./secrets itself is 0700 for the host user. os.chmod(path, 0o644) print(f"created secrets/{name}") @@ -46,17 +59,23 @@ def rabbit_hash(password: str) -> str: def main() -> int: SECRETS.mkdir(exist_ok=True) + os.chmod(SECRETS, 0o700) + # PostgreSQL: superuser (no network login, pg_hba) + one login role per service. write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs - write("valkey_password", secrets.token_urlsafe(24)) - write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger") - write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0") + for role in DB_ROLES: + write(f"pg_{role}_password", secrets.token_urlsafe(24)) + write(f"database_url_{role}", f"postgresql://messenger_{role}:{read(f'pg_{role}_password')}@postgres:5432/" + f"messenger?sslmode=verify-full&sslrootcert={CA}") + # Valkey: ACL user `api` (infra/valkey/start.sh); TLS only (rediss). + write("valkey_api_password", secrets.token_urlsafe(24)) + write("cache_url", f"rediss://api:{read('valkey_api_password')}@valkey:6379/0") # S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only; # api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write). for who in ("admin", "api", "worker", "auditor"): write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper()) write(f"s3_{who}_secret_access_key", secrets.token_hex(20)) - # Lab 5: RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume - # the jobs queue; neither may declare/delete anything (configure "^$"). + # RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume the jobs + # queue; neither may declare/delete anything (configure "^$"). write("rabbitmq_relay_password", secrets.token_urlsafe(24)) write("rabbitmq_worker_password", secrets.token_urlsafe(24)) users = { @@ -71,8 +90,8 @@ def main() -> int: for who in ("relay", "worker"): # AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and # the broker returns its unacked messages to the queue for the other consumers. - write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10") - # Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy). + write(f"broker_url_{who}", f"amqps://{who}:{read(f'rabbitmq_{who}_password')}@broker:5671/?heartbeat=10") + # Grafana admin (UI on https://localhost:3000 and the evidence scripts, via its datasource proxy). write("grafana_admin_password", secrets.token_urlsafe(18)) # Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki. sys.path.insert(0, str(Path(__file__).resolve().parent)) diff --git a/scripts/obs.py b/scripts/obs.py index 218e838..87b5fa5 100644 --- a/scripts/obs.py +++ b/scripts/obs.py @@ -16,6 +16,7 @@ from __future__ import annotations import base64 import json import os +import ssl import sys import time import urllib.error @@ -24,7 +25,9 @@ import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -GRAFANA = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/") +GRAFANA = os.environ.get("GRAFANA_URL", "https://localhost:3000").rstrip("/") +# Lab 7: Grafana is HTTPS with a public-CA certificate (SAN localhost); verified, never skipped. +TLS = ssl.create_default_context(cafile=os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt")) def _auth() -> str: @@ -38,7 +41,7 @@ def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) -> if params: url += "?" + urllib.parse.urlencode(params) request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"}) - with urllib.request.urlopen(request, timeout=timeout) as response: + with urllib.request.urlopen(request, timeout=timeout, context=TLS) as response: return json.loads(response.read()) diff --git a/scripts/trace_demo.py b/scripts/trace_demo.py index 52ff523..585b11a 100644 --- a/scripts/trace_demo.py +++ b/scripts/trace_demo.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt). - python scripts/trace_demo.py [--base-url http://localhost:8080] [--output evidence/trace-demo.txt] + python scripts/trace_demo.py [--base-url https://localhost:8443] [--output evidence/trace-demo.txt] 1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C `traceparent` header (trace id chosen here) and X-Request-Id; @@ -36,13 +36,13 @@ def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes data = json.dumps(body).encode() h["Content-Type"] = "application/json" request = urllib.request.Request(base + path, data=data, method=method, headers=h) - with urllib.request.urlopen(request, timeout=30) as response: + with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response: return response.status, response.headers, json.loads(response.read() or b"null") def main() -> int: parser = argparse.ArgumentParser() - parser.add_argument("--base-url", default="http://localhost:8080") + parser.add_argument("--base-url", default="https://localhost:8443") parser.add_argument("--output") args = parser.parse_args() base = args.base_url.rstrip("/") + "/api/v1" diff --git a/src/messenger/broker.py b/src/messenger/broker.py index 524d3c7..b14e061 100644 --- a/src/messenger/broker.py +++ b/src/messenger/broker.py @@ -21,6 +21,7 @@ from __future__ import annotations import datetime as dt import json import re +import ssl import uuid EXCHANGE = "messenger.jobs" @@ -28,6 +29,15 @@ QUEUE = "messenger.attachment-jobs" DLX = "messenger.jobs.dlx" DLQ = "messenger.attachment-jobs.dlq" ROUTING_KEY = "attachment.process.v1" + + +def ssl_context(settings) -> ssl.SSLContext | None: + """Lab 7: amqps:// -> TLS context that verifies the broker (internal CA + hostname `broker`). + A plain amqp:// URL gets None and is refused by the broker anyway (its TCP listener is off).""" + if not settings.broker_url.startswith("amqps://"): + return None + from .tls import client_context + return client_context(settings.tls_ca_file) JOB_TYPE = "attachment.process.v1" MAX_MESSAGE_BYTES = 4096 diff --git a/src/messenger/config.py b/src/messenger/config.py index c7752e7..3516f20 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -157,6 +157,9 @@ class Settings: # Lab 7: TLS of the API listener (mTLS, src/messenger/tls.py) and the loopback health port. tls_cert_file: str = "" tls_key_file: str = "" + # CA that every OUTGOING TLS connection verifies the server with (internal CA): S3, Valkey, + # RabbitMQ (PostgreSQL: sslrootcert in DATABASE_URL, OTLP: OTEL_EXPORTER_OTLP_CERTIFICATE). + tls_ca_file: str = "" tls_client_ca_file: str = "" health_port: int = 0 @@ -307,6 +310,7 @@ def s3_settings(*, credentials_required: bool = True) -> dict: janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0), fault_points=faults, fault_values=fault_values, + tls_ca_file=_path("TLS_CA_FILE"), ) diff --git a/src/messenger/relay.py b/src/messenger/relay.py index cd397c6..59ef6e5 100644 --- a/src/messenger/relay.py +++ b/src/messenger/relay.py @@ -58,7 +58,7 @@ class Relay: async def connect(self) -> None: self.connection = await aio_pika.connect( - self.settings.broker_url, timeout=5, + self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings), client_properties={"connection_name": "relay@" + self.settings.instance_id}) self.lost = service.watch_connection(self.connection) # Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log). diff --git a/src/messenger/s3_bootstrap.py b/src/messenger/s3_bootstrap.py index d7f2e65..3cb1d74 100644 --- a/src/messenger/s3_bootstrap.py +++ b/src/messenger/s3_bootstrap.py @@ -18,6 +18,7 @@ from __future__ import annotations import asyncio import os +import ssl import sys import time import urllib.error @@ -36,8 +37,10 @@ def say(text: str) -> None: def anonymous_status(url: str) -> int: """HTTP status of an UNSIGNED request (what anyone on the network could do).""" + ca = os.environ.get("TLS_CA_FILE", "").strip() or None + context = ssl.create_default_context(cafile=ca) if url.startswith("https://") else None try: - with urllib.request.urlopen(url, timeout=3) as response: + with urllib.request.urlopen(url, timeout=3, context=context) as response: return response.status except urllib.error.HTTPError as exc: return exc.code diff --git a/src/messenger/sessions.py b/src/messenger/sessions.py index 53736e4..4804789 100644 --- a/src/messenger/sessions.py +++ b/src/messenger/sessions.py @@ -18,6 +18,7 @@ Two interchangeable stores (SESSION_STORE): from __future__ import annotations import asyncio +import ssl import datetime as dt import hashlib import json @@ -107,12 +108,18 @@ class ValkeySessionStore: def __init__(self, settings: Settings): self.timeout = settings.cache_timeout_seconds + tls = {} + if settings.cache_url.startswith("rediss://"): + # Lab 7: TLS to Valkey, server verified by the internal CA AND hostname (SAN valkey). + tls = {"ssl_ca_certs": settings.tls_ca_file or None, "ssl_cert_reqs": "required", + "ssl_check_hostname": True, "ssl_min_version": ssl.TLSVersion.TLSv1_2} self.client = Redis.from_url( settings.cache_url, socket_timeout=self.timeout, socket_connect_timeout=self.timeout, retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once decode_responses=False, + **tls, ) def _key(self, token: str) -> str: diff --git a/src/messenger/storage.py b/src/messenger/storage.py index 9c891d7..4672d9e 100644 --- a/src/messenger/storage.py +++ b/src/messenger/storage.py @@ -68,6 +68,7 @@ class Storage: self._region = settings.s3_region self._access_key = access_key or settings.s3_access_key_id self._secret_key = secret_key or settings.s3_secret_access_key + self._ca_file = settings.tls_ca_file self._config = AioConfig( connect_timeout=settings.s3_connect_timeout_seconds, read_timeout=settings.s3_timeout_seconds, @@ -86,7 +87,9 @@ class Storage: session = get_session() self._client = await self._stack.enter_async_context(session.create_client( "s3", endpoint_url=self._endpoint, region_name=self._region, - aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config)) + aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config, + # Lab 7: https endpoint, chain AND hostname verified against the internal CA only. + verify=self._ca_file or True)) async def close(self) -> None: if self._stack is not None: diff --git a/src/messenger/worker.py b/src/messenger/worker.py index 63e691e..fca419a 100644 --- a/src/messenger/worker.py +++ b/src/messenger/worker.py @@ -74,7 +74,7 @@ class Worker: # ---------------------------------------------------------------- broker async def connect(self) -> None: self.connection = await aio_pika.connect( - self.settings.broker_url, timeout=5, + self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings), client_properties={"connection_name": "worker@" + self.name}) self.lost = service.watch_connection(self.connection) self.channel = await self.connection.channel()