From f6882a77b47601129a459d0f3bcec59b33c2daef Mon Sep 17 00:00:00 2001 From: da1zy3r Date: Wed, 25 Nov 2026 12:55:15 +0300 Subject: [PATCH 1/2] Add 6 lab code --- .env.example | 16 + .gitattributes | 2 + Dockerfile | 24 + compose.yaml | 313 ++++++++ infra/grafana/dashboards/messenger.json | 716 ++++++++++++++++++ .../provisioning/dashboards/default.yaml | 7 + .../provisioning/datasources/sources.yaml | 41 + infra/nginx.conf | 38 + infra/otel/alerts.yaml | 28 + infra/otel/collector.yaml | 69 ++ infra/otel/loki.yaml | 37 + infra/otel/prometheus.yaml | 12 + infra/otel/tempo.yaml | 23 + infra/readiness.sh | 38 + infra/s3-bootstrap.sh | 9 + infra/s3-policy.json | 17 + migrations/001_initial.sql | 30 + migrations/002_history_version.sql | 1 + migrations/003_message_idempotency.sql | 9 + migrations/004_attachments.sql | 18 + migrations/005_attachment_jobs.sql | 23 + migrations/006_job_error.sql | 1 + migrations/007_queue_measurements.sql | 3 + migrations/008_trace_context.sql | 1 + requirements.txt | 23 + src/__init__.py | 0 src/__main__.py | 14 + src/admission.py | 21 + src/attachments.py | 88 +++ src/auth.py | 68 ++ src/cache.py | 40 + src/cleanup.py | 86 +++ src/database.py | 106 +++ src/dependencies.py | 31 + src/errors.py | 60 ++ src/image_processor.py | 122 +++ src/jobs.py | 199 +++++ src/limits.py | 99 +++ src/main.py | 55 ++ src/middleware.py | 43 ++ src/models.py | 109 +++ src/object_storage.py | 33 + src/routers/__init__.py | 0 src/routers/attachments.py | 90 +++ src/routers/auth.py | 34 + src/routers/chats.py | 49 ++ src/routers/health.py | 23 + src/routers/users.py | 19 + src/schemas/__init__.py | 0 src/schemas/chat.py | 35 + src/schemas/common.py | 17 + src/schemas/message.py | 39 + src/schemas/user.py | 34 + src/store.py | 229 ++++++ src/telemetry.py | 206 +++++ src/worker.py | 122 +++ 56 files changed, 3570 insertions(+) create mode 100644 .gitattributes create mode 100644 Dockerfile create mode 100644 compose.yaml create mode 100644 infra/grafana/dashboards/messenger.json create mode 100644 infra/grafana/provisioning/dashboards/default.yaml create mode 100644 infra/grafana/provisioning/datasources/sources.yaml create mode 100644 infra/nginx.conf create mode 100644 infra/otel/alerts.yaml create mode 100644 infra/otel/collector.yaml create mode 100644 infra/otel/loki.yaml create mode 100644 infra/otel/prometheus.yaml create mode 100644 infra/otel/tempo.yaml create mode 100644 infra/readiness.sh create mode 100644 infra/s3-bootstrap.sh create mode 100644 infra/s3-policy.json create mode 100644 migrations/001_initial.sql create mode 100644 migrations/002_history_version.sql create mode 100644 migrations/003_message_idempotency.sql create mode 100644 migrations/004_attachments.sql create mode 100644 migrations/005_attachment_jobs.sql create mode 100644 migrations/006_job_error.sql create mode 100644 migrations/007_queue_measurements.sql create mode 100644 migrations/008_trace_context.sql create mode 100644 requirements.txt create mode 100644 src/__init__.py create mode 100644 src/__main__.py create mode 100644 src/admission.py create mode 100644 src/attachments.py create mode 100644 src/auth.py create mode 100644 src/cache.py create mode 100644 src/cleanup.py create mode 100644 src/database.py create mode 100644 src/dependencies.py create mode 100644 src/errors.py create mode 100644 src/image_processor.py create mode 100644 src/jobs.py create mode 100644 src/limits.py create mode 100644 src/main.py create mode 100644 src/middleware.py create mode 100644 src/models.py create mode 100644 src/object_storage.py create mode 100644 src/routers/__init__.py create mode 100644 src/routers/attachments.py create mode 100644 src/routers/auth.py create mode 100644 src/routers/chats.py create mode 100644 src/routers/health.py create mode 100644 src/routers/users.py create mode 100644 src/schemas/__init__.py create mode 100644 src/schemas/chat.py create mode 100644 src/schemas/common.py create mode 100644 src/schemas/message.py create mode 100644 src/schemas/user.py create mode 100644 src/store.py create mode 100644 src/telemetry.py create mode 100644 src/worker.py diff --git a/.env.example b/.env.example index 2e9f054..4e32d2a 100644 --- a/.env.example +++ b/.env.example @@ -39,3 +39,19 @@ BAO_CACERT=/run/secrets/bao-ca.crt ARGON2_MEMORY_KIB=19456 ARGON2_ITERATIONS=2 ARGON2_PARALLELISM=1 + +# Settings for the application carried over from lab 6 (compose.yaml). +MAX_PENDING_ATTACHMENTS=64 +JOB_MEMORY_MB=768 +POSTGRES_DB=messenger +POSTGRES_USER=messenger +POSTGRES_PASSWORD=replace-with-local-password +CACHE_TTL_SECONDS=30 +MAX_REQUEST_BYTES=65536 +MAX_INFLIGHT=32 +MINIO_ROOT_USER=local-admin +MINIO_ROOT_PASSWORD=replace-with-admin-password +S3_ACCESS_KEY_ID=messenger-api +S3_SECRET_ACCESS_KEY=replace-with-api-password +OTEL_SDK_DISABLED=false +GRAFANA_ADMIN_PASSWORD=replace-with-grafana-password diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..49819eb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Shell scripts are mounted into Linux containers, including on Windows hosts. +*.sh text eol=lf diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..564995c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.12.8-slim-bookworm + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY src ./src +COPY migrations ./migrations + +RUN useradd --create-home --shell /usr/sbin/nologin appuser +USER appuser + +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:' + os.getenv('APP_PORT', '8080') + '/health/ready', timeout=2).read()" + +STOPSIGNAL SIGTERM +CMD ["python", "-m", "src"] diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..f16ee99 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,313 @@ +x-api: &api + image: mtusi2026lab7-api:local + pull_policy: never + dns_opt: + - timeout:1 + - attempts:1 + environment: &app-env + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + POSTGRES_HOST: postgres + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} + REDIS_URL: redis://redis:6379/0 + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + CACHE_TTL_SECONDS: ${CACHE_TTL_SECONDS:-30} + MAX_REQUEST_BYTES: ${MAX_REQUEST_BYTES:-65536} + MAX_INFLIGHT: ${MAX_INFLIGHT:-32} + S3_ENDPOINT: http://s3:9000 + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + MAX_PENDING_ATTACHMENTS: ${MAX_PENDING_ATTACHMENTS:-64} + BROKER_URL: redis://broker:6379/0 + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_MEMORY_MB: ${JOB_MEMORY_MB:-768} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 + OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} + networks: [backend] + cpus: 1.0 + mem_limit: 512m + stop_grace_period: 10s + +services: + broker: + image: redis:7.4.2-bookworm + command: [redis-server, --appendonly, 'yes', --appendfsync, always, --maxmemory, 128mb, --maxmemory-policy, noeviction] + volumes: + - broker_data:/data + networks: [backend] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 2s + timeout: 2s + retries: 30 + cpus: 0.5 + mem_limit: 256m + + dispatcher: + <<: *api + environment: + <<: *app-env + OTEL_SERVICE_NAME: messenger-dispatcher + command: [python, -m, src.jobs, dispatch] + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + broker: + condition: service_healthy + restart: unless-stopped + mem_limit: 128m + + worker: + <<: *api + environment: + <<: *app-env + OTEL_SERVICE_NAME: messenger-worker + command: [python, -m, src.worker] + init: true + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + broker: + condition: service_healthy + s3-init: + condition: service_completed_successfully + restart: unless-stopped + cpus: 2.0 + mem_limit: 2g + pids_limit: 64 + + api: + <<: *api + build: . + deploy: + replicas: 2 + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + s3-init: + condition: service_completed_successfully + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=1).read()"] + interval: 2s + timeout: 2s + start_period: 5s + retries: 2 + + migrate: + <<: *api + environment: + <<: *app-env + OTEL_SDK_DISABLED: 'true' + command: [python, -m, src.database] + healthcheck: + disable: true + restart: 'no' + depends_on: + postgres: + condition: service_healthy + + s3: + # RELEASE.2025-09-07T16-13-09Z, pinned by immutable image digest. + image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + command: [server, /data, --console-address, '127.0.0.1:9001'] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} + MINIO_BROWSER: 'off' + volumes: + - s3_data:/data + networks: [backend] + healthcheck: + test: [CMD, curl, -f, http://127.0.0.1:9000/minio/health/live] + interval: 2s + timeout: 2s + retries: 30 + cpus: 1.0 + mem_limit: 512m + + s3-init: + # The pinned server image also contains mc; no second image is needed. + image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + entrypoint: [sh, /bootstrap.sh] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} + volumes: + - ./infra/s3-bootstrap.sh:/bootstrap.sh:ro + - ./infra/s3-policy.json:/policy.json:ro + depends_on: + s3: + condition: service_healthy + networks: [backend] + restart: 'no' + cpus: 0.25 + mem_limit: 128m + + cleanup: + <<: *api + environment: + <<: *app-env + OTEL_SDK_DISABLED: 'true' + command: [python, -m, src.cleanup] + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + + nginx: + image: nginx:1.28.0-alpine + entrypoint: [sh, /etc/nginx/readiness.sh] + dns_opt: + - timeout:1 + - attempts:1 + ports: + - '127.0.0.1:${APP_PORT:-8080}:8080' + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + - ./infra/readiness.sh:/etc/nginx/readiness.sh:ro + networks: [edge, backend] + depends_on: + api: + condition: service_healthy + healthcheck: + test: [CMD-SHELL, 'wget -q -O /dev/null http://127.0.0.1:8080/health/ready'] + interval: 2s + timeout: 2s + retries: 3 + cpus: 0.5 + mem_limit: 128m + stop_grace_period: 10s + + postgres: + image: postgres:17.4-bookworm + environment: + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} + volumes: + - postgres_data:/var/lib/postgresql/data + networks: [backend] + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] + interval: 2s + timeout: 2s + retries: 30 + cpus: 1.0 + mem_limit: 512m + + redis: + image: redis:7.4.2-bookworm + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always", "--maxmemory", "128mb", "--maxmemory-policy", "noeviction"] + volumes: + - redis_data:/data + networks: [backend] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 2s + retries: 30 + cpus: 0.5 + mem_limit: 256m + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.136.0 + command: [--config=/etc/otel/collector.yaml] + volumes: + - ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro + networks: [backend] + mem_limit: 256m + cpus: 0.5 + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.6.0 + command: [--config.file=/etc/prometheus/prometheus.yaml, --storage.tsdb.retention.time=3d] + volumes: + - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro + - ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro + - prometheus_data:/prometheus + ports: ['127.0.0.1:9090:9090'] + networks: [edge, backend] + mem_limit: 512m + cpus: 0.5 + restart: unless-stopped + + loki: + image: grafana/loki:3.5.7 + command: [-config.file=/etc/loki/local.yaml] + volumes: + - ./infra/otel/loki.yaml:/etc/loki/local.yaml:ro + - loki_data:/loki + ports: ['127.0.0.1:3100:3100'] + networks: [edge, backend] + mem_limit: 384m + cpus: 0.5 + restart: unless-stopped + + tempo: + image: grafana/tempo:2.9.0 + command: [-config.file=/etc/tempo.yaml] + volumes: + - ./infra/otel/tempo.yaml:/etc/tempo.yaml:ro + - tempo_data:/var/tempo + ports: ['127.0.0.1:3200:3200'] + networks: [edge, backend] + mem_limit: 384m + cpus: 0.5 + restart: unless-stopped + + grafana: + image: grafana/grafana:12.2.0 + environment: + 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' + GF_ANALYTICS_CHECK_FOR_UPDATES: 'false' + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafana_data:/var/lib/grafana + ports: ['127.0.0.1:3000:3000'] + networks: [edge, backend] + mem_limit: 384m + cpus: 0.5 + restart: unless-stopped + +networks: + edge: + backend: + internal: true +volumes: + broker_data: + postgres_data: + redis_data: + s3_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..0bcd64d --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,716 @@ +{ + "uid": "messenger-lab6", + "title": "Messenger / Lab 6", + "schemaVersion": 41, + "version": 1, + "refresh": "5s", + "time": { + "from": "now-30m", + "to": "now" + }, + "tags": [ + "lab6" + ], + "panels": [ + { + "id": 1, + "title": "API requests / second", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 0, + "w": 12, + "h": 8 + }, + "description": "Business requests only; health probes are excluded.", + "targets": [ + { + "refId": "A", + "expr": "sum by (method,route) (rate(http_requests_total{service_name=\"messenger-api\"}[2m]))", + "legendFormat": "{{method}} {{route}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 2, + "title": "API server error ratio", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 0, + "w": 12, + "h": 8 + }, + "description": "5xx / all non-health requests, rolling 2m. 4xx are not server errors.", + "targets": [ + { + "refId": "A", + "expr": "messenger:http_error_ratio:2m", + "legendFormat": "5xx / all" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 3, + "title": "API duration p50 / p95 / p99", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 8, + "w": 12, + "h": 8 + }, + "description": "Quantiles from merged histogram buckets across API replicas. Never averages of per-instance percentiles.", + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.5, sum by (le) (rate(http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))", + "legendFormat": "p99" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 4, + "title": "Job attempts / second", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 8, + "w": 12, + "h": 8 + }, + "description": "One count per claimed attempt; failed includes retryable failures, skipped is a fenced attempt.", + "targets": [ + { + "refId": "A", + "expr": "sum by (outcome) (rate(jobs_processed_total[2m]))", + "legendFormat": "{{outcome}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 5, + "title": "Worker processing duration p50 / p95 / p99", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 16, + "w": 12, + "h": 8 + }, + "description": "Includes isolated image process and durable result check; excludes queue wait.", + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.5, sum by (le) (rate(job_duration_seconds_bucket[2m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(job_duration_seconds_bucket[2m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(job_duration_seconds_bucket[2m])))", + "legendFormat": "p99" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 6, + "title": "Time from accepted upload to ready", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 16, + "w": 12, + "h": 8 + }, + "description": "Database timestamps: durable attachment creation to ready update. Includes queue wait and retries; observed on successful attempts.", + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.5, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", + "legendFormat": "p99" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 7, + "title": "Durable queue depth", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 24, + "w": 12, + "h": 8 + }, + "description": "PostgreSQL queued attachments, including unpublished outbox/retries; excludes processing jobs.", + "targets": [ + { + "refId": "A", + "expr": "max(queue_depth)", + "legendFormat": "queued" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 8, + "title": "Oldest queued attachment age", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 24, + "w": 12, + "h": 8 + }, + "description": "Age since acceptance. A stale sample is not zero; check queue sample age below.", + "targets": [ + { + "refId": "A", + "expr": "max(queue_oldest_age_seconds)", + "legendFormat": "age" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 9, + "title": "DB pool used / acquiring", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 32, + "w": 12, + "h": 8 + }, + "description": "Per long-lived process. Acquiring includes connection creation and pool wait; max pool size is 10.", + "targets": [ + { + "refId": "A", + "expr": "db_pool_used", + "legendFormat": "{{service_name}} {{service_instance_id}} used" + }, + { + "refId": "B", + "expr": "db_pool_waiting", + "legendFormat": "{{service_name}} {{service_instance_id}} acquiring" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 10, + "title": "Worker saturation", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 32, + "w": 12, + "h": 8 + }, + "description": "Busy consumers / configured concurrency. Missing capacity after 30s indicates stopped worker.", + "targets": [ + { + "refId": "A", + "expr": "sum(worker_busy)", + "legendFormat": "busy" + }, + { + "refId": "B", + "expr": "sum(worker_capacity)", + "legendFormat": "capacity" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 11, + "title": "Container memory (includes image children)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 40, + "w": 12, + "h": 8 + }, + "description": "cgroup v2 memory.current. Includes child processes and charged cache.", + "targets": [ + { + "refId": "A", + "expr": "container_memory_bytes", + "legendFormat": "{{service_name}} {{service_instance_id}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 12, + "title": "Container CPU", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 40, + "w": 12, + "h": 8 + }, + "description": "cgroup v2 CPU seconds / second; 1.0 is one fully used CPU core.", + "targets": [ + { + "refId": "A", + "expr": "rate(container_cpu_seconds_total[2m])", + "legendFormat": "{{service_name}} {{service_instance_id}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 13, + "title": "API availability SLI / SLO", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 48, + "w": 12, + "h": 8 + }, + "description": "Target: >=99% non-5xx business requests in a rolling 30m window. No traffic is not evidence that SLO is met.", + "targets": [ + { + "refId": "A", + "expr": "1 - ((sum(increase(http_requests_total{service_name=\"messenger-api\",status_class=\"5xx\"}[30m])) or vector(0)) / clamp_min(sum(increase(http_requests_total{service_name=\"messenger-api\"}[30m])), 1))", + "legendFormat": "SLI over 30m" + }, + { + "refId": "B", + "expr": "vector(0.99)", + "legendFormat": "SLO" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 14, + "title": "Local alerts", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 48, + "w": 12, + "h": 8 + }, + "description": "1 means pending/firing. Series disappears after resolution. Rules and runbooks are stored in infra/otel.", + "targets": [ + { + "refId": "A", + "expr": "ALERTS{alertname=~\"ApiHighErrorRate|QueueLagHigh\"}", + "legendFormat": "{{alertname}} {{alertstate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 15, + "title": "Collector memory", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 56, + "w": 12, + "h": 8 + }, + "description": "", + "targets": [ + { + "refId": "A", + "expr": "otelcol_process_memory_rss_bytes", + "legendFormat": "RSS" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 16, + "title": "Collector exporter queue / capacity", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 56, + "w": 12, + "h": 8 + }, + "description": "Bounded queues: 32 batches per backend, up to 256 records per batch.", + "targets": [ + { + "refId": "A", + "expr": "otelcol_exporter_queue_size", + "legendFormat": "{{exporter}} queued" + }, + { + "refId": "B", + "expr": "otelcol_exporter_queue_capacity", + "legendFormat": "{{exporter}} capacity" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 17, + "title": "Collector failed sends / rejected enqueue", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 64, + "w": 12, + "h": 8 + }, + "description": "Send failures may include retries, not unique lost spans. Exact experiment loss is measured by accepted/sent deltas after draining.", + "targets": [ + { + "refId": "A", + "expr": "rate(otelcol_exporter_send_failed_spans_total[2m])", + "legendFormat": "{{exporter}} span send failures" + }, + { + "refId": "B", + "expr": "rate(otelcol_exporter_send_failed_log_records_total[2m])", + "legendFormat": "{{exporter}} log send failures" + }, + { + "refId": "C", + "expr": "rate(otelcol_exporter_enqueue_failed_spans_total[2m])", + "legendFormat": "{{exporter}} span queue rejections" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 18, + "title": "Queue sample age", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 64, + "w": 12, + "h": 8 + }, + "description": "Above 15s: queue measurements are stale (e.g. DB outage).", + "targets": [ + { + "refId": "A", + "expr": "time() - max(queue_sample_timestamp_seconds)", + "legendFormat": "seconds since DB sample" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + } + ], + "links": [ + { + "title": "Explore logs", + "url": "/explore?left=%7B%22datasource%22%3A%22loki%22%7D" + }, + { + "title": "Explore traces", + "url": "/explore?left=%7B%22datasource%22%3A%22tempo%22%7D" + } + ] +} diff --git a/infra/grafana/provisioning/dashboards/default.yaml b/infra/grafana/provisioning/dashboards/default.yaml new file mode 100644 index 0000000..5be8c9d --- /dev/null +++ b/infra/grafana/provisioning/dashboards/default.yaml @@ -0,0 +1,7 @@ +apiVersion: 1 +providers: + - name: messenger + folder: Lab 6 + type: file + options: + path: /var/lib/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/sources.yaml b/infra/grafana/provisioning/datasources/sources.yaml new file mode 100644 index 0000000..2a3dc75 --- /dev/null +++ b/infra/grafana/provisioning/datasources/sources.yaml @@ -0,0 +1,41 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + jsonData: + timeInterval: 5s + exemplarTraceIdDestinations: + - name: trace_id + datasourceUid: tempo + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + jsonData: + derivedFields: + - name: trace_id + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: '$${__value.raw}' + urlDisplayLabel: View trace + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: '-5m' + spanEndTimeShift: '5m' + tags: [{key: service.name, value: service_name}] + filterByTraceID: true + filterBySpanID: false + nodeGraph: + enabled: true diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 0000000..1cc308b --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,38 @@ +worker_processes 1; +worker_shutdown_timeout 8s; +events { worker_connections 1024; } +http { + upstream messenger { + zone messenger 64k; + include /etc/nginx/ready-backends.conf; + } + log_format upstream '$request_method $uri $status upstream=$upstream_addr ' + 'upstream_status=$upstream_status time=$request_time'; + access_log /var/log/nginx/access.log upstream; + server { + listen 8080; + # API enforces the byte limit and returns the contracted JSON error. + client_max_body_size 0; + client_body_timeout 5s; + client_header_timeout 5s; + keepalive_timeout 5s; + location / { + proxy_pass http://messenger; + proxy_http_version 1.1; + proxy_request_buffering off; + proxy_buffering off; + proxy_set_header Host $host; + proxy_set_header Connection close; + proxy_connect_timeout 1s; + proxy_send_timeout 35s; + proxy_read_timeout 120s; + # A 503 is an API response (for example, S3 is unavailable), so + # preserve it for the client instead of marking every replica down. + proxy_next_upstream error timeout http_502 http_504; + proxy_next_upstream_tries 2; + proxy_next_upstream_timeout 8s; + # Never transparently retry a POST already sent to an API. + # A client retries messages using the original Idempotency-Key. + } + } +} diff --git a/infra/otel/alerts.yaml b/infra/otel/alerts.yaml new file mode 100644 index 0000000..b4701d9 --- /dev/null +++ b/infra/otel/alerts.yaml @@ -0,0 +1,28 @@ +groups: + - name: messenger + rules: + - record: messenger:http_error_ratio:2m + expr: | + (sum(rate(http_requests_total{service_name="messenger-api",status_class="5xx"}[2m])) or vector(0)) + / clamp_min(sum(rate(http_requests_total{service_name="messenger-api"}[2m])), 0.001) + - alert: ApiHighErrorRate + expr: messenger:http_error_ratio:2m > 0.05 and sum(increase(http_requests_total{service_name="messenger-api"}[2m])) >= 20 + for: 20s + labels: + severity: warning + annotations: + summary: 'API: more than 5% server errors over 2 minutes' + description: 'SLI is 5xx / all non-health requests. At least 20 requests in the window.' + runbook: 'infra/otel/README.md#api-errors' + - alert: QueueLagHigh + expr: | + max(queue_oldest_age_seconds) > 30 + and max(queue_depth) > 0 + and time() - max(queue_sample_timestamp_seconds) < 15 + for: 15s + labels: + severity: warning + annotations: + summary: 'Oldest queued attachment waits more than 30 seconds' + description: 'Check worker capacity/busy and job errors; backlog is sampled by dispatcher.' + runbook: 'infra/otel/README.md#queue-lag' diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..529a107 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,69 @@ +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + batch: + timeout: 1s + send_batch_size: 128 + send_batch_max_size: 256 + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_to_telemetry_conversion: + enabled: true + enable_open_metrics: true + metric_expiration: 30s + translation_strategy: UnderscoreEscapingWithSuffixes + otlphttp/loki: + endpoint: http://loki:3100/otlp + timeout: 2s + sending_queue: + queue_size: 32 + num_consumers: 2 + block_on_overflow: false + retry_on_failure: + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + otlphttp/tempo: + endpoint: http://tempo:4318 + timeout: 2s + sending_queue: + queue_size: 32 + num_consumers: 2 + block_on_overflow: false + retry_on_failure: + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + +service: + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] diff --git a/infra/otel/loki.yaml b/infra/otel/loki.yaml new file mode 100644 index 0000000..b5cf04f --- /dev/null +++ b/infra/otel/loki.yaml @@ -0,0 +1,37 @@ +auth_enabled: false +server: + http_listen_port: 3100 +common: + path_prefix: /loki + replication_factor: 1 + ring: + kvstore: + store: inmemory + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules +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: 72h + otlp_config: + resource_attributes: + ignore_defaults: true + attributes_config: + - action: index_label + attributes: [service.name, deployment.environment.name] +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem +analytics: + reporting_enabled: false diff --git a/infra/otel/prometheus.yaml b/infra/otel/prometheus.yaml new file mode 100644 index 0000000..5613d18 --- /dev/null +++ b/infra/otel/prometheus.yaml @@ -0,0 +1,12 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s +rule_files: + - /etc/prometheus/alerts.yaml +scrape_configs: + - job_name: messenger + static_configs: + - targets: ['otel-collector:8889'] + - job_name: collector + static_configs: + - targets: ['otel-collector:8888'] diff --git a/infra/otel/tempo.yaml b/infra/otel/tempo.yaml new file mode 100644 index 0000000..9653bf2 --- /dev/null +++ b/infra/otel/tempo.yaml @@ -0,0 +1,23 @@ +server: + http_listen_port: 3200 +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 +ingester: + trace_idle_period: 10s + max_block_duration: 5m +compactor: + compaction: + block_retention: 72h +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks +usage_report: + reporting_enabled: false diff --git a/infra/readiness.sh b/infra/readiness.sh new file mode 100644 index 0000000..9a2e627 --- /dev/null +++ b/infra/readiness.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Only ready API addresses enter the upstream, including at nginx startup. +update_backends() { + next=/etc/nginx/ready-backends.conf.next + : > "$next" + for address in $(getent ahostsv4 api | awk '{print $1}' | sort -u); do + if wget -q -T 1 -O /dev/null "http://$address:8080/health/ready"; then + echo "server $address:8080;" >> "$next" + fi + done + # If every running API temporarily loses a shared dependency (for example + # S3), retain the last addresses. The API can then return the contracted + # 503 instead of Nginx replacing it with a 502. At initial startup there + # is no previous healthy set, so use an inert placeholder. + if [ ! -s "$next" ]; then + if [ -s /etc/nginx/ready-backends.conf ] && ! grep -q '127.0.0.1:9 down' /etc/nginx/ready-backends.conf; then + rm -f "$next" + return + fi + echo 'server 127.0.0.1:9 down;' > "$next" + fi + if ! cmp -s "$next" /etc/nginx/ready-backends.conf; then + mv "$next" /etc/nginx/ready-backends.conf + if [ "${1:-}" = reload ] && [ -f /var/run/nginx.pid ]; then + nginx -s reload + fi + else + rm -f "$next" + fi +} + +update_backends +( + while sleep 2; do + update_backends reload + done +) & +exec nginx -g 'daemon off;' diff --git a/infra/s3-bootstrap.sh b/infra/s3-bootstrap.sh new file mode 100644 index 0000000..c0baf62 --- /dev/null +++ b/infra/s3-bootstrap.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +test "$MINIO_ROOT_USER" != "$S3_ACCESS_KEY_ID" +mc alias set local http://s3:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null +mc mb --ignore-existing local/messenger-attachments +mc anonymous set none local/messenger-attachments +mc admin user add local "$S3_ACCESS_KEY_ID" "$S3_SECRET_ACCESS_KEY" >/dev/null +mc admin policy info local attachments >/dev/null 2>&1 || mc admin policy create local attachments /policy.json +mc admin policy attach local attachments --user "$S3_ACCESS_KEY_ID" diff --git a/infra/s3-policy.json b/infra/s3-policy.json new file mode 100644 index 0000000..8e77546 --- /dev/null +++ b/infra/s3-policy.json @@ -0,0 +1,17 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:ListBucket", "s3:GetBucketLocation"], + "Resource": ["arn:aws:s3:::messenger-attachments"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::messenger-attachments/originals/*", + "arn:aws:s3:::messenger-attachments/staging/*", + "arn:aws:s3:::messenger-attachments/variants/*"] + } + ] +} diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..aee31d8 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,30 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); +CREATE INDEX chats_order_idx ON chats (created_at, id); diff --git a/migrations/002_history_version.sql b/migrations/002_history_version.sql new file mode 100644 index 0000000..7b7972c --- /dev/null +++ b/migrations/002_history_version.sql @@ -0,0 +1 @@ +ALTER TABLE chats ADD COLUMN history_version bigint NOT NULL DEFAULT 0; diff --git a/migrations/003_message_idempotency.sql b/migrations/003_message_idempotency.sql new file mode 100644 index 0000000..434b1e2 --- /dev/null +++ b/migrations/003_message_idempotency.sql @@ -0,0 +1,9 @@ +-- Additive migration: no rewrite of existing lab2 tables or messages. +CREATE TABLE message_idempotency ( + actor_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (actor_id, chat_id, key) +); diff --git a/migrations/004_attachments.sql b/migrations/004_attachments.sql new file mode 100644 index 0000000..77317cf --- /dev/null +++ b/migrations/004_attachments.sql @@ -0,0 +1,18 @@ +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users(id), + object_key text NOT NULL UNIQUE, + filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255), + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX attachments_chat_idx ON attachments(chat_id); + +ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}'; +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CHECK (char_length(text) <= 4000); +ALTER TABLE messages ADD CHECK (length(btrim(text)) > 0 OR cardinality(attachment_ids) > 0); +ALTER TABLE messages ADD CHECK (cardinality(attachment_ids) <= 10); diff --git a/migrations/005_attachment_jobs.sql b/migrations/005_attachment_jobs.sql new file mode 100644 index 0000000..1e5e88c --- /dev/null +++ b/migrations/005_attachment_jobs.sql @@ -0,0 +1,23 @@ +ALTER TABLE attachments + ADD COLUMN updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + ADD COLUMN status text NOT NULL DEFAULT 'ready' + CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + ADD COLUMN staging_key text, + ADD COLUMN variants jsonb NOT NULL DEFAULT '[]', + ADD COLUMN error_code text; +ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued'; + +CREATE TABLE attachment_jobs ( + id uuid PRIMARY KEY, + attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), + pipeline_version bigint NOT NULL DEFAULT 1 CHECK (pipeline_version = 1), + attempt bigint NOT NULL DEFAULT 0, + failures bigint NOT NULL DEFAULT 0, + available_at timestamptz NOT NULL DEFAULT now(), + published_at timestamptz, + lease_until timestamptz, + lease_token uuid, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + replay_audit jsonb NOT NULL DEFAULT '[]' +); +CREATE INDEX attachment_jobs_due_idx ON attachment_jobs(available_at); diff --git a/migrations/006_job_error.sql b/migrations/006_job_error.sql new file mode 100644 index 0000000..f721d2e --- /dev/null +++ b/migrations/006_job_error.sql @@ -0,0 +1 @@ +ALTER TABLE attachment_jobs ADD COLUMN last_error text; diff --git a/migrations/007_queue_measurements.sql b/migrations/007_queue_measurements.sql new file mode 100644 index 0000000..1c57b13 --- /dev/null +++ b/migrations/007_queue_measurements.sql @@ -0,0 +1,3 @@ +ALTER TABLE attachment_jobs ADD COLUMN first_started_at timestamptz; +CREATE INDEX attachments_pending_idx ON attachments(status) + WHERE status IN ('queued', 'processing'); diff --git a/migrations/008_trace_context.sql b/migrations/008_trace_context.sql new file mode 100644 index 0000000..28c6fe5 --- /dev/null +++ b/migrations/008_trace_context.sql @@ -0,0 +1 @@ +ALTER TABLE attachment_jobs ADD COLUMN trace_context jsonb NOT NULL DEFAULT '{}'; diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..01c2cf2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +fastapi==0.115.6 +uvicorn==0.34.0 +pydantic==2.13.5 +starlette==0.41.3 +annotated-types==0.8.0 +anyio==4.15.1 +click==8.5.0 +colorama==0.4.6; sys_platform == "win32" +h11==0.16.0 +idna==3.20 +pydantic_core==2.46.5 +typing-inspection==0.4.4 +typing_extensions==4.16.0 +psycopg[binary]==3.2.6 +SQLAlchemy==2.0.41 +redis==5.2.1 +argon2-cffi==23.1.0 +boto3==1.40.70 +Pillow==12.0.0 +opentelemetry-api==1.38.0 +opentelemetry-sdk==1.38.0 +opentelemetry-exporter-otlp-proto-http==1.38.0 +psutil==7.1.2 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/__main__.py b/src/__main__.py new file mode 100644 index 0000000..6846b7f --- /dev/null +++ b/src/__main__.py @@ -0,0 +1,14 @@ +import os + +import uvicorn + + +if __name__ == '__main__': + uvicorn.run( + 'src.main:app', + host=os.getenv('APP_HOST', '0.0.0.0'), + port=int(os.getenv('APP_PORT', '8080')), + workers=1, + access_log=False, # Structured logs use route templates, never query strings. + timeout_graceful_shutdown=5, + ) diff --git a/src/admission.py b/src/admission.py new file mode 100644 index 0000000..6b76e99 --- /dev/null +++ b/src/admission.py @@ -0,0 +1,21 @@ +"""A shared admission limit for unfinished attachments across all API replicas.""" +import os + +from sqlalchemy import func, select + +from .errors import APIError +from .models import Attachment + +MAX_PENDING = int(os.getenv('MAX_PENDING_ATTACHMENTS', '64')) +if MAX_PENDING < 1: + raise ValueError('MAX_PENDING_ATTACHMENTS must be positive') + + +def reserve_capacity(session): + # Keep the lock until the new queued row commits. Counting without this lock + # would allow simultaneous uploads on different replicas to exceed the limit. + session.execute(select(func.pg_advisory_xact_lock(202605))) + count = session.scalar(select(func.count()).select_from(Attachment).where( + Attachment.status.in_(['queued', 'processing']))) + if count >= MAX_PENDING: + raise APIError(429, 'rate_limited', 'Очередь обработки заполнена; повторите загрузку позже') diff --git a/src/attachments.py b/src/attachments.py new file mode 100644 index 0000000..aa85a58 --- /dev/null +++ b/src/attachments.py @@ -0,0 +1,88 @@ +import os +import unicodedata +from uuid import uuid4 + +from PIL import Image, UnidentifiedImageError +from sqlalchemy import func, select + +from .errors import APIError +from .admission import reserve_capacity +from .models import Attachment, AttachmentJob, ChatMember +from .object_storage import BUCKET, PREFIX, s3_client +from .store import ensure_uuid, serialize, store +from .telemetry import carrier + +MAX_BYTES = min(int(os.getenv('MAX_UPLOAD_BYTES', '10485760')), 10485760) +MAX_PIXELS = min(int(os.getenv('MAX_IMAGE_PIXELS', '40000000')), 40000000) +if MAX_BYTES < 1 or MAX_PIXELS < 1: + raise ValueError('Upload limits must be positive') + + +def validate_filename(filename): + if (not filename or not filename.strip() or len(filename) > 255 + or any(c in '/\\' or unicodedata.category(c) == 'Cc' for c in filename)): + raise APIError(400, 'invalid_request', 'Неверное имя файла') + + +def validate_image(source, content_type): + try: + source.seek(0) + with Image.open(source, formats=['PNG', 'JPEG']) as picture: + if picture.width * picture.height > MAX_PIXELS: + raise APIError(413, 'payload_too_large', 'Слишком много пикселей') + if Image.MIME[picture.format] != content_type: + raise APIError(415, 'unsupported_media_type', 'Тип изображения не совпадает с Content-Type') + picture.verify() + source.seek(0) + with Image.open(source, formats=['PNG', 'JPEG']) as picture: + picture.load() # verify alone does not decode JPEG or detect truncated pixel data. + except Image.DecompressionBombError as exc: + raise APIError(413, 'payload_too_large', 'Слишком много пикселей') from exc + except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc: + raise APIError(415, 'unsupported_media_type', 'Повреждённое изображение') from exc + source.seek(0) + + +def lock_object(session, key): + # Shared by upload and cleanup: no deletion while a COMMIT is in flight. + session.execute(select(func.pg_advisory_xact_lock(func.hashtextextended(key, 0)))) + + +def metadata(attachment): + result = serialize(attachment, 'id', 'chat_id', 'owner_id', 'filename', + 'content_type', 'size_bytes', 'sha256', 'created_at', + 'updated_at', 'status', 'error_code') + return {**result, 'variants': [{k: v for k, v in item.items() if k != 'object_key'} + for item in attachment.variants]} + + +def save_attachment(source, chat_id, actor_id, filename, content_type, size, digest): + validate_image(source, content_type) + attachment_id = str(uuid4()) + key = PREFIX + attachment_id + staging_key = 'staging/' + attachment_id + with store.sessions.begin() as session: + store._chat(session, chat_id, actor_id) + reserve_capacity(session) + lock_object(session, staging_key) + s3_client().put_object(Bucket=BUCKET, Key=staging_key, Body=source, + ContentLength=size, ContentType=content_type) + attachment = Attachment(id=attachment_id, chat_id=chat_id, owner_id=actor_id, + object_key=key, filename=filename, content_type=content_type, + size_bytes=size, sha256=digest, staging_key=staging_key) + session.add(attachment) + session.flush() + session.add(AttachmentJob(attachment_id=attachment_id, trace_context=carrier())) + result = metadata(attachment) + # An uncertain COMMIT is not followed by DELETE: cleanup checks the DB later. + return result + + +def get_attachment(attachment_id, actor_id): + with store.sessions() as session: + attachment = session.scalar(select(Attachment).join( + ChatMember, ChatMember.chat_id == Attachment.chat_id).where( + Attachment.id == ensure_uuid(attachment_id), ChatMember.user_id == actor_id)) + if attachment is None: + raise APIError(404, 'not_found', 'Объект не найден') + return attachment diff --git a/src/auth.py b/src/auth.py new file mode 100644 index 0000000..ab93a9f --- /dev/null +++ b/src/auth.py @@ -0,0 +1,68 @@ +import hashlib +import json +import os +import re +import secrets +from datetime import datetime, timedelta, timezone + +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError +from redis import Redis + +from .errors import APIError + +password_hasher = PasswordHasher() +dummy_hash = password_hasher.hash(secrets.token_urlsafe(32)) + + +def verify_password(encoded, password): + try: + return password_hasher.verify(encoded or dummy_hash, password) and encoded is not None + except VerificationError: + return False + + +def unauthorized(): + return APIError(401, 'unauthorized', 'Нет действительной идентификации') + + +class Sessions: + def __init__(self): + self.client = Redis.from_url( + os.getenv('REDIS_URL', 'redis://redis:6379/0'), decode_responses=True, + socket_connect_timeout=1, socket_timeout=1, max_connections=20, + retry_on_timeout=False, + ) + self.ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600')) + if self.ttl < 1: + raise ValueError('SESSION_TTL_SECONDS must be positive') + + @staticmethod + def key(token): + if not re.fullmatch(r'[A-Za-z0-9_-]{43}', token): + raise unauthorized() + return 'session:' + hashlib.sha256(token.encode('ascii')).hexdigest() + + def create(self, user): + token = secrets.token_urlsafe(32) + expires = datetime.now(timezone.utc) + timedelta(seconds=self.ttl) + expires_at = expires.isoformat(timespec='microseconds').replace('+00:00', 'Z') + self.client.set(self.key(token), json.dumps({'user_id': user['id'], 'expires_at': expires_at}), + pxat=int(expires.timestamp() * 1000)) + return {'token': token, 'token_type': 'Bearer', 'expires_at': expires_at, 'user': user} + + def user_id(self, token): + raw = self.client.get(self.key(token)) + if raw is None: + raise unauthorized() + session = json.loads(raw) + if datetime.fromisoformat(session['expires_at'].replace('Z', '+00:00')) <= datetime.now(timezone.utc): + raise unauthorized() + return session['user_id'] + + def delete(self, token): + if not self.client.delete(self.key(token)): + raise unauthorized() + + +sessions = Sessions() diff --git a/src/cache.py b/src/cache.py new file mode 100644 index 0000000..bde2077 --- /dev/null +++ b/src/cache.py @@ -0,0 +1,40 @@ +"""History pages are disposable; PostgreSQL owns both data and their version.""" +import hashlib +import json +import os + +from redis.exceptions import RedisError + +from .auth import sessions + + +class HistoryCache: + def __init__(self, client, ttl=30, prefix='history'): + self.client = client + self.ttl = ttl + self.prefix = prefix + if ttl < 1: + raise ValueError('CACHE_TTL_SECONDS must be positive') + + def key(self, chat_id, version, limit, after): + page = json.dumps([limit, after], separators=(',', ':')) + digest = hashlib.sha256(page.encode()).hexdigest() + return f'{self.prefix}:{chat_id}:{version}:{digest}' + + def get_or_load(self, chat_id, version, limit, after, load): + key = self.key(chat_id, version, limit, after) + try: + cached = self.client.get(key) + except RedisError: + return load() + if cached is not None: + return json.loads(cached) + page = load() + try: + self.client.set(key, json.dumps(page, ensure_ascii=False), ex=self.ttl) + except RedisError: + pass + return page + + +history_cache = HistoryCache(sessions.client, int(os.getenv('CACHE_TTL_SECONDS', '30')), prefix='history-v4') diff --git a/src/cleanup.py b/src/cleanup.py new file mode 100644 index 0000000..0d5eeb3 --- /dev/null +++ b/src/cleanup.py @@ -0,0 +1,86 @@ +"""Remove old S3 objects without committed metadata. Never delete on a DB error.""" +import argparse +import logging +import os +import time +from datetime import datetime, timedelta, timezone + +from sqlalchemy import select +from sqlalchemy.orm import sessionmaker + +from .attachments import lock_object +from .database import create_db_engine +from .models import Attachment +from .object_storage import BUCKET, s3_client + +GRACE = timedelta(seconds=max(1, int(os.getenv('STAGING_RETENTION_SECONDS', '86400')))) + + +def cleanup(sessions, client, now=None): + cutoff = (now or datetime.now(timezone.utc)) - GRACE + deleted = 0 + for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET): + for obj in page.get('Contents', []): + key = obj['Key'] + if not key.startswith(('staging/', 'originals/', 'variants/')): + continue + with sessions.begin() as session: + lock_object(session, key) + if key.startswith('staging/'): + attachment = session.scalar(select(Attachment).where( + Attachment.staging_key == key).with_for_update()) + if attachment: + if attachment.status in ('queued', 'processing'): + continue + if attachment.status == 'failed' and attachment.updated_at >= cutoff: + continue + client.delete_object(Bucket=BUCKET, Key=key) + attachment.staging_key = None + deleted += 1 + continue + else: + # All final keys belong to a server-generated attachment UUID. + from uuid import UUID + try: + attachment_id = str(UUID(key.split('/')[1])) + except (ValueError, IndexError): + continue + attachment = session.get(Attachment, attachment_id, with_for_update=True) + if attachment: + if attachment.status != 'failed' or attachment.updated_at >= cutoff: + continue + client.delete_object(Bucket=BUCKET, Key=key) + deleted += 1 + continue + # Recheck age after taking the same lock as the uploader. + if client.head_object(Bucket=BUCKET, Key=key)['LastModified'] >= cutoff: + continue + client.delete_object(Bucket=BUCKET, Key=key) + deleted += 1 + return deleted + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--once', action='store_true') + args = parser.parse_args() + logging.basicConfig(level=logging.INFO) + engine = create_db_engine() + try: + while True: + try: + count = cleanup(sessionmaker(engine), s3_client()) + logging.info('Cleanup completed: deleted=%d', count) + except Exception as exc: + logging.error('Cleanup deferred: %s', type(exc).__name__) + if args.once: + raise SystemExit(1) from None + if args.once: + break + time.sleep(60) + finally: + engine.dispose() + + +if __name__ == '__main__': + main() diff --git a/src/database.py b/src/database.py new file mode 100644 index 0000000..0c0fda4 --- /dev/null +++ b/src/database.py @@ -0,0 +1,106 @@ +import os +from pathlib import Path + +from sqlalchemy import create_engine, event, func, insert, select +from sqlalchemy.engine import URL, make_url +from sqlalchemy.pool import QueuePool +from threading import Lock + +from . import telemetry as otel + +from .models import SchemaMigration + + +def database_url(): + if os.getenv('DATABASE_URL'): + url = make_url(os.environ['DATABASE_URL']) + if url.drivername in ('postgres', 'postgresql'): + url = url.set(drivername='postgresql+psycopg') + if url.drivername != 'postgresql+psycopg': + raise ValueError('DATABASE_URL must use PostgreSQL with psycopg') + return url + return URL.create( + 'postgresql+psycopg', host=os.getenv('POSTGRES_HOST', 'postgres'), + database=os.getenv('POSTGRES_DB', 'messenger'), + username=os.getenv('POSTGRES_USER', 'messenger'), + password=os.environ['POSTGRES_PASSWORD'], + ) + + +class ObservedPool(QueuePool): + """Count threads acquiring a connection, including pool wait and reconnect time.""" + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.waiting = 0 + self.wait_lock = Lock() + + def connect(self): + with self.wait_lock: + self.waiting += 1 + try: + with otel.dependency_span('db.acquire', **{'db.system': 'postgresql'}): + return super().connect() + finally: + with self.wait_lock: + self.waiting -= 1 + + +def create_db_engine(): + engine = create_engine( + database_url(), pool_size=10, max_overflow=0, pool_timeout=2, pool_pre_ping=True, + poolclass=ObservedPool, hide_parameters=True, + connect_args={'connect_timeout': 2, + 'options': '-c statement_timeout=3000 -c lock_timeout=2000'}, + ) + # Only operation names; SQL text, bound values and connection URLs are never exported. + @event.listens_for(engine, 'before_cursor_execute') + def before(conn, cursor, statement, parameters, context, executemany): + if not otel.trace.get_current_span().get_span_context().is_valid: + return + operation = statement.lstrip().split(None, 1)[0].upper() if statement.strip() else 'OTHER' + if operation not in {'SELECT', 'INSERT', 'UPDATE', 'DELETE'}: + operation = 'OTHER' + context.otel_span = otel.tracer.start_span('db.' + operation, + kind=otel.SpanKind.CLIENT, attributes={'db.system': 'postgresql', 'db.operation.name': operation}) + + @event.listens_for(engine, 'after_cursor_execute') + def after(conn, cursor, statement, parameters, context, executemany): + current = getattr(context, 'otel_span', None) + if current: + current.end() + + @event.listens_for(engine, 'handle_error') + def error(context): + current = getattr(context.execution_context, 'otel_span', None) + if current: + current.set_status(otel.Status(otel.StatusCode.ERROR)) + current.set_attribute('error.type', type(context.original_exception).__name__) + current.end() + otel.event('db_error', severity=otel.logging.ERROR, error_type=type(context.original_exception).__name__) + + if os.getenv('OTEL_CHILD_PROCESS') != 'true': + otel.meter.create_observable_gauge('db_pool_used', callbacks=[ + lambda _: [otel.metrics.Observation(engine.pool.checkedout())]]) + otel.meter.create_observable_gauge('db_pool_waiting', callbacks=[ + lambda _: [otel.metrics.Observation(engine.pool.waiting)]]) + return engine + + +def migrate(engine): + with engine.begin() as conn: + conn.execute(select(func.pg_advisory_xact_lock(202602))) + SchemaMigration.__table__.create(conn, checkfirst=True) + applied = set(conn.scalars(select(SchemaMigration.version))) + for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')): + if path.name not in applied: + conn.exec_driver_sql(path.read_text(encoding='utf-8')) + conn.execute(insert(SchemaMigration).values(version=path.name)) + + +if __name__ == '__main__': + engine = create_db_engine() + try: + migrate(engine) + print('Migrations applied') + finally: + engine.dispose() diff --git a/src/dependencies.py b/src/dependencies.py new file mode 100644 index 0000000..03aac92 --- /dev/null +++ b/src/dependencies.py @@ -0,0 +1,31 @@ +from typing import Optional + +from fastapi import Depends, Header, Query + +from .auth import sessions, unauthorized +from .errors import APIError +from .store import store + + +def page_limit(limit: str = Query(default="50")) -> int: + if not limit.isascii() or not limit.isdecimal() or len(limit) > 3: + raise APIError(400, "invalid_request", "Неверный limit") + number = int(limit) + if not 1 <= number <= 100: + raise APIError(400, "invalid_request", "Неверный limit") + return number + + + +def bearer_token(authorization: Optional[str] = Header(default=None)) -> str: + parts = (authorization or '').split() + if len(parts) != 2 or parts[0].lower() != 'bearer': + raise unauthorized() + return parts[1] + + +def current_user(token: str = Depends(bearer_token)) -> dict: + user = store.get_user(sessions.user_id(token)) + if user is None: + raise unauthorized() + return user diff --git a/src/errors.py b/src/errors.py new file mode 100644 index 0000000..d02425b --- /dev/null +++ b/src/errors.py @@ -0,0 +1,60 @@ +from fastapi import Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException +from .middleware import INSTANCE_ID + + +class APIError(Exception): + def __init__(self, status_code: int, code: str, message: str): + self.status_code = status_code + self.code = code + self.message = message + + +def error_response(request: Request, status_code: int, code: str, message: str) -> JSONResponse: + request_id = getattr(request.state, "request_id", "") + return JSONResponse( + status_code=status_code, + headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}, + content={ + "error": { + "code": code, + "message": message, + "request_id": request_id, + } + }, + ) + + +def api_error_handler(request: Request, exc: APIError) -> JSONResponse: + response = error_response(request, exc.status_code, exc.code, exc.message) + if exc.status_code == 429: + response.headers['Retry-After'] = '1' + if exc.status_code == 401: + response.headers['WWW-Authenticate'] = ( + 'Basic realm="messenger", charset="UTF-8"' + if request.url.path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"' + ) + return response + + +def dependency_error_handler(request: Request, exc: Exception) -> JSONResponse: + return error_response(request, 503, 'unavailable', 'Хранилище временно недоступно') + + +def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse: + return error_response(request, 400, "invalid_request", "Неверный запрос") + + +def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse: + if exc.status_code == 404: + return error_response(request, 404, "not_found", "Объект не найден") + if exc.status_code == 405: + return error_response(request, 400, "invalid_request", "Метод не поддерживается") + else: + return error_response(request, exc.status_code, "invalid_request", "Неверный запрос") + + +def internal_error_handler(request: Request, exc: Exception) -> JSONResponse: + return error_response(request, 500, "internal_error", "Внутренняя ошибка") diff --git a/src/image_processor.py b/src/image_processor.py new file mode 100644 index 0000000..8533d88 --- /dev/null +++ b/src/image_processor.py @@ -0,0 +1,122 @@ +"""One isolated process per attempt; quality: JPEG 85, WebP 80; no EXIF/ICC.""" +import hashlib +import io +import os +import sys + +from PIL import Image, ImageOps, UnidentifiedImageError +from sqlalchemy.orm import sessionmaker + +from .attachments import MAX_BYTES, MAX_PIXELS +from .database import create_db_engine +from .jobs import now +from .models import Attachment, AttachmentJob +from .object_storage import BUCKET, s3_client +from . import telemetry as otel + + +def fit_size(size, bound): + width, height = size + if max(size) <= bound: + return size + return max(1, width * bound // max(size)), max(1, height * bound // max(size)) + + +def variants(data): + with Image.open(io.BytesIO(data), formats=['PNG', 'JPEG']) as original: + if original.width * original.height > MAX_PIXELS: + raise ValueError('pixel limit') + original.load() + oriented = ImageOps.exif_transpose(original) + rgba = oriented.convert('RGBA') + rgb = Image.new('RGB', rgba.size, 'white') + rgb.paste(rgba, mask=rgba.getchannel('A')) + rgba.close() + oriented.close() + rgb.info.clear() + try: + for name, image, fmt, mime, quality in ( + ('thumbnail', rgb.resize(fit_size(rgb.size, 256), Image.Resampling.LANCZOS), 'JPEG', 'image/jpeg', 85), + ('crop', ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS), 'JPEG', 'image/jpeg', 85), + ('optimized', rgb.resize(fit_size(rgb.size, 1280), Image.Resampling.LANCZOS), 'WEBP', 'image/webp', 80), + ): + with image, io.BytesIO() as output: + image.save(output, format=fmt, quality=quality) + blob = output.getvalue() + yield {'name': name, 'content_type': mime, 'width': image.width, + 'height': image.height, 'size_bytes': len(blob), + 'sha256': hashlib.sha256(blob).hexdigest()}, blob + finally: + rgb.close() + + +def process(sessions, job_id, token): + with sessions() as session: + job = session.get(AttachmentJob, job_id) + if job.lease_token != token: + return + attachment = session.get(Attachment, job.attachment_id) + staging_key = attachment.staging_key + client = s3_client() + response = client.get_object(Bucket=BUCKET, Key=staging_key) + with response['Body'] as body: + data = body.read(MAX_BYTES + 1) + if len(data) != attachment.size_bytes or hashlib.sha256(data).hexdigest() != attachment.sha256: + raise ValueError('staging checksum mismatch') + try: + rendered = list(variants(data)) + except OSError as exc: + raise ValueError('invalid image') from exc + # Job lock fences the final writes, cleanup and publication against lease recovery. + # Work before this transaction is CPU-only. Keys are stable across retries. + with sessions.begin() as session: + job = session.get(AttachmentJob, job_id, with_for_update=True) + if job.lease_token != token or job.lease_until <= now(): + return + current = session.get(Attachment, job.attachment_id, with_for_update=True) + if current.status != 'processing': + return + client.put_object(Bucket=BUCKET, Key=current.object_key, Body=data, + ContentType=current.content_type) + saved = [] + for meta, blob in rendered: + key = f'variants/{current.id}/v{job.pipeline_version}/{meta["name"]}' + client.put_object(Bucket=BUCKET, Key=key, Body=blob, ContentType=meta['content_type']) + saved.append({**meta, 'object_key': key}) + # Test-only crash injection; never enabled by compose.yaml. + if os.getenv('JOB_FAULT') == 'after_objects': + os._exit(91) + current.variants = saved + current.status, current.error_code = 'ready', None + current.updated_at = now() + job.lease_token = job.lease_until = None + if os.getenv('JOB_FAULT') == 'after_commit': + os._exit(92) + + +def main(): + # Linux worker: bounded address space as well as the container memory limit. + import resource + memory = int(os.getenv('JOB_MEMORY_MB', '768')) * 1024 * 1024 + resource.setrlimit(resource.RLIMIT_AS, (memory, memory)) + otel.setup(child=True) + engine = create_db_engine() + try: + with otel.span('image.process', context=otel.propagator.extract({ + 'traceparent': os.getenv('TRACEPARENT', ''), 'tracestate': os.getenv('TRACESTATE', '')})): + process(sessionmaker(engine, expire_on_commit=False), sys.argv[1], sys.argv[2]) + otel.event('image_completed') + except (UnidentifiedImageError, Image.DecompressionBombError, ValueError, SyntaxError): + return 20 + except MemoryError: + return 21 + except Exception: + return 22 # No credentials or decoder/database internals in logs. + finally: + engine.dispose() + otel.shutdown() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/jobs.py b/src/jobs.py new file mode 100644 index 0000000..0757b2c --- /dev/null +++ b/src/jobs.py @@ -0,0 +1,199 @@ +"""Small PostgreSQL outbox + Redis Streams queue; PostgreSQL owns job state.""" +import argparse +import json +import logging +import os +import random +import time +from datetime import datetime, timedelta, timezone +from uuid import UUID, uuid4 + +from redis import Redis +from redis.exceptions import ResponseError +from sqlalchemy import and_, or_, select, func +from sqlalchemy.orm import sessionmaker + +from .database import create_db_engine +from .admission import reserve_capacity +from .models import Attachment, AttachmentJob +from .object_storage import BUCKET, s3_client +from . import telemetry as otel + +STREAM = 'attachment-jobs' +GROUP = 'image-workers' +MAX_ATTEMPTS = max(1, int(os.getenv('JOB_MAX_ATTEMPTS', '5'))) +TIMEOUT = max(1, int(os.getenv('JOB_TIMEOUT_SECONDS', '60'))) +LEASE_SECONDS = TIMEOUT + 15 + + +def now(): + return datetime.now(timezone.utc) + + +def broker(): + return Redis.from_url(os.getenv('BROKER_URL', 'redis://broker:6379/0'), + decode_responses=True, socket_connect_timeout=2, socket_timeout=5) + + +def ensure_group(client): + try: + client.xgroup_create(STREAM, GROUP, id='0', mkstream=True) + except ResponseError as exc: + if not str(exc).startswith('BUSYGROUP'): + raise + + +def envelope(job): + return {'schema_version': 1, 'job_id': job.id, 'type': 'attachment.process.v1', + 'attachment_id': job.attachment_id, 'pipeline_version': job.pipeline_version, + 'attempt': job.attempt + 1, + 'created_at': job.created_at.isoformat().replace('+00:00', 'Z')} + + +def fail(session, job, attachment, code, permanent=False): + job.failures += 1 + job.last_error = code + job.lease_token = job.lease_until = job.published_at = None + attachment.updated_at = now() + if permanent or job.failures >= MAX_ATTEMPTS: + attachment.status = 'failed' + attachment.error_code = code if permanent else 'retry_exhausted' + else: + attachment.status = 'queued' + attachment.error_code = None + delay = min(60, 2 ** min(job.failures, 6)) * random.uniform(0.5, 1.5) + job.available_at = now() + timedelta(seconds=delay) + otel.event('job_retry' if attachment.status == 'queued' else 'job_failed', + attempt=job.attempt, outcome=attachment.status, error_code=code) + + +def dispatch_once(sessions, client): + # A crash after XADD but before COMMIT deliberately results in redelivery. + with sessions.begin() as session: + jobs = list(session.scalars(select(AttachmentJob).join(Attachment).where( + or_(and_(Attachment.status == 'queued', AttachmentJob.published_at.is_(None)), + and_(Attachment.status == 'processing', AttachmentJob.lease_until <= now())), + AttachmentJob.available_at <= now()).order_by(AttachmentJob.available_at) + .with_for_update(skip_locked=True, of=AttachmentJob).limit(50))) + for job in jobs: + attachment = session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment.status == 'processing': + if job.lease_until <= now(): + fail(session, job, attachment, 'lease_expired') + continue + if job.published_at is None: + with otel.span('attachment-jobs publish', kind=otel.SpanKind.PRODUCER, + context=otel.propagator.extract(job.trace_context), attributes={ + 'messaging.system': 'redis', 'messaging.destination.name': STREAM, + 'messaging.operation.type': 'publish', 'job.attempt': job.attempt + 1}): + client.xadd(STREAM, {'job': json.dumps({**envelope(job), **otel.carrier()})}) + otel.event('job_published', attempt=job.attempt + 1) + job.published_at = now() + + +def sample_queue(sessions): + # Database is the durable backlog: includes outbox rows not yet in Redis and retries. + with sessions() as session: + depth, oldest = session.execute(select(func.count(), func.min(Attachment.created_at)) + .select_from(Attachment).where(Attachment.status == 'queued')).one() + otel.queue_state.update(depth=depth, age=max(0, (now() - oldest).total_seconds()) if oldest else 0, + updated=time.time()) + + +def claim(sessions, message): + if (message.get('schema_version') != 1 or message.get('type') != 'attachment.process.v1' + or message.get('pipeline_version') != 1): + raise ValueError('unsupported job envelope') + job_id = str(UUID(message['job_id'])) + with sessions.begin() as session: + job = session.get(AttachmentJob, job_id, with_for_update=True) + if job is None or job.attachment_id != message.get('attachment_id'): + raise ValueError('unknown job') + attachment = session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment.status != 'queued' or job.available_at > now(): + return None + job.attempt += 1 + if job.first_started_at is None: + job.first_started_at = now() + job.lease_token = str(uuid4()) + job.lease_until = now() + timedelta(seconds=LEASE_SECONDS) + attachment.status = 'processing' + attachment.updated_at = now() + return job.id, job.lease_token + + +def record_failure(sessions, job_id, token, code, permanent=False): + with sessions.begin() as session: + job = session.get(AttachmentJob, job_id, with_for_update=True) + if job.lease_token == token: + attachment = session.get(Attachment, job.attachment_id, with_for_update=True) + fail(session, job, attachment, code, permanent) + + +def replay(sessions, job_id, reason): + if not reason.strip() or len(reason) > 200: + raise ValueError('Give a nonempty reason of at most 200 characters') + with sessions.begin() as session: + job = session.get(AttachmentJob, str(UUID(job_id)), with_for_update=True) + if job is None: + raise ValueError('Job not found') + attachment = session.get(Attachment, job.attachment_id, with_for_update=True) + if attachment.status != 'failed': + raise ValueError('Replay is allowed only for failed jobs') + if not attachment.staging_key: + raise ValueError('Staging retention expired; upload the file again') + s3_client().head_object(Bucket=BUCKET, Key=attachment.staging_key) + reserve_capacity(session) + job.replay_audit = job.replay_audit + [{'at': now().isoformat(), 'reason': reason, + 'after_attempt': job.attempt, + 'last_error': job.last_error}] + job.failures = 0 + job.available_at = now() + job.published_at = job.lease_until = job.lease_token = None + attachment.status, attachment.error_code = 'queued', None + attachment.updated_at = now() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest='command', required=True) + sub.add_parser('dispatch') + sub.add_parser('failed') + retry = sub.add_parser('replay') + retry.add_argument('job_id') + retry.add_argument('--reason', required=True) + args = parser.parse_args() + logging.basicConfig(level=logging.INFO) + otel.setup() + engine = create_db_engine() + sessions = sessionmaker(engine, expire_on_commit=False) + try: + if args.command == 'failed': + with sessions() as session: + for job, att in session.execute(select(AttachmentJob, Attachment).join( + Attachment, Attachment.id == AttachmentJob.attachment_id) + .where(Attachment.status == 'failed')): + print(json.dumps({'job_id': job.id, 'attachment_id': att.id, + 'attempt': job.attempt, 'error_code': att.error_code, + 'last_error': job.last_error, + 'replay_available': bool(att.staging_key)})) + elif args.command == 'replay': + replay(sessions, args.job_id, args.reason) + print('Job queued for replay') + else: + client = broker() + while True: + try: + ensure_group(client) + dispatch_once(sessions, client) + sample_queue(sessions) + except Exception as exc: + otel.event('dispatch_deferred', error_type=type(exc).__name__) + time.sleep(1) + finally: + engine.dispose() + otel.shutdown() + + +if __name__ == '__main__': + main() diff --git a/src/limits.py b/src/limits.py new file mode 100644 index 0000000..facdf11 --- /dev/null +++ b/src/limits.py @@ -0,0 +1,99 @@ +import asyncio +import os +from dataclasses import dataclass + +from starlette.requests import Request + +from .errors import error_response +from .middleware import is_upload + + +@dataclass(frozen=True) +class Limits: + max_users: int = 1000 + max_chats: int = 1000 + max_messages: int = 10000 + max_text_bytes: int = 16 * 1024 * 1024 + max_request_bytes: int = 64 * 1024 + max_inflight: int = 32 + message_rate: int = 1000 + message_burst: int = 1000 + + @classmethod + def from_env(cls): + values = {} + for name, default in cls().__dict__.items(): + value = int(os.getenv(name.upper(), str(default))) + if value < 1: + raise ValueError(f'{name.upper()} must be positive') + values[name] = value + return cls(**values) + + +limits = Limits.from_env() + + +class ResourceLimitMiddleware: + def __init__(self, app, settings=limits): + self.app = app + self.settings = settings + self.active = 0 + + async def __call__(self, scope, receive, send): + if scope['type'] != 'http' or scope['path'].startswith('/health/'): + return await self.app(scope, receive, send) + + request = Request(scope) + + async def reject(status, code, message): + response = error_response(request, status, code, message) + if status == 503: + response.headers['Retry-After'] = '1' + await response(scope, receive, send) + + if self.active >= self.settings.max_inflight: + return await reject(503, 'unavailable', 'Слишком много одновременных запросов') + self.active += 1 + try: + # The upload endpoint authenticates and bounds its stream itself. + if is_upload(scope['method'], scope['path']): + return await self.app(scope, receive, send) + length = request.headers.get('content-length') + if length is not None: + try: + size = int(length) + if size < 0: + raise ValueError() + except ValueError: + return await reject(400, 'invalid_request', 'Неверный Content-Length') + if size > self.settings.max_request_bytes: + return await reject(413, 'payload_too_large', 'Тело запроса слишком большое') + + body = bytearray() + try: + async with asyncio.timeout(5): + while True: + message = await receive() + if message['type'] == 'http.disconnect': + return + chunk = message.get('body', b'') + if len(body) + len(chunk) > self.settings.max_request_bytes: + return await reject(413, 'payload_too_large', 'Тело запроса слишком большое') + body.extend(chunk) + if not message.get('more_body', False): + break + except TimeoutError: + return await reject(503, 'unavailable', 'Истекло время чтения запроса') + + delivered = False + + async def buffered_receive(): + nonlocal delivered + if not delivered: + delivered = True + return {'type': 'http.request', 'body': bytes(body), 'more_body': False} + return await receive() + + await self.app(scope, buffered_receive, send) + finally: + self.active -= 1 diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..cfc43e6 --- /dev/null +++ b/src/main.py @@ -0,0 +1,55 @@ +from fastapi import FastAPI +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException +from contextlib import asynccontextmanager +from sqlalchemy.exc import OperationalError, InterfaceError, TimeoutError as PoolTimeout +from sqlalchemy.orm import sessionmaker +from redis.exceptions import RedisError +from botocore.exceptions import BotoCoreError, ClientError + +from .errors import APIError, api_error_handler, validation_error_handler, http_error_handler, internal_error_handler, dependency_error_handler +from .database import create_db_engine +from .store import store +from .auth import sessions +from .middleware import RequestIdMiddleware +from .limits import ResourceLimitMiddleware +from .routers.health import router as health_router +from .routers.users import router as users_router +from .routers.chats import router as chats_router +from .routers.auth import router as auth_router +from .routers.attachments import router as attachments_router +from . import telemetry + + +@asynccontextmanager +async def lifespan(app): + telemetry.setup() + telemetry.seed_http(app.routes) + engine = create_db_engine() + try: + store.sessions = sessionmaker(engine, expire_on_commit=False) + yield + finally: + engine.dispose() + sessions.client.close() + telemetry.shutdown() + + +app = FastAPI(title="MTUSI Messenger", lifespan=lifespan) +app.add_middleware(ResourceLimitMiddleware) +app.add_middleware(RequestIdMiddleware) +app.add_exception_handler(APIError, api_error_handler) +app.add_exception_handler(RequestValidationError, validation_error_handler) +app.add_exception_handler(HTTPException, http_error_handler) +app.add_exception_handler(Exception, internal_error_handler) +for error in (OperationalError, InterfaceError, PoolTimeout, RedisError, BotoCoreError, ClientError): + app.add_exception_handler(error, dependency_error_handler) + +app.include_router(health_router) +app.include_router(users_router) +app.include_router(chats_router) +app.include_router(auth_router) +app.include_router(attachments_router) + +# Outside FastAPI's error middleware: includes generated 500 responses and full streams. +app = telemetry.HttpTelemetry(app) diff --git a/src/middleware.py b/src/middleware.py new file mode 100644 index 0000000..c2b73a1 --- /dev/null +++ b/src/middleware.py @@ -0,0 +1,43 @@ +from uuid import uuid4 +from socket import gethostname +from starlette.responses import JSONResponse +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +import re + + +def is_upload(method, path): + return method == 'POST' and re.fullmatch(r'/api/v1/chats/[^/]+/attachments', path) is not None + +INSTANCE_ID = gethostname() + + +class RequestIdMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + request_id = request.headers.get("X-Request-Id", "").strip() or str(uuid4()) + request.state.request_id = request_id + + if (request.method in {"POST", "PUT", "PATCH"} + and request.url.path.startswith("/api/") + and not is_upload(request.method, request.url.path) + and request.url.path != '/api/v1/auth/sessions'): + content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + if content_type != "application/json": + response = JSONResponse( + status_code=415, + content={ + "error": { + "code": "unsupported_media_type", + "message": "Ожидается Content-Type application/json", + "request_id": request_id, + } + }, + ) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + return response diff --git a/src/models.py b/src/models.py new file mode 100644 index 0000000..d9e0212 --- /dev/null +++ b/src/models.py @@ -0,0 +1,109 @@ +from datetime import datetime +from uuid import uuid4 + +from sqlalchemy import BigInteger, CheckConstraint, DateTime, ForeignKey, Index, Text, Uuid, func +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from sqlalchemy.dialects.postgresql import ARRAY, JSONB + + +class Base(DeclarativeBase): + pass + + +class User(Base): + __tablename__ = 'users' + __table_args__ = ( + CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'"), + CheckConstraint('char_length(display_name) BETWEEN 1 AND 100'), + ) + id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4())) + username: Mapped[str] = mapped_column(Text, unique=True) + display_name: Mapped[str] = mapped_column(Text) + password_hash: Mapped[str] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + + +class Chat(Base): + __tablename__ = 'chats' + __table_args__ = ( + CheckConstraint('char_length(title) BETWEEN 1 AND 100'), + Index('chats_order_idx', 'created_at', 'id'), + ) + id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4())) + title: Mapped[str] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + history_version: Mapped[int] = mapped_column(BigInteger, server_default='0') + + +class ChatMember(Base): + __tablename__ = 'chat_members' + __table_args__ = (Index('chat_members_user_idx', 'user_id', 'chat_id'),) + chat_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('chats.id', ondelete='CASCADE'), primary_key=True) + user_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('users.id'), primary_key=True) + + +class Message(Base): + __tablename__ = 'messages' + __table_args__ = ( + CheckConstraint('char_length(text) <= 4000'), + CheckConstraint("length(btrim(text)) > 0 OR cardinality(attachment_ids) > 0"), + Index('messages_history_idx', 'chat_id', 'created_at', 'id'), + ) + id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4())) + chat_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('chats.id', ondelete='CASCADE')) + sender_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('users.id')) + text: Mapped[str] = mapped_column(Text) + attachment_ids: Mapped[list[str]] = mapped_column(ARRAY(Uuid(as_uuid=False)), default=list, server_default='{}') + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + + +class SchemaMigration(Base): + __tablename__ = 'schema_migrations' + version: Mapped[str] = mapped_column(Text, primary_key=True) + applied_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=True) + + +class Attachment(Base): + __tablename__ = 'attachments' + id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True) + chat_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('chats.id', ondelete='CASCADE')) + owner_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('users.id')) + object_key: Mapped[str] = mapped_column(Text, unique=True) + filename: Mapped[str] = mapped_column(Text) + content_type: Mapped[str] = mapped_column(Text) + size_bytes: Mapped[int] = mapped_column(BigInteger) + sha256: Mapped[str] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + status: Mapped[str] = mapped_column(Text, server_default='queued') + staging_key: Mapped[str | None] = mapped_column(Text) + variants: Mapped[list] = mapped_column(JSONB, server_default='[]') + error_code: Mapped[str | None] = mapped_column(Text) + + +class AttachmentJob(Base): + """The job row is also the transactional outbox and failed-job registry.""" + __tablename__ = 'attachment_jobs' + id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4())) + attachment_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('attachments.id'), unique=True) + pipeline_version: Mapped[int] = mapped_column(BigInteger, server_default='1') + attempt: Mapped[int] = mapped_column(BigInteger, server_default='0') + failures: Mapped[int] = mapped_column(BigInteger, server_default='0') + last_error: Mapped[str | None] = mapped_column(Text) + first_started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + lease_token: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) + replay_audit: Mapped[list] = mapped_column(JSONB, server_default='[]') + trace_context: Mapped[dict] = mapped_column(JSONB, server_default='{}') + + +class IdempotencyRecord(Base): + __tablename__ = 'message_idempotency' + actor_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('users.id'), primary_key=True) + chat_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('chats.id', ondelete='CASCADE'), primary_key=True) + key: Mapped[str] = mapped_column(Text, primary_key=True) + message_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('messages.id', ondelete='CASCADE')) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp()) diff --git a/src/object_storage.py b/src/object_storage.py new file mode 100644 index 0000000..924a837 --- /dev/null +++ b/src/object_storage.py @@ -0,0 +1,33 @@ +import os +from functools import lru_cache + +import boto3 +from botocore.config import Config +from .telemetry import dependency_span + +BUCKET = os.getenv('S3_BUCKET', 'messenger-attachments') +PREFIX = 'originals/' + + +@lru_cache(maxsize=1) +def s3_client(): + client = boto3.client( + 's3', endpoint_url=os.getenv('S3_ENDPOINT', 'http://s3:9000'), + region_name=os.getenv('S3_REGION', 'us-east-1'), + aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'], + aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'], + config=Config(connect_timeout=2, read_timeout=5, + retries={'total_max_attempts': 1}, + s3={'addressing_style': 'path'}, + request_checksum_calculation='when_required', + response_checksum_validation='when_required'), + ) + # Instrument SDK operations without object keys, signed URLs, headers or bytes. + original = client._make_api_call + + def call(operation, parameters): + with dependency_span('s3.' + operation, **{'rpc.system': 'aws-api', 'rpc.service': 'S3', + 'rpc.method': operation}): + return original(operation, parameters) + client._make_api_call = call + return client diff --git a/src/routers/__init__.py b/src/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/routers/attachments.py b/src/routers/attachments.py new file mode 100644 index 0000000..f5eb354 --- /dev/null +++ b/src/routers/attachments.py @@ -0,0 +1,90 @@ +import asyncio +import hashlib +from tempfile import TemporaryFile +from urllib.parse import quote + +from fastapi import APIRouter, Depends, Query, Request +from starlette.background import BackgroundTask +from starlette.concurrency import run_in_threadpool +from starlette.requests import ClientDisconnect +from starlette.responses import StreamingResponse + +from ..attachments import MAX_BYTES, get_attachment, metadata, save_attachment, validate_filename +from ..dependencies import current_user +from ..errors import APIError +from ..object_storage import BUCKET, s3_client +from ..store import ensure_uuid, store + +router = APIRouter(prefix='/api/v1', tags=['attachments']) +# At most one decoded image (<=40M pixels) per API process; incoming bodies use disk. +decode_slot = asyncio.Semaphore(1) + + +@router.post('/chats/{chat_id}/attachments', status_code=202) +async def upload(chat_id: str, request: Request, filename: str = Query(...), + user: dict = Depends(current_user)): + chat_id = ensure_uuid(chat_id) + await run_in_threadpool(store.get_chat_for_user, chat_id, user['id']) + validate_filename(filename) + content_type = request.headers.get('content-type', '').split(';', 1)[0].strip().lower() + if content_type not in ('image/png', 'image/jpeg'): + raise APIError(415, 'unsupported_media_type', 'Ожидается PNG или JPEG') + length = request.headers.get('content-length') + if length is not None: + try: + length = int(length) + if length < 0: + raise ValueError() + except ValueError as exc: + raise APIError(400, 'invalid_request', 'Неверный Content-Length') from exc + if length > MAX_BYTES: + raise APIError(413, 'payload_too_large', 'Файл слишком большой') + size = 0 + digest = hashlib.sha256() + with TemporaryFile() as source: + try: + async with asyncio.timeout(30): + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_BYTES: + raise APIError(413, 'payload_too_large', 'Файл слишком большой') + digest.update(chunk) + await run_in_threadpool(source.write, chunk) + except (TimeoutError, ClientDisconnect) as exc: + raise APIError(400, 'invalid_request', 'Загрузка прервана') from exc + if length is not None and size != length: + raise APIError(400, 'invalid_request', 'Неполное тело запроса') + async with decode_slot: + return await run_in_threadpool(save_attachment, source, chat_id, user['id'], + filename, content_type, size, digest.hexdigest()) + + +@router.get('/attachments/{attachment_id}') +def attachment_info(attachment_id: str, user: dict = Depends(current_user)): + return metadata(get_attachment(attachment_id, user['id'])) + + +@router.get('/attachments/{attachment_id}/content') +def download(attachment_id: str, variant: str = 'original', user: dict = Depends(current_user)): + attachment = get_attachment(attachment_id, user['id']) + if attachment.status != 'ready': + raise APIError(409, 'conflict', 'Вложение ещё не готово') + key, content_type, size = attachment.object_key, attachment.content_type, attachment.size_bytes + if variant != 'original': + item = next((v for v in attachment.variants if v['name'] == variant), None) + if item is None: + raise APIError(404, 'not_found', 'Вариант не найден') + key, content_type, size = item['object_key'], item['content_type'], item['size_bytes'] + body = s3_client().get_object(Bucket=BUCKET, Key=key)['Body'] + + def chunks(): + try: + yield from body.iter_chunks(chunk_size=64 * 1024) + finally: + body.close() + + return StreamingResponse(chunks(), media_type=content_type, + headers={'Content-Length': str(size), + 'Content-Disposition': "attachment; filename*=UTF-8''" + quote(attachment.filename, safe=''), + 'X-Content-Type-Options': 'nosniff'}, + background=BackgroundTask(body.close)) diff --git a/src/routers/auth.py b/src/routers/auth.py new file mode 100644 index 0000000..bb4beaa --- /dev/null +++ b/src/routers/auth.py @@ -0,0 +1,34 @@ +import base64 + +from fastapi import APIRouter, Depends, Header, Request, Response +from starlette.concurrency import run_in_threadpool + +from ..auth import sessions, unauthorized +from ..dependencies import bearer_token, current_user +from ..errors import APIError +from ..store import store + +router = APIRouter(prefix='/api/v1/auth/sessions', tags=['auth']) + + +@router.post('', status_code=201) +async def create_session(request: Request, authorization: str = Header(default='')): + if await request.body(): + raise APIError(400, 'invalid_request', 'Вход не принимает тело запроса') + try: + scheme, encoded = authorization.split() + if scheme.lower() != 'basic': + raise ValueError() + username, password = base64.b64decode(encoded, validate=True).decode('utf-8').split(':', 1) + if not username.isascii() or not 12 <= len(password) <= 128 or '\x00' in username: + raise ValueError() + except (ValueError, UnicodeError): + raise unauthorized() from None + user = await run_in_threadpool(store.login, username, password) + return await run_in_threadpool(sessions.create, user) + + +@router.delete('/current', status_code=204) +def logout(token: str = Depends(bearer_token), user: dict = Depends(current_user)): + sessions.delete(token) + return Response(status_code=204) diff --git a/src/routers/chats.py b/src/routers/chats.py new file mode 100644 index 0000000..58aa1c7 --- /dev/null +++ b/src/routers/chats.py @@ -0,0 +1,49 @@ +from typing import Optional +import re + +from fastapi import APIRouter, Depends, Header, Query, status +from ..errors import APIError + +from ..dependencies import current_user, page_limit +from ..schemas.chat import Chat, ChatPage, CreateChat +from ..schemas.message import CreateMessage, Message, MessagePage +from ..store import store + +router = APIRouter(prefix="/api/v1/chats", tags=["chats"]) + + +@router.post("", response_model=Chat, status_code=status.HTTP_201_CREATED) +def create_chat(payload: CreateChat, user: dict = Depends(current_user)): + return store.create_chat(user["id"], payload.title, payload.member_ids) + + +@router.get("", response_model=ChatPage) +def list_chats( + limit: int = Depends(page_limit), + cursor: Optional[str] = Query(default=None, min_length=1), + user: dict = Depends(current_user), +): + return store.list_chats(user["id"], limit, cursor) + + +@router.get("/{chat_id}", response_model=Chat) +def get_chat(chat_id: str, user: dict = Depends(current_user)): + return store.get_chat_for_user(chat_id, user["id"]) + + +@router.post("/{chat_id}/messages", response_model=Message, status_code=status.HTTP_201_CREATED) +def create_message(chat_id: str, payload: CreateMessage, user: dict = Depends(current_user), + idempotency_key: Optional[str] = Header(default=None)): + if not idempotency_key or not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', idempotency_key): + raise APIError(400, 'invalid_request', 'Требуется корректный Idempotency-Key') + return store.create_message(chat_id, user["id"], payload.text, idempotency_key, payload.attachment_ids) + + +@router.get("/{chat_id}/messages", response_model=MessagePage) +def list_messages( + chat_id: str, + limit: int = Depends(page_limit), + cursor: Optional[str] = Query(default=None, min_length=1), + user: dict = Depends(current_user), +): + return store.list_messages(chat_id, user["id"], limit, cursor) diff --git a/src/routers/health.py b/src/routers/health.py new file mode 100644 index 0000000..f2015d3 --- /dev/null +++ b/src/routers/health.py @@ -0,0 +1,23 @@ +from fastapi import APIRouter +from sqlalchemy import select + +from ..schemas.common import Health +from ..auth import sessions +from ..store import store +from ..object_storage import BUCKET, s3_client + +router = APIRouter(prefix='/health') + + +@router.get("/live", response_model=Health) +def health_live(): + return {"status": "ok"} + + +@router.get("/ready", response_model=Health) +def health_ready(): + with store.sessions() as session: + session.execute(select(1)) + sessions.client.ping() + s3_client().head_bucket(Bucket=BUCKET) + return {"status": "ok"} diff --git a/src/routers/users.py b/src/routers/users.py new file mode 100644 index 0000000..2c8b69c --- /dev/null +++ b/src/routers/users.py @@ -0,0 +1,19 @@ +from fastapi import APIRouter, Depends, status + +from ..dependencies import current_user +from ..schemas.user import CreateUser, User +from ..store import store + + + +router = APIRouter(prefix="/api/v1/users", tags=["users"]) + + +@router.post("", response_model=User, status_code=status.HTTP_201_CREATED) +def create_user(payload: CreateUser): + return store.create_user(payload.username, payload.display_name, payload.password) + + +@router.get("/me", response_model=User) +def get_current_user(user: dict = Depends(current_user)): + return user diff --git a/src/schemas/__init__.py b/src/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/schemas/chat.py b/src/schemas/chat.py new file mode 100644 index 0000000..b1a3629 --- /dev/null +++ b/src/schemas/chat.py @@ -0,0 +1,35 @@ +from typing import List, Optional + +from pydantic import Field, StrictStr, field_validator + +from .common import ContractModel + + + +class CreateChat(ContractModel): + title: StrictStr = Field(min_length=1, max_length=100) + member_ids: List[StrictStr] = Field(min_length=1, max_length=100) + + @field_validator("title") + def validate_title(cls, value): + if not value.strip(): + raise ValueError("blank title") + return value + + @field_validator("member_ids") + def validate_member_ids(cls, value): + if len(value) != len(set(value)): + raise ValueError("duplicate member_ids") + return value + + +class Chat(ContractModel): + id: str + title: str + member_ids: List[str] + created_at: str + + +class ChatPage(ContractModel): + items: List[Chat] + next_cursor: Optional[str] diff --git a/src/schemas/common.py b/src/schemas/common.py new file mode 100644 index 0000000..06a7bc2 --- /dev/null +++ b/src/schemas/common.py @@ -0,0 +1,17 @@ +from pydantic import BaseModel, ConfigDict, field_validator + + +class ContractModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + @field_validator('*') + def validate_text_encoding(cls, value, info): + if isinstance(value, str): + value.encode('utf-8') + if info.field_name != 'password' and '\x00' in value: + raise ValueError('NUL is not supported in PostgreSQL text') + return value + + +class Health(ContractModel): + status: str diff --git a/src/schemas/message.py b/src/schemas/message.py new file mode 100644 index 0000000..75268c5 --- /dev/null +++ b/src/schemas/message.py @@ -0,0 +1,39 @@ +from typing import List, Optional + +from pydantic import Field, StrictStr, field_validator, model_validator +from uuid import UUID + +from .common import ContractModel + + + +class CreateMessage(ContractModel): + text: StrictStr = Field(max_length=4000) + attachment_ids: List[StrictStr] = Field(default_factory=list, max_length=10) + + @field_validator('attachment_ids') + def validate_ids(cls, value): + ids = [str(UUID(item)) for item in value] + if len(ids) != len(set(ids)): + raise ValueError('duplicate attachments') + return ids + + @model_validator(mode='after') + def validate_content(self): + if not self.text.strip() and not self.attachment_ids: + raise ValueError('empty message') + return self + + +class Message(ContractModel): + id: str + chat_id: str + sender_id: str + text: str + attachment_ids: List[str] + created_at: str + + +class MessagePage(ContractModel): + items: List[Message] + next_cursor: Optional[str] diff --git a/src/schemas/user.py b/src/schemas/user.py new file mode 100644 index 0000000..bd18d5b --- /dev/null +++ b/src/schemas/user.py @@ -0,0 +1,34 @@ +import re + +from pydantic import Field, StrictStr, field_validator + +from .common import ContractModel + + + +USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") + + +class CreateUser(ContractModel): + username: StrictStr + display_name: StrictStr = Field(min_length=1, max_length=100) + password: StrictStr = Field(min_length=12, max_length=128) + + @field_validator("username") + def validate_username(cls, value): + if not USERNAME_RE.fullmatch(value): + raise ValueError("invalid username") + return value + + @field_validator("display_name") + def validate_display_name(cls, value): + if not value.strip(): + raise ValueError("blank display_name") + return value + + +class User(ContractModel): + id: str + username: str + display_name: str = Field(min_length=1, max_length=100) + created_at: str diff --git a/src/store.py b/src/store.py new file mode 100644 index 0000000..b273f4c --- /dev/null +++ b/src/store.py @@ -0,0 +1,229 @@ +import base64 +import json +from datetime import datetime, timezone +from typing import Tuple +from uuid import UUID + +from sqlalchemy import select, tuple_, update +from sqlalchemy.exc import IntegrityError + +from .auth import password_hasher, verify_password, unauthorized +from .errors import APIError +from .cache import history_cache +from .models import User, Chat, ChatMember, Message, IdempotencyRecord, Attachment + + +def ensure_uuid(value): + try: + if not isinstance(value, str): + raise ValueError() + return str(UUID(value)) + except (TypeError, ValueError) as exc: + raise APIError(400, 'invalid_request', 'Неверный UUID') from exc + + +def serialize(model, *fields): + if model is None: + return None + result = {} + for field in fields: + value = getattr(model, field) + if isinstance(value, datetime): + value = value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z') + result[field] = value + return result + + +USER_FIELDS = ('id', 'username', 'display_name', 'created_at') +CHAT_FIELDS = ('id', 'title', 'created_at') +MESSAGE_FIELDS = ('id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids') + + +def after_condition(model, after): + return tuple_(model.created_at, model.id) > ( + datetime.fromisoformat(after[0].replace('Z', '+00:00')), after[1]) + + +def history_query(chat_id, limit, after): + query = select(Message).where(Message.chat_id == chat_id) + if after: + query = query.where(after_condition(Message, after)) + return query.order_by(Message.created_at, Message.id).limit(limit + 1) + + +class PostgresStore: + def __init__(self, cache=history_cache): + self.sessions = None + self.cache = cache + + def create_user(self, username, display_name, password): + user = User(username=username, display_name=display_name, password_hash=password_hasher.hash(password)) + try: + with self.sessions.begin() as session: + session.add(user) + session.flush() + result = serialize(user, *USER_FIELDS) + return result + except IntegrityError as exc: + if getattr(exc.orig, 'sqlstate', None) == '23505': + raise APIError(409, 'conflict', 'Имя пользователя уже занято') from exc + raise + + def get_user(self, user_id): + with self.sessions() as session: + return serialize(session.get(User, ensure_uuid(user_id)), *USER_FIELDS) + + def login(self, username, password): + with self.sessions() as session: + user = session.scalar(select(User).where(User.username == username)) + encoded = user.password_hash if user else None + result = serialize(user, *USER_FIELDS) + if not verify_password(encoded, password): + raise unauthorized() + return result + + def create_chat(self, actor_id, title, member_ids): + members = [ensure_uuid(member) for member in member_ids] + if len(members) != len(set(members)) or actor_id not in members: + raise APIError(400, 'invalid_request', 'Неверный список участников') + try: + with self.sessions.begin() as session: + chat = Chat(title=title) + session.add(chat) + session.flush() + session.add_all([ChatMember(chat_id=chat.id, user_id=member) for member in members]) + result = serialize(chat, *CHAT_FIELDS) + result['member_ids'] = sorted(members) + return result + except IntegrityError as exc: + if getattr(exc.orig, 'sqlstate', None) == '23503': + raise APIError(400, 'invalid_request', 'Неизвестный участник') from exc + raise + + @staticmethod + def _chat(session, chat_id, actor_id): + chat = session.scalar(select(Chat).join(ChatMember).where( + Chat.id == chat_id, ChatMember.user_id == actor_id)) + if chat is None: + raise APIError(404, 'not_found', 'Объект не найден') + return chat + + @staticmethod + def _members(session, chat): + result = serialize(chat, *CHAT_FIELDS) + result['member_ids'] = list(session.scalars(select(ChatMember.user_id).where( + ChatMember.chat_id == chat.id).order_by(ChatMember.user_id))) + return result + + def get_chat_for_user(self, chat_id, actor_id): + with self.sessions() as session: + return self._members(session, self._chat(session, ensure_uuid(chat_id), actor_id)) + + def list_chats(self, actor_id, limit, cursor): + after = self._decode_cursor(cursor, 'chats', actor_id) if cursor else None + query = select(Chat).join(ChatMember).where(ChatMember.user_id == actor_id) + if after: + query = query.where(after_condition(Chat, after)) + query = query.order_by(Chat.created_at, Chat.id).limit(limit + 1) + with self.sessions() as session: + chats = list(session.scalars(query)) + items = [self._members(session, chat) for chat in chats[:limit]] + return self._page(items, len(chats) > limit, 'chats', actor_id) + + def create_message(self, chat_id, actor_id, text, idempotency_key=None, attachment_ids=None): + chat_id = ensure_uuid(chat_id) + attachment_ids = [ensure_uuid(item) for item in (attachment_ids or [])] + with self.sessions.begin() as session: + self._chat(session, chat_id, actor_id) + if attachment_ids: + found = list(session.scalars(select(Attachment).where( + Attachment.id.in_(attachment_ids), Attachment.chat_id == chat_id) + .order_by(Attachment.id).with_for_update())) + if len(found) != len(attachment_ids): + raise APIError(404, 'not_found', 'Объект не найден') + if idempotency_key is not None: + # Serialize writers to this chat before looking up the key. + # The same row is updated below for history cache invalidation. + session.execute(select(Chat.id).where(Chat.id == chat_id).with_for_update()) + record = session.get(IdempotencyRecord, (actor_id, chat_id, idempotency_key)) + if record is not None: + previous = session.get(Message, record.message_id) + if previous.text != text or previous.attachment_ids != attachment_ids: + raise APIError(409, 'conflict', 'Ключ уже использован для другого сообщения') + return serialize(previous, *MESSAGE_FIELDS) + if attachment_ids and any(item.status == 'failed' for item in found): + raise APIError(409, 'conflict', 'Обработка вложения завершилась ошибкой') + session.execute(update(Chat).where(Chat.id == chat_id).values( + history_version=Chat.history_version + 1)) + message = Message(chat_id=chat_id, sender_id=actor_id, text=text, attachment_ids=attachment_ids) + session.add(message) + session.flush() + if idempotency_key is not None: + session.add(IdempotencyRecord(actor_id=actor_id, chat_id=chat_id, + key=idempotency_key, message_id=message.id)) + result = serialize(message, *MESSAGE_FIELDS) + return result + + def list_messages(self, chat_id, actor_id, limit, cursor): + chat_id = ensure_uuid(chat_id) + after = self._decode_cursor(cursor, 'messages', chat_id) if cursor else None + with self.sessions() as session: + version = self._chat(session, chat_id, actor_id).history_version + return self.cache.get_or_load( + chat_id, version, limit, after, + lambda: self._load_messages(chat_id, limit, after), + ) + + def _load_messages(self, chat_id, limit, after): + with self.sessions() as session: + messages = list(session.scalars(history_query(chat_id, limit, after))) + items = [serialize(message, *MESSAGE_FIELDS) for message in messages[:limit]] + return self._page(items, len(messages) > limit, 'messages', chat_id) + + def _page(self, items, has_more, resource, owner_id): + cursor = None + if has_more: + last = items[-1] + cursor = self._encode_cursor(resource, owner_id, last['created_at'], last['id']) + return {'items': items, 'next_cursor': cursor} + + @staticmethod + def _encode_cursor(resource: str, owner_id: str, created_at: str, item_id: str) -> str: + payload = { + "resource": resource, + "owner_id": owner_id, + "created_at": created_at, + "id": item_id, + } + raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + @staticmethod + def _decode_cursor(cursor: str, resource: str, owner_id: str) -> Tuple[str, str]: + try: + padded = cursor + "=" * (-len(cursor) % 4) + payload = json.loads(base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True).decode("utf-8")) + except (ValueError, UnicodeError, json.JSONDecodeError) as exc: + raise APIError(400, "invalid_request", "Неверный cursor") from exc + + if not isinstance(payload, dict): + raise APIError(400, "invalid_request", "Неверный cursor") + + if payload.get("resource") != resource or payload.get("owner_id") != owner_id: + raise APIError(400, "invalid_request", "Неверный cursor") + + item_id = ensure_uuid(payload.get("id")) + created_at = payload.get("created_at") + if not isinstance(created_at, str) or not created_at: + raise APIError(400, "invalid_request", "Неверный cursor") + try: + parsed = datetime.fromisoformat(created_at.replace("Z", "+00:00")) + if not created_at.endswith("Z") or parsed.tzinfo != timezone.utc: + raise ValueError("Expected UTC timestamp") + created_at = parsed.isoformat(timespec="microseconds").replace("+00:00", "Z") + except ValueError as exc: + raise APIError(400, "invalid_request", "Неверный cursor") from exc + return created_at, item_id + + +store = PostgresStore() diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 0000000..bc285bf --- /dev/null +++ b/src/telemetry.py @@ -0,0 +1,206 @@ +"""Small, explicit OTel instrumentation. Only allowlisted technical fields leave the app.""" +import json +import logging +import os +import re +import socket +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path + +import psutil +from opentelemetry import metrics, trace +from opentelemetry.trace import SpanKind, Status, StatusCode +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.metrics import MeterProvider, Histogram +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation +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 + +tracer = trace.get_tracer('messenger', '1.6.0') +meter = metrics.get_meter('messenger', '1.6.0') +propagator = TraceContextTextMapPropagator() # No baggage: it may contain user data. +logger = logging.getLogger('messenger.events') +logger.propagate = False +logger.setLevel(logging.INFO) +providers = [] +LOG_FIELDS = {'method', 'route', 'status_class', 'status', 'duration_seconds', 'request_id', + 'operation', 'error_type', 'attempt', 'outcome', 'error_code', 'job_type'} +http_requests = meter.create_counter('http_requests') +http_duration = meter.create_histogram('http_duration', unit='s') +jobs_processed = meter.create_counter('jobs_processed') +job_duration = meter.create_histogram('job_duration', unit='s') +time_to_ready = meter.create_histogram('attachment_time_to_ready', unit='s') +worker_busy = meter.create_up_down_counter('worker_busy') +queue_state = {'depth': 0, 'age': 0, 'updated': 0} + + +class JsonFormatter(logging.Formatter): + def format(self, record): + context = trace.get_current_span().get_span_context() + return json.dumps({ + 'timestamp': datetime.fromtimestamp(record.created, timezone.utc).isoformat(), + 'severity': record.levelname, 'service.name': os.getenv('OTEL_SERVICE_NAME', 'messenger-api'), + '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 '', + **{key: record.__dict__[key] for key in LOG_FIELDS if key in record.__dict__}, + }) + + +def event(name, *, severity=logging.INFO, **fields): + # Call sites pass fixed event names, safe enums/numbers and technical correlation IDs. + logger.log(severity, name, extra={'event': name, **{k: v for k, v in fields.items() if k in LOG_FIELDS}}) + + +def setup(*, child=False): + if providers or os.getenv('OTEL_SDK_DISABLED', 'false').lower() == 'true': + return + resource = Resource({ + 'service.name': os.getenv('OTEL_SERVICE_NAME', 'messenger-api'), + 'service.version': '1.6.0', 'service.instance.id': socket.gethostname(), + 'deployment.environment.name': 'lab', + }) + endpoint = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/') + traces = TracerProvider(resource=resource) + traces.add_span_processor(BatchSpanProcessor( + OTLPSpanExporter(endpoint=endpoint + '/v1/traces', timeout=1), + max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=1000)) + trace.set_tracer_provider(traces) + logs = LoggerProvider(resource=resource) + logs.add_log_record_processor(BatchLogRecordProcessor( + OTLPLogExporter(endpoint=endpoint + '/v1/logs', timeout=1), + max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=1000)) + console = logging.StreamHandler() + console.setFormatter(JsonFormatter()) + logger.addHandler(console) + logger.addHandler(LoggingHandler(logger_provider=logs)) + providers.extend([traces, logs]) + if child: + return # Short-lived image processes emit spans/logs; parent owns worker metrics. + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=endpoint + '/v1/metrics', timeout=1), + export_interval_millis=5000, export_timeout_millis=2000) + buckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 3, 5, 10, 30, 60, 120, 300] + metric_provider = MeterProvider(resource=resource, metric_readers=[reader], views=[ + View(instrument_type=Histogram, + aggregation=ExplicitBucketHistogramAggregation(buckets))]) + metrics.set_meter_provider(metric_provider) + providers.append(metric_provider) + process = psutil.Process() + meter.create_observable_gauge('process_memory', unit='By', callbacks=[ + lambda _: [metrics.Observation(process.memory_info().rss)]]) + meter.create_observable_counter('process_cpu', unit='s', callbacks=[ + lambda _: [metrics.Observation(sum(process.cpu_times()[:2]))]]) + cgroup = Path('/sys/fs/cgroup') + if (cgroup / 'memory.current').exists(): + meter.create_observable_gauge('container_memory', unit='By', callbacks=[ + lambda _: [metrics.Observation(int((cgroup / 'memory.current').read_text()))]]) + def cpu_usage(_): + values = dict(line.split() for line in (cgroup / 'cpu.stat').read_text().splitlines()) + return [metrics.Observation(int(values['usage_usec']) / 1_000_000)] + meter.create_observable_counter('container_cpu', unit='s', callbacks=[cpu_usage]) + if os.getenv('OTEL_SERVICE_NAME') == 'messenger-worker': + capacity = min(4, max(1, int(os.getenv('WORKER_CONCURRENCY', '2')))) + meter.create_observable_gauge('worker_capacity', callbacks=[ + lambda _: [metrics.Observation(capacity)]]) + worker_busy.add(0) + if os.getenv('OTEL_SERVICE_NAME') == 'messenger-dispatcher': + for name, key, unit in [('queue_depth', 'depth', ''), ('queue_oldest_age', 'age', 's'), + ('queue_sample_timestamp', 'updated', 's')]: + meter.create_observable_gauge(name, unit=unit, callbacks=[ + lambda _, key=key: [metrics.Observation(queue_state[key], {'queue': 'attachment-jobs'})]]) + + +def shutdown(): + for provider in reversed(providers): + provider.shutdown() + providers.clear() + + +def seed_http(routes): + # Export zero before the first failure: Prometheus rate needs a prior sample. + for route in routes: + if route.path.startswith('/health/'): + continue + for method in route.methods or (): + for status in ('2xx', '3xx', '4xx', '5xx'): + http_requests.add(0, {'method': method, 'route': route.path, 'status_class': status}) + + +def carrier(): + result = {} + propagator.inject(result) + return result + + +@contextmanager +def span(name, *, kind=SpanKind.INTERNAL, context=None, attributes=None): + # Never export exception messages/stack traces (SQL errors can embed parameters). + with tracer.start_as_current_span(name, kind=kind, context=context, attributes=attributes, + record_exception=False, set_status_on_exception=False) as current: + try: + yield current + except Exception as exc: + current.set_status(Status(StatusCode.ERROR)) + current.set_attribute('error.type', type(exc).__name__) + event('operation_failed', severity=logging.ERROR, operation=name, error_type=type(exc).__name__) + raise + + +@contextmanager +def dependency_span(name, **attributes): + # Background health probes and queue polling must not create disconnected trace noise. + if not trace.get_current_span().get_span_context().is_valid: + yield + else: + with span(name, kind=SpanKind.CLIENT, attributes=attributes): + yield + + +class HttpTelemetry: + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope['type'] != 'http' or scope['path'].startswith('/health/'): + return await self.app(scope, receive, send) + headers = {k.decode('latin1'): v.decode('latin1') for k, v in scope['headers'] + if k in (b'traceparent', b'tracestate')} + method = scope['method'] if scope['method'] in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'} else 'OTHER' + status = 500 + started = time.monotonic() + with span('HTTP ' + method, kind=SpanKind.SERVER, context=propagator.extract(headers)) as current: + async def response(message): + nonlocal status + if message['type'] == 'http.response.start': + status = message['status'] + await send(message) + try: + await self.app(scope, receive, response) + finally: + route = getattr(scope.get('route'), 'path', 'unmatched') + labels = {'method': method, 'route': route, 'status_class': f'{status // 100}xx'} + elapsed = time.monotonic() - started + http_requests.add(1, labels) + http_duration.record(elapsed, labels) + current.update_name(method + ' ' + route) + current.set_attributes({'http.request.method': method, 'http.route': route, + 'http.response.status_code': status}) + if status >= 500: + current.set_status(Status(StatusCode.ERROR)) + request_id = scope.get('state', {}).get('request_id', '') + if not re.fullmatch(r'[A-Za-z0-9_-]{1,64}', request_id): + request_id = '' + current.set_attribute('request_id', request_id) + event('http_request', severity=logging.ERROR if status >= 500 else logging.INFO, + **labels, status=status, duration_seconds=elapsed, + request_id=request_id) diff --git a/src/worker.py b/src/worker.py new file mode 100644 index 0000000..118c885 --- /dev/null +++ b/src/worker.py @@ -0,0 +1,122 @@ +"""Bounded consumers, one unacknowledged message per consumer, hard process timeout.""" +import json +import logging +import os +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from uuid import uuid4 + +from sqlalchemy.orm import sessionmaker + +from .database import create_db_engine +from .jobs import GROUP, STREAM, LEASE_SECONDS, TIMEOUT, broker, claim, ensure_group, record_failure +from .models import Attachment, AttachmentJob +from . import telemetry as otel + + +def handle(sessions, client, message_id, fields): + try: + message = json.loads(fields['job']) + if not isinstance(message, dict): + raise ValueError('invalid envelope') + except (ValueError, KeyError, TypeError): + otel.event('invalid_job') + acknowledge(client, message_id) + return + with otel.span('attachment-jobs process', kind=otel.SpanKind.CONSUMER, + context=otel.propagator.extract(message), attributes={ + 'messaging.system': 'redis', 'messaging.destination.name': STREAM, + 'messaging.operation.type': 'process', 'job.attempt': message.get('attempt', 0)}): + process_message(sessions, client, message_id, message) + + +def process_message(sessions, client, message_id, message): + try: + claimed = claim(sessions, message) + except (ValueError, KeyError, TypeError): + otel.event('invalid_job') + claimed = None + if claimed: + job_id, token = claimed + started = time.monotonic() + outcome = 'failed' + otel.worker_busy.add(1) + try: + environment = {**os.environ, 'OTEL_CHILD_PROCESS': 'true'} + environment.update({key.upper(): value for key, value in otel.carrier().items()}) + try: + result = subprocess.run([sys.executable, '-m', 'src.image_processor', job_id, token], + timeout=TIMEOUT, check=False, env=environment) + code = result.returncode + except subprocess.TimeoutExpired: + code = 23 + if code in (91, 92): + # Simulate a lost worker before ack: leave the pending entry and lease. + return + if code: + record_failure(sessions, job_id, token, + {20: 'invalid_image', 21: 'resource_limit', 23: 'processing_timeout'} + .get(code, 'processing_failed'), permanent=code in (20, 21)) + otel.trace.get_current_span().set_status(otel.Status(otel.StatusCode.ERROR)) + else: + with sessions() as session: + job = session.get(AttachmentJob, job_id) + attachment = session.get(Attachment, job.attachment_id) + outcome = 'ready' if attachment.status == 'ready' else 'skipped' + if outcome == 'ready': + otel.time_to_ready.record((attachment.updated_at - attachment.created_at).total_seconds(), + {'job_type': 'attachment.process.v1'}) + finally: + otel.worker_busy.add(-1) + labels = {'job_type': 'attachment.process.v1', 'outcome': outcome} + elapsed = time.monotonic() - started + otel.jobs_processed.add(1, labels) + otel.job_duration.record(elapsed, labels) + otel.event('job_processed', severity=logging.ERROR if outcome == 'failed' else logging.INFO, + **labels, duration_seconds=elapsed) + # Only after a durable ready/failed/retry (or an existing durable lease). + acknowledge(client, message_id) + + +def acknowledge(client, message_id): + with client.pipeline(transaction=True) as pipe: + pipe.xack(STREAM, GROUP, message_id) + pipe.xdel(STREAM, message_id) + pipe.execute() + + +def consume(sessions): + client = broker() + consumer = str(uuid4()) + cursor = '0-0' + while True: + try: + ensure_group(client) + pending = client.xautoclaim(STREAM, GROUP, consumer, LEASE_SECONDS * 1000, + start_id=cursor, count=1) + cursor, messages = pending[0], pending[1] + if not messages: + batches = client.xreadgroup(GROUP, consumer, {STREAM: '>'}, count=1, block=1000) + messages = batches[0][1] if batches else [] + for message_id, fields in messages: + handle(sessions, client, message_id, fields) + except Exception as exc: + otel.event('worker_deferred', error_type=type(exc).__name__) + time.sleep(1) + + +def main(): + logging.basicConfig(level=logging.INFO) + otel.setup() + engine = create_db_engine() + sessions = sessionmaker(engine, expire_on_commit=False) + concurrency = min(4, max(1, int(os.getenv('WORKER_CONCURRENCY', '2')))) + with ThreadPoolExecutor(max_workers=concurrency) as pool: + for task in [pool.submit(consume, sessions) for _ in range(concurrency)]: + task.result() + + +if __name__ == '__main__': + main() -- 2.54.0 From b6c71fd96a2f032764268c313ee10302cc340470 Mon Sep 17 00:00:00 2001 From: da1zy3r Date: Fri, 27 Nov 2026 21:55:47 +0300 Subject: [PATCH 2/2] Grade 4 --- .env.example | 61 +- .github/pull_request_template.md | 43 +- .gitignore | 1 + Dockerfile | 2 +- README.md | 6 + REPORT.md | 113 ++- compose.yaml | 898 +++++++++++++----- contracts/trust-matrix.md | 60 +- evidence/README.md | 20 +- evidence/environment.json | 379 ++++++++ evidence/internal.json | 514 ++++++++++ evidence/internal.txt | 115 +++ evidence/lifecycle.json | 72 ++ evidence/scan-findings.csv | 398 ++++++++ evidence/scan-summary.json | 40 + evidence/security.txt | 1 + evidence/smoke.txt | 1 + evidence/telemetry.json | 9 + evidence/verification.txt | 17 + .../provisioning/datasources/sources.yaml | 90 +- infra/nginx.conf | 38 - infra/openbao/README.md | 10 +- infra/openbao/api.hcl | 2 + infra/openbao/cleanup.hcl | 2 + infra/openbao/config.hcl | 11 + infra/openbao/dispatcher.hcl | 2 + infra/openbao/worker.hcl | 2 + infra/otel/collector.yaml | 59 +- infra/otel/loki.yaml | 23 +- infra/otel/prometheus.yaml | 26 +- infra/otel/tempo.yaml | 6 +- infra/postgres/pg_hba.conf | 3 + infra/postgres/start.sh | 6 + infra/readiness.sh | 38 - infra/s3-api-policy.json | 1 + infra/s3-bootstrap.sh | 9 - infra/s3-cleanup-policy.json | 1 + infra/s3-policy.json | 17 - infra/s3-worker-policy.json | 1 + infra/tls/api1.cfg | 20 + infra/tls/api2.cfg | 20 + infra/tls/broker.cfg | 20 + infra/tls/grafana.cfg | 19 + infra/tls/lb.cfg | 34 + infra/tls/loki.cfg | 24 + infra/tls/otel-collector.cfg | 30 + infra/tls/prometheus.cfg | 24 + infra/tls/redis.cfg | 19 + infra/tls/s3.cfg | 19 + infra/tls/tempo.cfg | 29 + requirements-operator.txt | 3 + requirements.txt | 2 +- scripts/lab7.py | 328 +++++++ security/OPERATIONS.md | 86 ++ security/SCAN_TRIAGE.md | 38 + security/THREAT_MODEL.md | 39 +- src/auth.py | 40 +- src/image_processor.py | 2 +- src/jobs.py | 6 +- src/object_storage.py | 1 + src/secure_run.py | 82 ++ src/store.py | 9 +- src/telemetry.py | 13 +- src/worker.py | 2 +- student-tests/internal.py | 185 ++++ student-tests/lifecycle.py | 127 +++ student-tests/telemetry.py | 47 + 67 files changed, 3770 insertions(+), 595 deletions(-) create mode 100644 evidence/environment.json create mode 100644 evidence/internal.json create mode 100644 evidence/internal.txt create mode 100644 evidence/lifecycle.json create mode 100644 evidence/scan-findings.csv create mode 100644 evidence/scan-summary.json create mode 100644 evidence/security.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/telemetry.json create mode 100644 evidence/verification.txt delete mode 100644 infra/nginx.conf create mode 100644 infra/openbao/api.hcl create mode 100644 infra/openbao/cleanup.hcl create mode 100644 infra/openbao/config.hcl create mode 100644 infra/openbao/dispatcher.hcl create mode 100644 infra/openbao/worker.hcl create mode 100644 infra/postgres/pg_hba.conf create mode 100644 infra/postgres/start.sh delete mode 100644 infra/readiness.sh create mode 100644 infra/s3-api-policy.json delete mode 100644 infra/s3-bootstrap.sh create mode 100644 infra/s3-cleanup-policy.json delete mode 100644 infra/s3-policy.json create mode 100644 infra/s3-worker-policy.json create mode 100644 infra/tls/api1.cfg create mode 100644 infra/tls/api2.cfg create mode 100644 infra/tls/broker.cfg create mode 100644 infra/tls/grafana.cfg create mode 100644 infra/tls/lb.cfg create mode 100644 infra/tls/loki.cfg create mode 100644 infra/tls/otel-collector.cfg create mode 100644 infra/tls/prometheus.cfg create mode 100644 infra/tls/redis.cfg create mode 100644 infra/tls/s3.cfg create mode 100644 infra/tls/tempo.cfg create mode 100644 requirements-operator.txt create mode 100644 scripts/lab7.py create mode 100644 security/OPERATIONS.md create mode 100644 security/SCAN_TRIAGE.md create mode 100644 src/secure_run.py create mode 100644 student-tests/internal.py create mode 100644 student-tests/lifecycle.py create mode 100644 student-tests/telemetry.py diff --git a/.env.example b/.env.example index 4e32d2a..d62e419 100644 --- a/.env.example +++ b/.env.example @@ -1,57 +1,4 @@ -# 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_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 -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/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 -MAX_UPLOAD_BYTES=10485760 -MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 -JOB_MAX_ATTEMPTS=5 -JOB_TIMEOUT_SECONDS=60 -STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 -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 -BAO_ADDR=https://openbao:8200 -BAO_CACERT=/run/secrets/bao-ca.crt -# No root token here. Bootstrap operator -> short-lived service auth -> scoped token. -ARGON2_MEMORY_KIB=19456 -ARGON2_ITERATIONS=2 -ARGON2_PARALLELISM=1 - -# Settings for the application carried over from lab 6 (compose.yaml). -MAX_PENDING_ATTACHMENTS=64 -JOB_MEMORY_MB=768 -POSTGRES_DB=messenger -POSTGRES_USER=messenger -POSTGRES_PASSWORD=replace-with-local-password -CACHE_TTL_SECONDS=30 -MAX_REQUEST_BYTES=65536 -MAX_INFLIGHT=32 -MINIO_ROOT_USER=local-admin -MINIO_ROOT_PASSWORD=replace-with-admin-password -S3_ACCESS_KEY_ID=messenger-api -S3_SECRET_ACCESS_KEY=replace-with-api-password -OTEL_SDK_DISABLED=false -GRAFANA_ADMIN_PASSWORD=replace-with-grafana-password +# Runtime secrets are generated by: python scripts/lab7.py bootstrap +# Do not put service passwords here; applications read scoped KV paths from OpenBao. +# Non-secret runtime settings and resource limits are explicit in compose.yaml. +# Operator instructions: security/OPERATIONS.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8aef0ff..ab5959f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,33 @@ ## Лабораторная 7 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор / группа: Ромашко Владимир, БВТ2301. -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Целевая оценка (3/4/5): **4**. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +Трек 5, если заявлен: не заявляется. + +Что реализовано и что перенесено: из lab6 перенесено основное приложение — API мессенджера, миграции, sessions/cache, outbox и обработка вложений, telemetry. В lab7 добавлены HTTPS, обязательное mTLS LB → обе API и сервисов → broker/Collector, TLS остальных связей, отдельные service identities и ACL, persistent OpenBao с cert auth/scoped KV/TTL, Argon2id rehash и общий rate limit. Показаны ротация DB secret и LB leaf без rebuild, отзыв старых credentials, expiry/sealed recovery, container hardening и разбор CVE. Лишних функций уровня 5 нет. + +Команды запуска из чистого clone (Windows, Python 3.12+, Docker Desktop Linux containers/Compose v2): + +```powershell +python -m pip install -r requirements-operator.txt +python scripts/check_contract.py +python scripts/lab7.py bootstrap +python scripts/lab7.py verify +``` + +Bootstrap выполняет локальную генерацию secrets/CA, init/unseal, policies, миграции, build/up и ожидание readiness. API: https://localhost:8443, CA: secrets/ca.crt. .env не требуется. Остановка без удаления данных: docker compose stop. Leaf certificates действуют 24 часа; продление: python scripts/lab7.py renew-leaves. Подробности и намеренное удаление данных описаны в отчёте. + +Результаты проверок и ссылка на REPORT.md: [REPORT.md](../REPORT.md), [evidence](../evidence/README.md). Публичные smoke/security по HTTPS прошли; 114 внутренних и 16 lifecycle проверок завершены. Проверены остановка каждой API, полный restart с сохранностью sessions/messages/original/thumbnail, старые secret/cert, expiry/sealed OpenBao и telemetry. Структура/контракт и синтаксис проверены отдельно. На Windows без make выполнены его эквиваленты: check_contract.py и неизменённый tests/smoke.py внутри verify. + +Ограничения / известные ошибки: один Docker-host и одиночные stateful зависимости; ручные unseal и renewal; краткий перерыв при ротации допустим. Остаточные CVE разобраны в [SCAN_TRIAGE.md](../security/SCAN_TRIAGE.md); нулевой scan и production readiness не заявляются. Полные scan JSON сохранены локально вне Git, все текущие findings и сводка включены в evidence. Последний повторный запуск сохранял существующие volumes; data wipe не выполнялся. Linux bind-mount permissions отдельно не проверялись. + +Источники и использование ИИ: материалы задания OWASP/OpenBao/Docker, документация используемых библиотек и приложение lab6; ссылки и версии приведены в REPORT.md. Codex использован для реализации, проверки и документации; evidence получены реальным запуском стенда. + +- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены. +- [x] make check и make test выполнены через указанные выше эквиваленты без make; приложен реальный вывод. +- [x] Сценарии отказов/безопасности своего уровня воспроизведены. +- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.gitignore b/.gitignore index b5a7189..85a76b0 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,5 @@ coverage/ .idea/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. +evidence/raw/ # Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/Dockerfile b/Dockerfile index 564995c..b4f8238 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.12.8-slim-bookworm +FROM python:3.12.16-slim-bookworm ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ diff --git a/README.md b/README.md index b329f91..48515c8 100644 --- a/README.md +++ b/README.md @@ -110,3 +110,9 @@ Threat model, заполненная trust matrix, TLS/mTLS конфигурац - [OpenBao policies](https://openbao.org/docs/concepts/policies/) - [OpenBao production hardening](https://openbao.org/docs/internals/security/) - [Docker security](https://docs.docker.com/engine/security/) + +## Запуск реализации + +Инструкция и команды bootstrap/verify: [security/OPERATIONS.md](security/OPERATIONS.md). +Модель угроз: [security/THREAT_MODEL.md](security/THREAT_MODEL.md). +Фактические результаты проверки сохраняются в `evidence/`. diff --git a/REPORT.md b/REPORT.md index 9801db4..c61565a 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,120 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Ромашко Владимир, БВТ2301. +- Целевая оценка: **4**, все обязательные пункты уровней 3 и 4. Трек на 5 не заявляется. +- Commit/PR: изменения подготовлены к сдаче в индексе Git; коммит и PR пока не созданы. +- Использованные источники, библиотеки и помощь ИИ: основное приложение перенесено из lab6; FastAPI, SQLAlchemy/psycopg, Redis, boto3, argon2-cffi, Pillow и OpenTelemetry. Версии закреплены в requirements.txt и compose.yaml. Использованы материалы задания: [OWASP Password Storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), [OWASP File Upload](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html), [OpenBao cert auth](https://openbao.org/docs/auth/cert/), [OpenBao policies](https://openbao.org/docs/concepts/policies/), [Docker security](https://docs.docker.com/engine/security/). Codex помог с переносом, реализацией TLS/OpenBao, проверками, разбором scan и подготовкой отчёта; результаты ниже получены запуском команд на стенде. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Проверенное окружение: Windows, Python 3.14 у оператора, Docker Desktop (Engine 28.5.1) с Linux containers и Compose 2.40.0, 8 доступных Docker CPU и 8 328 019 968 байт RAM. Нужны доступ к Docker Engine, свободные локальные порты 8443/3443/8200 и интернет для первой загрузки образов/пакетов. Python оператора — 3.12 или новее. Проверки выполняются из корня репозитория. + +```powershell +python -m pip install -r requirements-operator.txt +python scripts/check_contract.py +python scripts/lab7.py bootstrap +python scripts/lab7.py verify +``` + +Bootstrap создаёт локальные ключи, CA и credentials в игнорируемом secrets/, подготавливает volumes, запускает зависимости, выполняет init/unseal OpenBao, применяет KV/DB/S3 policies, SQL migrations по schema_migrations, собирает app image и ждёт HTTPS readiness. Он сохраняет существующие данные при повторном запуске. .env создавать не требуется: [.env.example](.env.example) объясняет переход на OpenBao; несекретные настройки находятся в compose.yaml, DATABASE_URL/REDIS_URL/BROKER_URL и S3 credentials выдаются из KV соответствующей роли. + +Приложение: https://localhost:8443, Grafana: https://localhost:3443, OpenBao оператора: https://127.0.0.1:8200. CA для клиентов — secrets/ca.crt. Grafana: пользователь admin, пароль из локального secrets/grafana-admin/password. Пароли и ключи не нужно копировать в отчёт или Git. + +Проверить готовность отдельно: + +```powershell +python -c "import requests; r=requests.get('https://localhost:8443/health/ready',verify='secrets/ca.crt',timeout=5); r.raise_for_status(); print(r.status_code,r.text)" +``` + +Runtime приложения: python:3.12.16-slim-bookworm, FastAPI 0.115.6, Argon2 23.1.0, Pillow 13.0.0. Инфраструктура: HAProxy 3.0.12-alpine, PostgreSQL 17.4-bookworm, Redis 7.4.2-bookworm, OpenBao 2.4.4, Collector 0.136.0, Prometheus 3.6.0, Loki 3.5.7, Tempo 2.9.0, Grafana 12.2.0; MinIO закреплён digest в compose.yaml. Полный перечень и лимиты — [environment.json](evidence/environment.json). + +verify запускает неизменённые публичные smoke/security в audit-контейнере, затем student-tests/lifecycle.py и внутренние mTLS/ACL проверки. make на проверенном Windows-host не установлен: python scripts/check_contract.py эквивалентен make check, а smoke.py внутри verify — make test с CA и адресом https://lb:8443. При установленном make можно использовать make check PYTHON=python и make test PYTHON=python CA_FILE=secrets/ca.crt. + +Операторские действия и безопасная остановка: + +```powershell +python scripts/lab7.py rotate-secret +python scripts/lab7.py rotate-leaf +python scripts/lab7.py renew-leaves +python scripts/lab7.py restart +docker compose stop +# После остановки снова запустить, сохранить данные и дождаться readiness: +python scripts/lab7.py bootstrap +``` + +rotate-secret меняет рабочий пароль API в PostgreSQL и KV, разрывая старые DB-соединения. rotate-leaf заменяет сертификат LB и отзывает старый serial через CRL. renew-leaves нужен до истечения 24 часов; CA живёт 30 дней. После отдельного restart OpenBao оператор выполняет python scripts/lab7.py unseal. Полный restart нужно делать скриптом: сначала владельцы network namespace, затем их TLS sidecars. Ключ CA, root token и unseal share доступны только оператору; учебный init использует один share с threshold=1. Подробнее: [OPERATIONS.md](security/OPERATIONS.md). + +**Намеренное удаление всех учебных данных**, включая БД, S3, сессии, OpenBao и telemetry: docker compose down --volumes. Эта команда не нужна для обычной остановки и при проверке не выполнялась. Локальные secrets/ сохраняются; следующий bootstrap заново инициализирует пустой OpenBao и данные. Потеря secrets/operator-private при сохранённом sealed OpenBao не имеет автоматического восстановления. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +```text +Клиент --HTTPS--> LB --mTLS--> API1 / API2 + |--TLS + SCRAM--> PostgreSQL + |--TLS + ACL----> Redis (sessions/cache/rate) + |--TLS + SigV4--> S3 +API/dispatcher/worker --mTLS + ACL--> Redis Streams broker +API/worker/dispatcher --mTLS--> OTel Collector +Collector --mTLS--> Loki / Tempo; Prometheus --mTLS--> Collector metrics +Grafana --mTLS, read/query--> Prometheus / Loki / Tempo +API/worker/dispatcher/cleanup --TLS + cert auth--> OpenBao (свой KV) +``` + +Из lab6 перенесены бизнес-API, миграции, Redis sessions/cache, PostgreSQL outbox, асинхронная обработка вложений, dispatcher/worker/cleanup и telemetry. PostgreSQL — источник истины для пользователей, ACL, сообщений и состояния заданий. Redis хранит сессии/кеш и отдельно очередь; S3 — байты приватных вложений. Создание сообщения, idempotency record и изменение версии истории происходят в одной DB-транзакции. Создание metadata вложения и outbox job также атомарно в БД. S3/Redis не включены в SQL-транзакцию: используются устойчивые object keys, повторная доставка/lease и cleanup, а не обещание exactly-once. + +В lab7 добавлены TLS, проверка CA/hostname и ролей, ограниченные DB/S3/broker/KV права, OpenBao supervisor, rehash/rate limit и hardening. Password hash — Argon2id m=19456 KiB, t=2, p=1 со случайной солью. При успешном входе старый hash обновляется условным UPDATE; сессии имеют TTL 3600s, в Redis используется SHA-256 ключа bearer token. Username/global rate budget проверяется до hash: 8 попыток за 10s на имя и 32/s суммарно на обе реплики, плюс не более двух hash operations на API. + +Для продуктов без подходящего native TLS используется одинаковый HAProxy sidecar. Plaintext доступен только на 127.0.0.1 внутри общего network namespace; все межконтейнерные связи из [матрицы доверия](contracts/trust-matrix.md) защищены TLS. PostgreSQL использует native TLS verify-full. Проверка разрешённого CN роли дополняет доверие CA. API/worker/dispatcher имеют разные клиентские identities; серверные identities API1/API2 отдельные. Наружу опубликованы только три loopback TLS-порта. В OpenBao сервис читает только secret/data/своя-роль, получает token TTL/maxTTL 60s и отзывает его после чтения. Supervisor обновляет конфигурацию каждые 10s, останавливает child после исчерпания ограниченного кеша и восстанавливает его после unseal. + +API: 1 CPU/384 MiB на реплику. Worker: 2 CPU/2 GiB, два subprocess, до 768 MiB адресного пространства и 60s на задачу. Upload: до 10 MiB и 40 млн пикселей, только PNG/JPEG; JSON body до 64 KiB. read_only, no-new-privileges, cap_drop ALL и tmpfs заданы всем контейнерам. Stateful volumes остаются writable; PostgreSQL entrypoint получает только необходимые capabilities для подготовки файлов, затем работает как postgres. Операторский audit имеет доступ к тестовым identities/credentials для отрицательных проверок и не запускается как постоянный сервис. + +Решение ограничено Compose, статическими policy-файлами и одним операторским скриптом. Автоматическая PKI, CA rollover, Kubernetes и исследовательские сценарии уровня 5 не добавлялись. ## Доказательства критериев +Все сценарии в таблице выполняются python scripts/lab7.py verify после bootstrap, кроме offline check и Trivy. Результаты последнего полного прогона: публичные smoke/security, 114 внутренних проверок и 16 lifecycle проверок. Финальная запись lifecycle — Complete lifecycle suite. + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Offline структура и сохранность контракта | python scripts/check_contract.py; сравнение tests/ и OpenAPI с HEAD | Структура/refs/Python syntax PASS, публичные тесты и контракт не изменены | [verification.txt](evidence/verification.txt) | +| Публичный smoke; 3.1 HTTPS и прежний API | verify: tests/smoke.py и tests/security.py с CA | Пользователи, сессии, чаты, сообщения, ACL и обработка вложений работают; недоверенный CA отклонён | [smoke.txt](evidence/smoke.txt), [security.txt](evidence/security.txt) | +| 3.1 Argon2id и измеренные параметры | internal: Measured Argon2 budget, Password rehashed | m=19456, t=2, p=1; реальные 20 измерений verify hash | [internal.json](evidence/internal.json) | +| 3.2 Обязательное mTLS LB → обе API | internal: allowed/no cert/foreign/outsider/expired/revoked и plaintext ports | Разрешён LB; отсутствующий, чужой, просроченный и отозванный cert отклонены; :8080 закрыт снаружи namespace | [internal.json](evidence/internal.json) | +| 3.3 TLS остальных связей и least privilege | internal: TLS/hostname, DB/S3/broker/KV ACL; telemetry | TLS соединения успешны, неверный hostname/роль и запрещённые операции отвергнуты; plaintext backends недоступны | [internal.json](evidence/internal.json), [trust-matrix.md](contracts/trust-matrix.md) | +| 3.4 Persistent non-dev OpenBao и scoped auth | bootstrap; internal own/other KV и policy write; lifecycle full restart | Сервис получает только свой KV, чужой path/policy write дают 403; init/state переживают restart, требуется unseal | [internal.json](evidence/internal.json), [lifecycle.json](evidence/lifecycle.json), [config.hcl](infra/openbao/config.hcl) | +| 3.5 Non-root, порты, capabilities, limits, secrets | lifecycle hardening и поиск canaries; проверка Git/build context | Hardening настроен всем сервисам; app/worker non-root; секретов/ключей в сдаваемых файлах нет | [environment.json](evidence/environment.json), [verification.txt](evidence/verification.txt), [.dockerignore](.dockerignore) | +| 3.6 Rate/size/ACL/logout/expiry/CA | smoke; internal shared rate/expiry; lifecycle cross-chat/oversize | 8×401 и 4×429 на обеих API, Retry-After; logout/expiry → 401; чужое вложение → 404, большой body → 413 | [internal.json](evidence/internal.json), [lifecycle.json](evidence/lifecycle.json), [smoke.txt](evidence/smoke.txt) | +| 4.1 mTLS broker и Collector, разные роли | internal: CA-trusted outsider и allowed service identities | Чужая роль с тем же CA отклонена; worker не может XADD, dispatcher не может читать consumer group | [internal.json](evidence/internal.json) | +| 4.2 Hashes, rehash, ошибки и login DoS | internal: old hash login, SQL hash, session digest, общий rate и timing | Старый hash заменён после успешного login; token не хранится открытым в ключе; лимит общий, дорогие операции ограничены | [internal.json](evidence/internal.json), [lifecycle.json](evidence/lifecycle.json) | +| 4.3 Secret/leaf rotation, отзыв, expiry/sealed | lifecycle вызывает rotate-secret, rotate-leaf, seal/unseal | Старый DB password и LB serial отвергнуты; image ID не изменился; token истёк; sealed остановил API и consumers; unseal восстановил работу | [lifecycle.json](evidence/lifecycle.json), [OPERATIONS.md](security/OPERATIONS.md) | +| 4.4 read_only/tmpfs/caps и scan с применимостью | lifecycle hardening; Trivy 0.76.2 по команде в SCAN_TRIAGE | Все сервисы ограничены; Python/Pillow обновлены; оставшиеся CVE разобраны по используемым путям | [environment.json](evidence/environment.json), [scan-summary.json](evidence/scan-summary.json), [scan-findings.csv](evidence/scan-findings.csv), [SCAN_TRIAGE.md](security/SCAN_TRIAGE.md) | +| 4.5 Модель ≥6 угроз, worker budget, TLS/ACL/telemetry audit | 12 путей угроз; internal/lifecycle/telemetry; просмотр worker limits | Все заявленные связи проверены; живые metrics/logs/traces, canaries отсутствуют, Grafana ingest запрещён; worker CPU/RAM/timeout заданы | [THREAT_MODEL.md](security/THREAT_MODEL.md), [internal.json](evidence/internal.json), [telemetry.json](evidence/telemetry.json), [environment.json](evidence/environment.json) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Проверка выполнена 27.11.2026. Гипотеза: минимальные параметры Argon2id дают приемлемую задержку на этом стенде, а общий rate limit и два hash slots ограничивают расход ресурсов независимо от выбранной API-реплики. Методика: audit container 0.5 CPU/256 MiB, один синтетический hash/password, один прогрев, 20 последовательных verify (concurrency=1, без заданного arrival rate). В [internal.json](evidence/internal.json) сохранены все samples_ms, p50/median, p95, p99, длительность, CPU seconds и peak RSS процесса. При 20 наблюдениях p99 принят равным максимуму. Peak RSS относится ко всему процессу аудита, а не только Argon2. Последний результат: p50 **72.59 ms**, p95 **93.82 ms**, p99 **100.27 ms**; 20/20 успешных verify за **1.144s**, CPU **0.592s**, peak RSS **102728 KiB**. Это около 17.48 hash verify/s при последовательном исполнении в ограниченном audit-контейнере, не HTTP RPS. + +Отдельный HTTP эксперимент переключается между двумя API и делает 12 последовательных неверных входов одного пользователя: 8 ответов 401 и 4 ответа 429. Это ожидаемые отказы защиты, не ошибки теста. Успешные API RPS и p50/p95/p99 под конкурентной нагрузкой здесь не измерялись: пропускная способность не является результатом этой лабораторной. 32/s — верхний лимит попыток, а не гарантированный throughput. Один hash использует 19 MiB; два слота дают около 38 MiB рабочей памяти Argon2 на API, дополнительно к Python и приложению. + +Lifecycle создаёт трёх синтетических пользователей, два чата, сообщение-canary и один sample.png с thumbnail. Публичный smoke создаёт свой набор данных. Каждый verify добавляет записи; стенд не очищается перед прогоном, размеры всей БД не используются как база performance-выводов. После каждого отказа сравниваются исходное сообщение, действующая сессия и байты оригинала/thumbnail. Тесты последовательные; отказ каждой API проверяется один раз за полный прогон, не является статистическим SLA. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| docker compose stop api1, затем api2 по очереди | LB направляет запросы на оставшуюся API | Для каждой остановки получено 5 последовательных ответов surviving instance; сессия, сообщение и оба файла сохранены | **api1: 1.67s, 1 неуспешная попытка; api2: 1.25s, 0**; измерение включает контрольные чтения, потери проверенных данных нет | +| Полный restart владельцев namespace и TLS sidecars | Volumes и приложение переживают restart; OpenBao требует unseal | PostgreSQL, Redis, broker, S3, OpenBao и telemetry перезапущены; saved checks проходят после operator unseal | Readiness в пределах тестового ожидания 90s; потери проверенных данных нет | +| Ротация API DB secret | Старое подключение закрыто, новый пароль применяется | Старый пароль отвергнут новым PostgreSQL connection, API продолжает чтение | Проверка через 12s и ожидание readiness; точная latency ротации не измерялась | +| Ротация LB leaf | Новый cert работает, старый serial отвергнут обеими API | Negative tests старого cert проходят; image ID до/после одинаков | Короткий restart трёх TLS listeners; данные сохранены | +| Истечение OpenBao token | После TTL чтение KV запрещено | После lease_duration + 2s ответ 403 | TTL 60s; приложение получает новые tokens cert auth | +| Seal OpenBao, затем unseal | Нет бесконечной работы на старых secrets; восстановление после оператора | Через 70s API not ready, worker/dispatcher/cleanup child остановлены; после unseal saved checks проходят | Cache до 60s плюс poll/request/stop задержки; проверка восстановления в пределах 45s, без потери проверенных данных | +| Недоверенная/чужая TLS identity, запрещённые ACL операции | Отказ без plaintext fallback | Отрицательные проверки проходят во всей матрице | Данные не изменены | + +Scan приложения до/после обновления Python/Pillow: Debian CRITICAL 9 → 2, HIGH 145 → 100; Python CRITICAL 5 → 0, HIGH 40 → 3. Сохранены все оставшиеся находки в CSV и разбор применимости. Полные Trivy JSON сохранены локально в evidence/raw/ и исключены из Git как объёмный дубликат; сводка/CSV входят в сдачу. Scan не означает отсутствие уязвимостей. Проверка telemetry читает живые metrics/logs и до 20 trace bodies, ищет реальные service credentials и синтетические secrets/canary, не записывая их в evidence. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Переживается отказ одной API и управляемый restart стенда с сохранёнными volumes. PostgreSQL, LB, Redis, S3, OpenBao и Docker-host остаются единичными точками отказа; backup/HA не заявляются. +- TLS sidecars и локальные hops доверяют владельцу host/namespace. Операторские CA/root/unseal материалы хранятся локально; автоматического renewal/CA rollover нет. Перед повторной демонстрацией через сутки нужно renew-leaves. +- При недоступном Redis login закрывается с 503; sealed OpenBao после ограниченного кеша останавливает работу. Это выбранное fail-closed поведение с потерей доступности. +- Rate limit ограничивает общий ресурс, но атакующий может исчерпать бюджет законных пользователей. Полноценный нагрузочный login-DoS эксперимент и tuning сверх измерения hash не проводились. +- В app image остаются CVE; применимость/mitigation и принятые учебные риски перечислены в SCAN_TRIAGE. Образы сторонней инфраструктуры этим scan не охвачены. Перед внешним развёртыванием нужен отдельный patch review, особенно реально используемых библиотек; это следующий шаг, а не выполненная работа. +- Проверки показывают выбранные негативные сценарии и отсутствие заданных canaries в выборке telemetry, но не доказывают отсутствие любых утечек. Последний повторный bootstrap выполнен на существующих volumes; полное удаление данных ради повторной проверки чистого clone не выполнялось. Запуск и файловые права проверены на Windows Docker Desktop; Linux host требует отдельной проверки прав bind mounts. diff --git a/compose.yaml b/compose.yaml index f16ee99..2cf6ad0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,313 +1,685 @@ -x-api: &api - image: mtusi2026lab7-api:local - pull_policy: never - dns_opt: - - timeout:1 - - attempts:1 - environment: &app-env - APP_HOST: 0.0.0.0 - APP_PORT: 8080 - POSTGRES_HOST: postgres - POSTGRES_DB: ${POSTGRES_DB:-messenger} - POSTGRES_USER: ${POSTGRES_USER:-messenger} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} - REDIS_URL: redis://redis:6379/0 - SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} - CACHE_TTL_SECONDS: ${CACHE_TTL_SECONDS:-30} - MAX_REQUEST_BYTES: ${MAX_REQUEST_BYTES:-65536} - MAX_INFLIGHT: ${MAX_INFLIGHT:-32} - S3_ENDPOINT: http://s3:9000 - S3_REGION: us-east-1 - S3_BUCKET: messenger-attachments - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} - MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} - MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} - MAX_PENDING_ATTACHMENTS: ${MAX_PENDING_ATTACHMENTS:-64} - BROKER_URL: redis://broker:6379/0 - WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} - JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} - JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} - JOB_MEMORY_MB: ${JOB_MEMORY_MB:-768} - STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} - OTEL_SERVICE_NAME: messenger-api - OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 - OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} - networks: [backend] - cpus: 1.0 - mem_limit: 512m - stop_grace_period: 10s - +name: mtusi2026lab7 services: - broker: - image: redis:7.4.2-bookworm - command: [redis-server, --appendonly, 'yes', --appendfsync, always, --maxmemory, 128mb, --maxmemory-policy, noeviction] - volumes: - - broker_data:/data - networks: [backend] - healthcheck: - test: [CMD, redis-cli, ping] - interval: 2s - timeout: 2s - retries: 30 - cpus: 0.5 - mem_limit: 256m - - dispatcher: - <<: *api - environment: - <<: *app-env - OTEL_SERVICE_NAME: messenger-dispatcher - command: [python, -m, src.jobs, dispatch] - healthcheck: - disable: true - depends_on: - migrate: - condition: service_completed_successfully - broker: - condition: service_healthy + api1: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: &drop_all_capabilities + - ALL + security_opt: &no_new_privileges + - no-new-privileges:true + tmpfs: &runtime_tmpfs + - /tmp:rw,noexec,nosuid,size=64m restart: unless-stopped - mem_limit: 128m - - worker: - <<: *api + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src environment: - <<: *app-env - OTEL_SERVICE_NAME: messenger-worker - command: [python, -m, src.worker] + SERVICE_ROLE: api + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + volumes: + - ./secrets/api:/run/identity:ro init: true healthcheck: disable: true - depends_on: - migrate: - condition: service_completed_successfully - broker: - condition: service_healthy - s3-init: - condition: service_completed_successfully + pids_limit: 64 + stop_grace_period: 15s + api1-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/api1:/run/identity:ro + - ./infra/tls/api1.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:api1 + depends_on: + - api1 + api2: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src + environment: + SERVICE_ROLE: api + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + volumes: + - ./secrets/api:/run/identity:ro + init: true + healthcheck: + disable: true + pids_limit: 64 + stop_grace_period: 15s + api2-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/api2:/run/identity:ro + - ./infra/tls/api2.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:api2 + depends_on: + - api2 + worker: + image: mtusi2026lab7-api:local + networks: + - backend cpus: 2.0 mem_limit: 2g - pids_limit: 64 - - api: - <<: *api - build: . - deploy: - replicas: 2 - depends_on: - migrate: - condition: service_completed_successfully - redis: - condition: service_healthy - s3-init: - condition: service_completed_successfully - healthcheck: - test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=1).read()"] - interval: 2s - timeout: 2s - start_period: 5s - retries: 2 - - migrate: - <<: *api - environment: - <<: *app-env - OTEL_SDK_DISABLED: 'true' - command: [python, -m, src.database] - healthcheck: - disable: true - restart: 'no' - depends_on: - postgres: - condition: service_healthy - - s3: - # RELEASE.2025-09-07T16-13-09Z, pinned by immutable image digest. - image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e - command: [server, /data, --console-address, '127.0.0.1:9001'] - environment: - MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} - MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} - MINIO_BROWSER: 'off' - volumes: - - s3_data:/data - networks: [backend] - healthcheck: - test: [CMD, curl, -f, http://127.0.0.1:9000/minio/health/live] - interval: 2s - timeout: 2s - retries: 30 - cpus: 1.0 - mem_limit: 512m - - s3-init: - # The pinned server image also contains mc; no second image is needed. - image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e - entrypoint: [sh, /bootstrap.sh] - environment: - MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env} - MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env} - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:?Set S3_ACCESS_KEY_ID in .env} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:?Set S3_SECRET_ACCESS_KEY in .env} - volumes: - - ./infra/s3-bootstrap.sh:/bootstrap.sh:ro - - ./infra/s3-policy.json:/policy.json:ro - depends_on: - s3: - condition: service_healthy - networks: [backend] - restart: 'no' - cpus: 0.25 - mem_limit: 128m - - cleanup: - <<: *api - environment: - <<: *app-env - OTEL_SDK_DISABLED: 'true' - command: [python, -m, src.cleanup] - healthcheck: - disable: true - depends_on: - migrate: - condition: service_completed_successfully - s3-init: - condition: service_completed_successfully + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - cpus: 0.25 - mem_limit: 128m - - nginx: - image: nginx:1.28.0-alpine - entrypoint: [sh, /etc/nginx/readiness.sh] - dns_opt: - - timeout:1 - - attempts:1 - ports: - - '127.0.0.1:${APP_PORT:-8080}:8080' + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src.worker + environment: + SERVICE_ROLE: worker + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-worker + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' volumes: - - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro - - ./infra/readiness.sh:/etc/nginx/readiness.sh:ro - networks: [edge, backend] - depends_on: - api: - condition: service_healthy + - ./secrets/worker:/run/identity:ro + init: true healthcheck: - test: [CMD-SHELL, 'wget -q -O /dev/null http://127.0.0.1:8080/health/ready'] - interval: 2s - timeout: 2s - retries: 3 + disable: true + pids_limit: 64 + stop_grace_period: 15s + dispatcher: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src.jobs + - dispatch + environment: + SERVICE_ROLE: dispatcher + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-dispatcher + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + volumes: + - ./secrets/dispatcher:/run/identity:ro + init: true + healthcheck: + disable: true + pids_limit: 64 + stop_grace_period: 15s + cleanup: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 1.0 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + build: . + pull_policy: never + user: 1000:1000 + entrypoint: + - python + - -m + - src.secure_run + command: + - python + - -m + - src.cleanup + environment: + SERVICE_ROLE: cleanup + APP_HOST: 127.0.0.1 + APP_PORT: '8080' + OTEL_SERVICE_NAME: messenger-cleanup + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:44318 + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/identity/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/identity/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/identity/tls.key + WORKER_CONCURRENCY: '2' + JOB_MEMORY_MB: '768' + JOB_TIMEOUT_SECONDS: '60' + OTEL_SDK_DISABLED: 'true' + volumes: + - ./secrets/cleanup:/run/identity:ro + init: true + healthcheck: + disable: true + pids_limit: 64 + stop_grace_period: 15s + lb: + image: haproxy:3.0.12-alpine + networks: + - edge + - backend cpus: 0.5 - mem_limit: 128m - stop_grace_period: 10s - + mem_limit: 96m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + ports: + - 127.0.0.1:8443:8443 + volumes: + - ./secrets/lb:/run/identity:ro + - ./infra/tls/lb.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro postgres: image: postgres:17.4-bookworm - environment: - POSTGRES_DB: ${POSTGRES_DB:-messenger} - POSTGRES_USER: ${POSTGRES_USER:-messenger} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} - volumes: - - postgres_data:/var/lib/postgresql/data - networks: [backend] - healthcheck: - test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] - interval: 2s - timeout: 2s - retries: 30 + networks: + - backend cpus: 1.0 mem_limit: 512m - + read_only: true + cap_drop: + - ALL + security_opt: *no_new_privileges + tmpfs: + - /tmp:rw,nosuid,size=16m + - /var/run/postgresql:rw,nosuid,size=16m + restart: unless-stopped + cap_add: + - CHOWN + - DAC_OVERRIDE + - FOWNER + - SETGID + - SETUID + environment: + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/admin/postgres-password + volumes: + - type: volume + source: postgres_data + target: /var/lib/postgresql/data + volume: + nocopy: true + - ./secrets/postgres:/run/identity:ro + - ./secrets/postgres-admin:/run/admin:ro + - ./infra/postgres/pg_hba.conf:/etc/pg_hba.conf:ro + - ./infra/postgres/start.sh:/start.sh:ro + entrypoint: + - sh + - /start.sh redis: image: redis:7.4.2-bookworm - command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always", "--maxmemory", "128mb", "--maxmemory-policy", "noeviction"] - volumes: - - redis_data:/data - networks: [backend] - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 2s - timeout: 2s - retries: 30 + networks: + - backend cpus: 0.5 mem_limit: 256m - + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 999:999 + command: + - redis-server + - /run/config/redis.conf + volumes: + - type: volume + source: redis_data + target: /data + volume: + nocopy: true + - ./secrets/redis-config:/run/config:ro + redis-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/redis:/run/identity:ro + - ./infra/tls/redis.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:redis + depends_on: + - redis + broker: + image: redis:7.4.2-bookworm + networks: + - backend + cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 999:999 + command: + - redis-server + - /run/config/redis.conf + volumes: + - type: volume + source: broker_data + target: /data + volume: + nocopy: true + - ./secrets/broker-config:/run/config:ro + broker-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/broker:/run/identity:ro + - ./infra/tls/broker.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:broker + depends_on: + - broker + s3: + image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + networks: + - backend + cpus: 1.0 + mem_limit: 512m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 1000:1000 + entrypoint: + - sh + - -c + command: + - export MINIO_ROOT_USER=$$(cat /run/admin/user); export MINIO_ROOT_PASSWORD=$$(cat + /run/admin/password); exec minio server /data --address 127.0.0.1:9000 --console-address + 127.0.0.1:9001 + environment: + MINIO_BROWSER: 'off' + volumes: + - type: volume + source: s3_data + target: /data + volume: + nocopy: true + - ./secrets/s3-admin:/run/admin:ro + s3-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/s3:/run/identity:ro + - ./infra/tls/s3.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:s3 + depends_on: + - s3 + openbao: + image: openbao/openbao:2.4.4 + networks: + - edge + - backend + cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 100:1000 + entrypoint: + - bao + command: + - server + - -config=/etc/bao/config.hcl + volumes: + - type: volume + source: bao_data + target: /bao/data + volume: + nocopy: true + - ./secrets/openbao:/run/identity:ro + - ./infra/openbao/config.hcl:/etc/bao/config.hcl:ro + ports: + - 127.0.0.1:8200:8200 otel-collector: image: otel/opentelemetry-collector-contrib:0.136.0 - command: [--config=/etc/otel/collector.yaml] - volumes: - - ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro - networks: [backend] - mem_limit: 256m + networks: + - backend cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 1000:1000 + command: + - --config=/etc/otel/config.yaml + volumes: + - ./secrets/otel-collector:/run/identity:ro + - ./infra/otel/collector.yaml:/etc/otel/config.yaml:ro + otel-collector-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/otel-collector:/run/identity:ro + - ./infra/tls/otel-collector.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:otel-collector + depends_on: + - otel-collector prometheus: image: prom/prometheus:v3.6.0 - command: [--config.file=/etc/prometheus/prometheus.yaml, --storage.tsdb.retention.time=3d] - volumes: - - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro - - ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro - - prometheus_data:/prometheus - ports: ['127.0.0.1:9090:9090'] - networks: [edge, backend] - mem_limit: 512m + networks: + - backend cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 65534:65534 + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.retention.time=3d + - --web.listen-address=127.0.0.1:9090 + volumes: + - type: volume + source: prometheus_data + target: /prometheus + volume: + nocopy: true + - ./secrets/prometheus:/run/identity:ro + - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro + - ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro + prometheus-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/prometheus:/run/identity:ro + - ./infra/tls/prometheus.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:prometheus + depends_on: + - prometheus loki: image: grafana/loki:3.5.7 - command: [-config.file=/etc/loki/local.yaml] - volumes: - - ./infra/otel/loki.yaml:/etc/loki/local.yaml:ro - - loki_data:/loki - ports: ['127.0.0.1:3100:3100'] - networks: [edge, backend] - mem_limit: 384m + networks: + - backend cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 1000:1000 + command: + - -config.file=/etc/config.yaml + volumes: + - type: volume + source: loki_data + target: /loki + volume: + nocopy: true + - ./infra/otel/loki.yaml:/etc/config.yaml:ro + loki-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/loki:/run/identity:ro + - ./infra/tls/loki.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:loki + depends_on: + - loki tempo: image: grafana/tempo:2.9.0 - command: [-config.file=/etc/tempo.yaml] - volumes: - - ./infra/otel/tempo.yaml:/etc/tempo.yaml:ro - - tempo_data:/var/tempo - ports: ['127.0.0.1:3200:3200'] - networks: [edge, backend] - mem_limit: 384m + networks: + - backend cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 1000:1000 + command: + - -config.file=/etc/config.yaml + volumes: + - type: volume + source: tempo_data + target: /var/tempo + volume: + nocopy: true + - ./infra/otel/tempo.yaml:/etc/config.yaml:ro + tempo-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 65532:65532 + volumes: + - ./secrets/tempo:/run/identity:ro + - ./infra/tls/tempo.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:tempo + depends_on: + - tempo grafana: image: grafana/grafana:12.2.0 + networks: + - edge + - backend + cpus: 0.5 + mem_limit: 384m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: unless-stopped + user: 472:472 environment: + GF_SERVER_HTTP_ADDR: 127.0.0.1 GF_SECURITY_ADMIN_USER: admin - GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env} + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/admin/password GF_USERS_ALLOW_SIGN_UP: 'false' + GF_AUTH_ANONYMOUS_ENABLED: 'false' GF_ANALYTICS_REPORTING_ENABLED: 'false' GF_ANALYTICS_CHECK_FOR_UPDATES: 'false' + GF_PLUGINS_PREINSTALL_DISABLED: 'true' volumes: - - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro - - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro - - grafana_data:/var/lib/grafana - ports: ['127.0.0.1:3000:3000'] - networks: [edge, backend] - mem_limit: 384m - cpus: 0.5 + - type: volume + source: grafana_data + target: /var/lib/grafana + volume: + nocopy: true + - ./secrets/grafana-admin:/run/admin:ro + - ./secrets/grafana-datasources:/etc/grafana/provisioning/datasources:ro + - ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + ports: + - 127.0.0.1:3443:3443 + grafana-tls: + image: haproxy:3.0.12-alpine + cpus: 0.25 + mem_limit: 64m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs restart: unless-stopped - + user: 65532:65532 + volumes: + - ./secrets/grafana:/run/identity:ro + - ./infra/tls/grafana.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + network_mode: service:grafana + depends_on: + - grafana + audit: + image: mtusi2026lab7-api:local + networks: + - backend + cpus: 0.5 + mem_limit: 256m + read_only: true + cap_drop: *drop_all_capabilities + security_opt: *no_new_privileges + tmpfs: *runtime_tmpfs + restart: 'no' + profiles: + - tools + user: 1000:1000 + entrypoint: + - python + command: + - /audit/internal.py + volumes: + - ./student-tests:/audit:ro + - ./secrets:/audit-secrets:ro + - ./evidence:/evidence + - ./tests:/tests:ro + - ./contracts:/contracts:ro + - ./lab.json:/lab.json:ro + healthcheck: + disable: true networks: - edge: backend: internal: true + edge: {} volumes: - broker_data: - postgres_data: - redis_data: - s3_data: - prometheus_data: - loki_data: - tempo_data: - grafana_data: + postgres_data: {} + redis_data: {} + broker_data: {} + s3_data: {} + bao_data: {} + prometheus_data: {} + loki_data: {} + tempo_data: {} + grafana_data: {} diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..3ac869f 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,33 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +CA: secrets/ca.crt, 30 дней. Leaf: 24 часа; DNS SAN равен имени сервиса, публичные +сертификаты также содержат localhost и 127.0.0.1. HAProxy проверяет цепочку, срок, +CRL и разрешённый CN (роль, выпускаемую оператором); одного доверенного CA недостаточно. +Конфиги: infra/tls/*.cfg, compose.yaml, infra/openbao/*.hcl. -| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | +| Связь | Transport/identity | Права и lifecycle | Проверка | | --- | --- | --- | --- | -| Клиент → 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 | +| Клиент → LB | https://localhost:8443, CA+SAN, Bearer | Redis sessions 3600s, hash ключа, logout; общий login budget | smoke/security, internal expiry/rate | +| LB → API1/API2 | mTLS :8443, client CN=lb; verifyhost api1/api2 | CRL; leaf 24h | internal negatives на каждой реплике, lifecycle rotation | +| API/worker/dispatcher/cleanup → PostgreSQL | postgres:5432 native TLS verify-full, SCRAM, отдельные roles | API DML; worker/dispatcher SELECT/UPDATE attachments/jobs; cleanup attachments; без DDL/superuser | internal DB grants; lifecycle password rotation | +| API/worker/cleanup → S3 | https://s3:9443, CA/SAN + отдельные SigV4 users | API пишет staging, читает originals/variants; worker читает staging, пишет originals/variants; cleanup читает/удаляет; без admin | internal denied prefixes, smoke | +| API/dispatcher/worker → broker | broker:6380, mTLS CN api/dispatcher/worker + Redis ACL | API ping; dispatcher XADD/XGROUP CREATE; worker consume/ack/delete/XGROUP CREATE; ключ attachment-jobs | internal mTLS и запрещённые команды | +| API/worker/dispatcher → Collector | https://otel-collector:44318, mTLS CN api/worker/dispatcher | Только OTLP ingest; разные leaf keys | internal negatives и положительные пробы всех ролей | +| Collector → Loki/Tempo | https://loki:13100/otlp и https://tempo:14318, mTLS CN otel-collector | POST ingest paths | internal TLS; lifecycle живые сигналы | +| Prometheus → Collector | HTTPS :18889 и :18888 /metrics, mTLS CN prometheus | Metrics scrape | internal TLS и запрет plaintext обхода | +| Grafana → sources | https://prometheus:19090, loki:13100, tempo:13200, mTLS CN grafana | GET/HEAD + query POST Prometheus; TLS SAN; private key в generated secret provisioning | internal outsider; lifecycle запрещённый POST | +| API/worker/dispatcher/cleanup → OpenBao | https://openbao:8200, TLS + cert auth с CN/DNS SAN роли | Только secret/data/своя-роль; token TTL/maxTTL 60s, новый cert auth каждые 10s | internal own/other KV, lifecycle expiry/sealed | +| Оператор → OpenBao | https://127.0.0.1:8200, CA + operator token | Root только у оператора; init/unseal не в app | bootstrap, mounts | +| Оператор → Grafana | https://localhost:3443, CA/SAN + отдельный admin password | Host loopback; login обязателен | HTTPS/login | +| Оператор → S3 admin | Docker exec → локальный 127.0.0.1:9000 + admin auth | Не сетевой канал; Docker-host доверенный, console не опубликована | bootstrap, inspect ports | +| API → Redis | rediss://redis:6380, CA/SAN + ACL user api | session:*, history-v4:*, login:*; без CONFIG/FLUSHALL/ACL | internal TLS/session digest/expiry | +| Replication | N/A: один PostgreSQL, Redis и S3; два API без peer-to-peer | HA host/DB/LB не заявляется | Failover только API | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +Plaintext HAProxy→service находится только на 127.0.0.1 в одном network namespace +(network_mode: service:...), без публикации. Internal тест проверяет каждый такой порт +снаружи namespace. PostgreSQL не допускает hostnossl. LB readiness использует mTLS. +SQL bootstrap — Unix socket, S3 bootstrap — docker exec loopback, только оператор. +Внешний /health не предоставляет обхода бизнес-API. Кластерные каналы не используются. -## Обязательные отрицательные проверки - -1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». -2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. -3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. -4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. -5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. -6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. - -## Bootstrap и эксплуатация - -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. - -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. +Проверка: python scripts/lab7.py verify. Evidence содержит команды/результаты. +Ротация: rotate-leaf, rotate-secret. Эксплуатация: security/OPERATIONS.md. diff --git a/evidence/README.md b/evidence/README.md index 8df7001..e6836e0 100644 --- a/evidence/README.md +++ b/evidence/README.md @@ -1,5 +1,19 @@ -# Доказательства +# Evidence lab7 -Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. +Команда проверки: `python scripts/lab7.py verify` после `bootstrap`. -Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. +- `smoke.txt`, `security.txt`: неизменённые публичные tests через HTTPS. +- `internal.json`, `internal.txt`: фактические mTLS/ACL/rehash/expiry/rate/Argon2 проверки. +- `lifecycle.json`: отказ каждой API, сохранность после restart, secret/leaf rotation, + отзыв старых credentials, OpenBao expiry/sealed/recovery, telemetry и hardening. +- `telemetry.json`: живые сигналы, проверка утечек и доступ Grafana к TLS sources. +- `environment.json`: CPU/RAM стенда, image ID и лимиты каждого сервиса. +- `verification.txt`: offline contract check и синтаксис Python. +- `scan-summary.json`, `scan-findings.csv`: сводка до/после и все находки повторного scan. +- `raw/image-scan.json`, `raw/image-scan-updated.json`: полные локальные Trivy reports + до/после; сохранены у оператора, исключены из Git из-за объёма и дублирования CSV. +- `security/SCAN_TRIAGE.md` в корне проекта: применимость и остаточные риски. + +JSON тестов содержит только реально пройденные проверки. При неуспешном запуске +lifecycle сохраняет промежуточный результат; признак полного успеха — последняя запись +`Complete lifecycle suite`. Tokens/passwords/keys не включаются в результаты. diff --git a/evidence/environment.json b/evidence/environment.json new file mode 100644 index 0000000..807af98 --- /dev/null +++ b/evidence/environment.json @@ -0,0 +1,379 @@ +{ + "cpus": 8, + "memory_bytes": 8328019968, + "os": "Docker Desktop", + "architecture": "x86_64", + "app_image": "sha256:8ce282347ac73e6fd187038941b84d16df7cceede5a47e8310f381ae0275e3f6", + "services": { + "api1": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "api1-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "api2": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "api2-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "broker": { + "image": "redis:7.4.2-bookworm", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "999:999", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "broker-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "cleanup": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "dispatcher": { + "image": "mtusi2026lab7-api:local", + "cpus": 1, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "grafana": { + "image": "grafana/grafana:12.2.0", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "472:472", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "grafana-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "lb": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.5, + "mem_limit": "100663296", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "loki": { + "image": "grafana/loki:3.5.7", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "loki-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "openbao": { + "image": "openbao/openbao:2.4.4", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "100:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "otel-collector": { + "image": "otel/opentelemetry-collector-contrib:0.136.0", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "otel-collector-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "postgres": { + "image": "postgres:17.4-bookworm", + "cpus": 1, + "mem_limit": "536870912", + "user": null, + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": [ + "CHOWN", + "DAC_OVERRIDE", + "FOWNER", + "SETGID", + "SETUID" + ], + "security_opt": [ + "no-new-privileges:true" + ] + }, + "prometheus": { + "image": "prom/prometheus:v3.6.0", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "65534:65534", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "prometheus-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "redis": { + "image": "redis:7.4.2-bookworm", + "cpus": 0.5, + "mem_limit": "268435456", + "user": "999:999", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "redis-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "s3": { + "image": "minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e", + "cpus": 1, + "mem_limit": "536870912", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "s3-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "tempo": { + "image": "grafana/tempo:2.9.0", + "cpus": 0.5, + "mem_limit": "402653184", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "tempo-tls": { + "image": "haproxy:3.0.12-alpine", + "cpus": 0.25, + "mem_limit": "67108864", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + }, + "worker": { + "image": "mtusi2026lab7-api:local", + "cpus": 2, + "mem_limit": "2147483648", + "user": "1000:1000", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "cap_add": null, + "security_opt": [ + "no-new-privileges:true" + ] + } + } +} \ No newline at end of file diff --git a/evidence/internal.json b/evidence/internal.json new file mode 100644 index 0000000..035f5da --- /dev/null +++ b/evidence/internal.json @@ -0,0 +1,514 @@ +{ + "checks": [ + { + "test": "Oversized HTTP/JSON trace context has bounded parsing cost", + "passed": true + }, + { + "test": "Valid trace context remains supported", + "passed": true + }, + { + "test": "api1 accepts allowed identity", + "passed": true + }, + { + "test": "api1 rejects None", + "passed": true + }, + { + "test": "api1 rejects foreign-lb", + "passed": true + }, + { + "test": "api1 rejects outsider", + "passed": true + }, + { + "test": "api1 rejects expired-lb", + "passed": true + }, + { + "test": "api1 rejects revoked LB serial", + "passed": true + }, + { + "test": "api2 accepts allowed identity", + "passed": true + }, + { + "test": "api2 rejects None", + "passed": true + }, + { + "test": "api2 rejects foreign-lb", + "passed": true + }, + { + "test": "api2 rejects outsider", + "passed": true + }, + { + "test": "api2 rejects expired-lb", + "passed": true + }, + { + "test": "api2 rejects revoked LB serial", + "passed": true + }, + { + "test": "broker accepts allowed identity", + "passed": true + }, + { + "test": "broker rejects None", + "passed": true + }, + { + "test": "broker rejects foreign-worker", + "passed": true + }, + { + "test": "broker rejects outsider", + "passed": true + }, + { + "test": "broker rejects expired-worker", + "passed": true + }, + { + "test": "otel-collector accepts allowed identity", + "passed": true + }, + { + "test": "otel-collector rejects None", + "passed": true + }, + { + "test": "otel-collector rejects foreign-api", + "passed": true + }, + { + "test": "otel-collector rejects outsider", + "passed": true + }, + { + "test": "otel-collector rejects expired-api", + "passed": true + }, + { + "test": "Collector accepts worker", + "passed": true + }, + { + "test": "Collector accepts dispatcher", + "passed": true + }, + { + "test": "lb server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "lb rejects wrong hostname", + "passed": true + }, + { + "test": "redis server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "redis rejects wrong hostname", + "passed": true + }, + { + "test": "s3 server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "s3 rejects wrong hostname", + "passed": true + }, + { + "test": "grafana server TLS verified", + "passed": true, + "protocol": "TLSv1.3" + }, + { + "test": "grafana rejects wrong hostname", + "passed": true + }, + { + "test": "openbao server TLS verified", + "passed": true, + "protocol": "TLSv1.2" + }, + { + "test": "openbao rejects wrong hostname", + "passed": true + }, + { + "test": "prometheus:19090 trusted identity", + "passed": true + }, + { + "test": "prometheus:19090 rejects outsider", + "passed": true + }, + { + "test": "loki:13100 trusted identity", + "passed": true + }, + { + "test": "loki:13100 rejects outsider", + "passed": true + }, + { + "test": "tempo:13200 trusted identity", + "passed": true + }, + { + "test": "tempo:13200 rejects outsider", + "passed": true + }, + { + "test": "otel-collector:18889 trusted identity", + "passed": true + }, + { + "test": "otel-collector:18889 rejects outsider", + "passed": true + }, + { + "test": "otel-collector:18888 trusted identity", + "passed": true + }, + { + "test": "otel-collector:18888 rejects outsider", + "passed": true + }, + { + "test": "tempo:14318 trusted identity", + "passed": true + }, + { + "test": "tempo:14318 rejects outsider", + "passed": true + }, + { + "test": "No plaintext bypass api1:8080", + "passed": true + }, + { + "test": "No plaintext bypass api2:8080", + "passed": true + }, + { + "test": "No plaintext bypass broker:6379", + "passed": true + }, + { + "test": "No plaintext bypass redis:6379", + "passed": true + }, + { + "test": "No plaintext bypass s3:9000", + "passed": true + }, + { + "test": "No plaintext bypass otel-collector:4318", + "passed": true + }, + { + "test": "No plaintext bypass otel-collector:8888", + "passed": true + }, + { + "test": "No plaintext bypass otel-collector:8889", + "passed": true + }, + { + "test": "No plaintext bypass prometheus:9090", + "passed": true + }, + { + "test": "No plaintext bypass loki:3100", + "passed": true + }, + { + "test": "No plaintext bypass loki:9095", + "passed": true + }, + { + "test": "No plaintext bypass tempo:3200", + "passed": true + }, + { + "test": "No plaintext bypass tempo:4318", + "passed": true + }, + { + "test": "No plaintext bypass tempo:9095", + "passed": true + }, + { + "test": "No plaintext bypass grafana:3000", + "passed": true + }, + { + "test": "PostgreSQL TLS api", + "passed": true + }, + { + "test": "DB no DDL api", + "passed": true + }, + { + "test": "OpenBao cert auth api", + "passed": true + }, + { + "test": "OpenBao short TTL api", + "passed": true + }, + { + "test": "OpenBao own KV api", + "passed": true + }, + { + "test": "OpenBao other KV denied api", + "passed": true + }, + { + "test": "OpenBao policy write denied api", + "passed": true + }, + { + "test": "PostgreSQL TLS worker", + "passed": true + }, + { + "test": "DB no DDL worker", + "passed": true + }, + { + "test": "DB password hashes denied worker", + "passed": true + }, + { + "test": "OpenBao cert auth worker", + "passed": true + }, + { + "test": "OpenBao short TTL worker", + "passed": true + }, + { + "test": "OpenBao own KV worker", + "passed": true + }, + { + "test": "OpenBao other KV denied worker", + "passed": true + }, + { + "test": "OpenBao policy write denied worker", + "passed": true + }, + { + "test": "PostgreSQL TLS dispatcher", + "passed": true + }, + { + "test": "DB no DDL dispatcher", + "passed": true + }, + { + "test": "DB password hashes denied dispatcher", + "passed": true + }, + { + "test": "OpenBao cert auth dispatcher", + "passed": true + }, + { + "test": "OpenBao short TTL dispatcher", + "passed": true + }, + { + "test": "OpenBao own KV dispatcher", + "passed": true + }, + { + "test": "OpenBao other KV denied dispatcher", + "passed": true + }, + { + "test": "OpenBao policy write denied dispatcher", + "passed": true + }, + { + "test": "PostgreSQL TLS cleanup", + "passed": true + }, + { + "test": "DB no DDL cleanup", + "passed": true + }, + { + "test": "DB password hashes denied cleanup", + "passed": true + }, + { + "test": "OpenBao cert auth cleanup", + "passed": true + }, + { + "test": "OpenBao short TTL cleanup", + "passed": true + }, + { + "test": "OpenBao own KV cleanup", + "passed": true + }, + { + "test": "OpenBao other KV denied cleanup", + "passed": true + }, + { + "test": "OpenBao policy write denied cleanup", + "passed": true + }, + { + "test": "OpenBao outsider denied", + "passed": true + }, + { + "test": "Broker authenticated api", + "passed": true + }, + { + "test": "Broker ACL denied api", + "passed": true + }, + { + "test": "Broker authenticated worker", + "passed": true + }, + { + "test": "Broker ACL denied worker", + "passed": true + }, + { + "test": "Broker authenticated dispatcher", + "passed": true + }, + { + "test": "Broker ACL denied dispatcher", + "passed": true + }, + { + "test": "S3 denied write prefix api", + "passed": true + }, + { + "test": "S3 denied write prefix worker", + "passed": true + }, + { + "test": "S3 denied write prefix cleanup", + "passed": true + }, + { + "test": "Old Argon2 login succeeds", + "passed": true + }, + { + "test": "Password rehashed", + "passed": true + }, + { + "test": "Session stores digest key, no credential", + "passed": true + }, + { + "test": "Expired session rejected", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit carries Retry-After", + "passed": true + }, + { + "test": "Rate limit shared across replicas", + "passed": true, + "instances": 2, + "statuses": [ + 401, + 401, + 401, + 401, + 401, + 401, + 401, + 401, + 429, + 429, + 429, + 429 + ] + }, + { + "test": "Measured Argon2 budget", + "passed": true, + "memory_kib": 19456, + "time_cost": 2, + "parallelism": 1, + "median_ms": 72.59, + "p95_ms": 93.82, + "p99_ms": 100.27, + "samples_ms": [ + 39.139, + 70.695, + 22.805, + 79.572, + 26.963, + 82.623, + 100.27, + 85.038, + 25.732, + 77.702, + 26.895, + 77.439, + 26.264, + 74.49, + 24.908, + 75.369, + 93.821, + 31.636, + 79.445, + 23.472 + ], + "duration_seconds": 1.144, + "cpu_seconds": 0.592, + "process_peak_rss_kib": 102728, + "global_limit_per_second": 32, + "account_limit_per_10seconds": 8, + "hash_concurrency_per_api": 2 + } + ] +} \ No newline at end of file diff --git a/evidence/internal.txt b/evidence/internal.txt new file mode 100644 index 0000000..7f973bc --- /dev/null +++ b/evidence/internal.txt @@ -0,0 +1,115 @@ +PASS: Oversized HTTP/JSON trace context has bounded parsing cost +PASS: Valid trace context remains supported +PASS: api1 accepts allowed identity +PASS: api1 rejects None +PASS: api1 rejects foreign-lb +PASS: api1 rejects outsider +PASS: api1 rejects expired-lb +PASS: api1 rejects revoked LB serial +PASS: api2 accepts allowed identity +PASS: api2 rejects None +PASS: api2 rejects foreign-lb +PASS: api2 rejects outsider +PASS: api2 rejects expired-lb +PASS: api2 rejects revoked LB serial +PASS: broker accepts allowed identity +PASS: broker rejects None +PASS: broker rejects foreign-worker +PASS: broker rejects outsider +PASS: broker rejects expired-worker +PASS: otel-collector accepts allowed identity +PASS: otel-collector rejects None +PASS: otel-collector rejects foreign-api +PASS: otel-collector rejects outsider +PASS: otel-collector rejects expired-api +PASS: Collector accepts worker +PASS: Collector accepts dispatcher +PASS: lb server TLS verified +PASS: lb rejects wrong hostname +PASS: redis server TLS verified +PASS: redis rejects wrong hostname +PASS: s3 server TLS verified +PASS: s3 rejects wrong hostname +PASS: grafana server TLS verified +PASS: grafana rejects wrong hostname +PASS: openbao server TLS verified +PASS: openbao rejects wrong hostname +PASS: prometheus:19090 trusted identity +PASS: prometheus:19090 rejects outsider +PASS: loki:13100 trusted identity +PASS: loki:13100 rejects outsider +PASS: tempo:13200 trusted identity +PASS: tempo:13200 rejects outsider +PASS: otel-collector:18889 trusted identity +PASS: otel-collector:18889 rejects outsider +PASS: otel-collector:18888 trusted identity +PASS: otel-collector:18888 rejects outsider +PASS: tempo:14318 trusted identity +PASS: tempo:14318 rejects outsider +PASS: No plaintext bypass api1:8080 +PASS: No plaintext bypass api2:8080 +PASS: No plaintext bypass broker:6379 +PASS: No plaintext bypass redis:6379 +PASS: No plaintext bypass s3:9000 +PASS: No plaintext bypass otel-collector:4318 +PASS: No plaintext bypass otel-collector:8888 +PASS: No plaintext bypass otel-collector:8889 +PASS: No plaintext bypass prometheus:9090 +PASS: No plaintext bypass loki:3100 +PASS: No plaintext bypass loki:9095 +PASS: No plaintext bypass tempo:3200 +PASS: No plaintext bypass tempo:4318 +PASS: No plaintext bypass tempo:9095 +PASS: No plaintext bypass grafana:3000 +PASS: PostgreSQL TLS api +PASS: DB no DDL api +PASS: OpenBao cert auth api +PASS: OpenBao short TTL api +PASS: OpenBao own KV api +PASS: OpenBao other KV denied api +PASS: OpenBao policy write denied api +PASS: PostgreSQL TLS worker +PASS: DB no DDL worker +PASS: DB password hashes denied worker +PASS: OpenBao cert auth worker +PASS: OpenBao short TTL worker +PASS: OpenBao own KV worker +PASS: OpenBao other KV denied worker +PASS: OpenBao policy write denied worker +PASS: PostgreSQL TLS dispatcher +PASS: DB no DDL dispatcher +PASS: DB password hashes denied dispatcher +PASS: OpenBao cert auth dispatcher +PASS: OpenBao short TTL dispatcher +PASS: OpenBao own KV dispatcher +PASS: OpenBao other KV denied dispatcher +PASS: OpenBao policy write denied dispatcher +PASS: PostgreSQL TLS cleanup +PASS: DB no DDL cleanup +PASS: DB password hashes denied cleanup +PASS: OpenBao cert auth cleanup +PASS: OpenBao short TTL cleanup +PASS: OpenBao own KV cleanup +PASS: OpenBao other KV denied cleanup +PASS: OpenBao policy write denied cleanup +PASS: OpenBao outsider denied +PASS: Broker authenticated api +PASS: Broker ACL denied api +PASS: Broker authenticated worker +PASS: Broker ACL denied worker +PASS: Broker authenticated dispatcher +PASS: Broker ACL denied dispatcher +PASS: S3 denied write prefix api +PASS: S3 denied write prefix worker +PASS: S3 denied write prefix cleanup +PASS: Old Argon2 login succeeds +PASS: Password rehashed +PASS: Session stores digest key, no credential +PASS: Expired session rejected +PASS: Rate limit carries Retry-After +PASS: Rate limit carries Retry-After +PASS: Rate limit carries Retry-After +PASS: Rate limit carries Retry-After +PASS: Rate limit shared across replicas +PASS: Measured Argon2 budget +PASS: 114 internal checks diff --git a/evidence/lifecycle.json b/evidence/lifecycle.json new file mode 100644 index 0000000..33de649 --- /dev/null +++ b/evidence/lifecycle.json @@ -0,0 +1,72 @@ +[ + { + "test": "Cannot attach another chat file", + "passed": true + }, + { + "test": "Request size is bounded", + "passed": true + }, + { + "test": "Replica failover api1", + "passed": true, + "recovery_seconds": 1.67, + "failed_attempts": 1 + }, + { + "test": "Replica failover api2", + "passed": true, + "recovery_seconds": 1.25, + "failed_attempts": 0 + }, + { + "test": "Full restart preserves sessions, messages, original and processed attachment", + "passed": true + }, + { + "test": "Working DB secret rotated; old password rejected on new connection", + "passed": true + }, + { + "test": "Leaf rotated and old LB identity revoked on both replicas", + "passed": true + }, + { + "test": "Rotations do not rebuild image", + "passed": true, + "image": "sha256:8ce282347ac73e6fd187038941b84d16df7cceede5a47e8310f381ae0275e3f6" + }, + { + "test": "Expired OpenBao token denied", + "passed": true + }, + { + "test": "Sealed OpenBao stops API within bounded secret cache", + "passed": true, + "elapsed_seconds": 70.01 + }, + { + "test": "Sealed OpenBao stops background consumers too", + "passed": true + }, + { + "test": "Unseal recovers without baked-in fallback secret", + "passed": true + }, + { + "test": "Container logs do not expose credentials or private message", + "passed": true + }, + { + "test": "Live metrics/logs/traces have no credential leaks; datasource writes denied", + "passed": true + }, + { + "test": "All services have read_only, no-new-privileges, cap_drop and limits", + "passed": true + }, + { + "test": "Complete lifecycle suite", + "passed": true + } +] \ No newline at end of file diff --git a/evidence/scan-findings.csv b/evidence/scan-findings.csv new file mode 100644 index 0000000..bc1effb --- /dev/null +++ b/evidence/scan-findings.csv @@ -0,0 +1,398 @@ +type,package,installed,CVE,severity,fixed,status,title,url +debian,apt,2.6.2,CVE-2011-3374,LOW,,affected,"It was found that apt-key in apt, all versions, do not correctly valid ...",https://avd.aquasec.com/nvd/cve-2011-3374 +debian,bash,5.2.15-2+b13,TEMP-0841856-B18BAF,LOW,,affected,[Privilege escalation possible to other user than root],https://security-tracker.debian.org/tracker/TEMP-0841856-B18BAF +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,bsdutils,1:2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,coreutils,9.1-1,CVE-2016-2781,LOW,,will_not_fix,coreutils: Non-privileged session can escape to the parent session in chroot,https://avd.aquasec.com/nvd/cve-2016-2781 +debian,coreutils,9.1-1,CVE-2017-18018,LOW,,affected,coreutils: race condition vulnerability in chown and chgrp,https://avd.aquasec.com/nvd/cve-2017-18018 +debian,coreutils,9.1-1,CVE-2025-5278,LOW,,affected,coreutils: Heap Buffer Under-Read in GNU Coreutils sort via Key Specification,https://avd.aquasec.com/nvd/cve-2025-5278 +debian,coreutils,9.1-1,CVE-2026-56391,LOW,,affected,coreutils: GNU coreutils uniq: Denial of Service and information disclosure via out-of-bounds read with multibyte input,https://avd.aquasec.com/nvd/cve-2026-56391 +debian,coreutils,9.1-1,CVE-2026-56392,LOW,,affected,coreutils: GNU coreutils unexpand: Denial of Service via crafted tab stop values,https://avd.aquasec.com/nvd/cve-2026-56392 +debian,dash,0.5.12-2,CVE-2026-102473,LOW,,affected,dash: dash: Super-polynomial backtracking in pmatch when libc fnmatch is disabled,https://avd.aquasec.com/nvd/cve-2026-102473 +debian,dash,0.5.12-2,CVE-2026-102474,LOW,,affected,dash: dash: Heap out-of-bounds write in conv_escape via undersized Unicode escape reservation,https://avd.aquasec.com/nvd/cve-2026-102474 +debian,diffutils,1:3.8-4,CVE-2026-53910,LOW,,affected,diffutils: heap‑based buffer overflow due to multiple signed integer overflows in line‑mapping calculations,https://avd.aquasec.com/nvd/cve-2026-53910 +debian,dpkg,1.21.23,CVE-2026-91094,UNKNOWN,,fix_deferred,A directory traversal bug was discovered when unpacking 3.0 (quilt) so ...,https://avd.aquasec.com/nvd/cve-2026-91094 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-102010,MEDIUM,,fix_deferred,gcc-toolset-15-gcc: gcc: gcc-toolset-16: gcc: Denial of Service via use-after-free in binary heap erase_if,https://avd.aquasec.com/nvd/cve-2026-102010 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-114690,MEDIUM,,affected,gcc: Confirmed out-of-bounds read/write in libstdc++ parallel `std,https://avd.aquasec.com/nvd/cve-2026-114690 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-114691,MEDIUM,,affected,gcc: Integer wrap in `std,https://avd.aquasec.com/nvd/cve-2026-114691 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-125709,MEDIUM,,fix_deferred,libstdc++: overflow leaves streambuf in inconsistent state on I/O error.,https://avd.aquasec.com/nvd/cve-2026-125709 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-95619,MEDIUM,,fix_deferred,gcc: libstdc++ integer overflow in `new` operator,https://avd.aquasec.com/nvd/cve-2026-95619 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2022-27943,LOW,,affected,binutils: libiberty/rust-demangle.c in GNU GCC 11.2 allows stack exhaustion in demangle_const,https://avd.aquasec.com/nvd/cve-2022-27943 +debian,gcc-12-base,12.2.0-14+deb12u1,CVE-2026-115456,LOW,,fix_deferred,gcc: Out-of-bounds read in std::from_chars,https://avd.aquasec.com/nvd/cve-2026-115456 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2025-30258,MEDIUM,,affected,gnupg: verification DoS due to a malicious subkey in the keyring,https://avd.aquasec.com/nvd/cve-2025-30258 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2025-68972,MEDIUM,,affected,gnupg: GnuPG: Signature bypass via form feed character in signed messages,https://avd.aquasec.com/nvd/cve-2025-68972 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2022-3219,LOW,,affected,gnupg: denial of service issue (resource consumption) using compressed packets,https://avd.aquasec.com/nvd/cve-2022-3219 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2026-105712,LOW,,fix_deferred,gnupg2: gnupg: Arbitrary file overwrite via symlink traversal in gpgtar,https://avd.aquasec.com/nvd/cve-2026-105712 +debian,gpgv,2.2.40-1.1+deb12u2,CVE-2026-57062,LOW,,fix_deferred,GnuPG: Incorrect cryptographic message parsing,https://avd.aquasec.com/nvd/cve-2026-57062 +debian,gzip,1.12-1,CVE-2026-41992,HIGH,,fix_deferred,gzip: gzip: Information disclosure via global buffer overflow in LZH decompression,https://avd.aquasec.com/nvd/cve-2026-41992 +debian,gzip,1.12-1,CVE-2026-41991,MEDIUM,,fix_deferred,gzip: gzip: Arbitrary file overwrite via insecure temporary file handling in gzexe utility,https://avd.aquasec.com/nvd/cve-2026-41991 +debian,libacl1,2.3.1-3,CVE-2026-54369,HIGH,,fix_deferred,acl: Symlink traversal privilege escalation via libacl functions,https://avd.aquasec.com/nvd/cve-2026-54369 +debian,libacl1,2.3.1-3,CVE-2026-54370,MEDIUM,,fix_deferred,acl: TOCTOU Symlink Traversal via getfacl/setfacl,https://avd.aquasec.com/nvd/cve-2026-54370 +debian,libapt-pkg6.0,2.6.2,CVE-2011-3374,LOW,,affected,"It was found that apt-key in apt, all versions, do not correctly valid ...",https://avd.aquasec.com/nvd/cve-2011-3374 +debian,libattr1,1:2.5.1-4,CVE-2026-54371,MEDIUM,,fix_deferred,attr: attr: Symlink Traversal Privilege Escalation via getfattr and setfattr,https://avd.aquasec.com/nvd/cve-2026-54371 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libblkid1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libbz2-1.0,1.0.8-5+b1,CVE-2026-42250,MEDIUM,,affected,bzip2: bzip2: Denial of Service in bzip2recover via a specially crafted file,https://avd.aquasec.com/nvd/cve-2026-42250 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-115819,MEDIUM,,affected,glibc: glibc: Memory corruption via out-of-bounds write in wide scanf functions,https://avd.aquasec.com/nvd/cve-2026-115819 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-121757,MEDIUM,,affected,glibc: glibc: Denial of Service via out-of-bounds read in CP949 character conversion,https://avd.aquasec.com/nvd/cve-2026-121757 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-18374,MEDIUM,,fix_deferred,glibc: glibc: Heap buffer overflow via attacker-controlled fopen mode string,https://avd.aquasec.com/nvd/cve-2026-18374 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-19499,MEDIUM,,fix_deferred,glibc: Buffer Overflow in strfmon right-justification padding,https://avd.aquasec.com/nvd/cve-2026-19499 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-19542,MEDIUM,,fix_deferred,glibc: Fix out-of-bounds array write in tdelete,https://avd.aquasec.com/nvd/cve-2026-19542 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-5435,MEDIUM,,affected,glibc: glibc: Out-of-bounds write via TSIG record processing,https://avd.aquasec.com/nvd/cve-2026-5435 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-5450,MEDIUM,,affected,glibc: glibc: Heap Buffer Overflow in `scanf` with `%mc` format specifier and large width,https://avd.aquasec.com/nvd/cve-2026-5450 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-5928,MEDIUM,,affected,glibc: glibc: Information disclosure or denial of service via ungetwc function with specific wide character encodings,https://avd.aquasec.com/nvd/cve-2026-5928 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-6238,MEDIUM,,affected,glibc: glibc: Application crash or uninitialized memory read via crafted DNS response,https://avd.aquasec.com/nvd/cve-2026-6238 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-6368,MEDIUM,,fix_deferred,glibc: glibc: Process abort due to invalid memory in wordexp,https://avd.aquasec.com/nvd/cve-2026-6368 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-6791,MEDIUM,,fix_deferred,glibc: Glibc: Denial of Service via stack exhaustion during tilde expansion,https://avd.aquasec.com/nvd/cve-2026-6791 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-77117,MEDIUM,,fix_deferred,glibc: Non-progress DoS in SHIFT_JISX0213 ->,https://avd.aquasec.com/nvd/cve-2026-77117 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-80489,MEDIUM,,fix_deferred,glibc: Non-progress DoS in EUC_JISX0213 -> UCS-4 conversion state,https://avd.aquasec.com/nvd/cve-2026-80489 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-84243,MEDIUM,,affected,glibc: glibc: Arbitrary code execution via directory traversal in LANGUAGE environment variable,https://avd.aquasec.com/nvd/cve-2026-84243 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-8674,MEDIUM,,fix_deferred,glibc: glibc DNS stub resolver: Denial of Service via long search domain in configuration,https://avd.aquasec.com/nvd/cve-2026-8674 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-86805,MEDIUM,,affected,glibc: glibc: Privilege escalation and arbitrary code execution via TOCTOU race condition in dynamic loader,https://avd.aquasec.com/nvd/cve-2026-86805 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-89092,MEDIUM,,fix_deferred,glibc: nscd stack overflow leads to degraded DNS resolution,https://avd.aquasec.com/nvd/cve-2026-89092 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-95818,MEDIUM,,affected,glibc: glibc: Local attacker can cause denial of service and information disclosure via stack-based buffer overflow.,https://avd.aquasec.com/nvd/cve-2026-95818 +debian,libc-bin,2.36-9+deb12u14,CVE-2010-4756,LOW,,affected,glibc: glob implementation can cause excessive CPU and memory consumption due to crafted glob expressions,https://avd.aquasec.com/nvd/cve-2010-4756 +debian,libc-bin,2.36-9+deb12u14,CVE-2018-20796,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2018-20796 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010022,LOW,,affected,glibc: stack guard protection bypass,https://avd.aquasec.com/nvd/cve-2019-1010022 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010023,LOW,,affected,glibc: running ldd on malicious ELF leads to code execution because of wrong size computation,https://avd.aquasec.com/nvd/cve-2019-1010023 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010024,LOW,,affected,glibc: ASLR bypass using cache of thread stack and heap,https://avd.aquasec.com/nvd/cve-2019-1010024 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-1010025,LOW,,affected,glibc: information disclosure of heap addresses of pthread_created thread,https://avd.aquasec.com/nvd/cve-2019-1010025 +debian,libc-bin,2.36-9+deb12u14,CVE-2019-9192,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2019-9192 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-100290,LOW,,affected,glibc: glibc: Denial of Service via memory allocation failure during regular expression processing,https://avd.aquasec.com/nvd/cve-2026-100290 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-126765,LOW,,affected,glibc: glibc: Denial of Service via double free in glob functions,https://avd.aquasec.com/nvd/cve-2026-126765 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-97399,LOW,,affected,glibc: glibc: Denial of Service via out-of-bounds read in strncasecmp,https://avd.aquasec.com/nvd/cve-2026-97399 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-121758,UNKNOWN,,affected,Converting crafted ISO-2022-CN-EXT input in the GNU C Library version ...,https://avd.aquasec.com/nvd/cve-2026-121758 +debian,libc-bin,2.36-9+deb12u14,CVE-2026-124024,UNKNOWN,,affected,Converting crafted input from UCS-4 to IBM1390 or IBM1399 character en ...,https://avd.aquasec.com/nvd/cve-2026-124024 +debian,libc6,2.36-9+deb12u14,CVE-2026-115819,MEDIUM,,affected,glibc: glibc: Memory corruption via out-of-bounds write in wide scanf functions,https://avd.aquasec.com/nvd/cve-2026-115819 +debian,libc6,2.36-9+deb12u14,CVE-2026-121757,MEDIUM,,affected,glibc: glibc: Denial of Service via out-of-bounds read in CP949 character conversion,https://avd.aquasec.com/nvd/cve-2026-121757 +debian,libc6,2.36-9+deb12u14,CVE-2026-18374,MEDIUM,,fix_deferred,glibc: glibc: Heap buffer overflow via attacker-controlled fopen mode string,https://avd.aquasec.com/nvd/cve-2026-18374 +debian,libc6,2.36-9+deb12u14,CVE-2026-19499,MEDIUM,,fix_deferred,glibc: Buffer Overflow in strfmon right-justification padding,https://avd.aquasec.com/nvd/cve-2026-19499 +debian,libc6,2.36-9+deb12u14,CVE-2026-19542,MEDIUM,,fix_deferred,glibc: Fix out-of-bounds array write in tdelete,https://avd.aquasec.com/nvd/cve-2026-19542 +debian,libc6,2.36-9+deb12u14,CVE-2026-5435,MEDIUM,,affected,glibc: glibc: Out-of-bounds write via TSIG record processing,https://avd.aquasec.com/nvd/cve-2026-5435 +debian,libc6,2.36-9+deb12u14,CVE-2026-5450,MEDIUM,,affected,glibc: glibc: Heap Buffer Overflow in `scanf` with `%mc` format specifier and large width,https://avd.aquasec.com/nvd/cve-2026-5450 +debian,libc6,2.36-9+deb12u14,CVE-2026-5928,MEDIUM,,affected,glibc: glibc: Information disclosure or denial of service via ungetwc function with specific wide character encodings,https://avd.aquasec.com/nvd/cve-2026-5928 +debian,libc6,2.36-9+deb12u14,CVE-2026-6238,MEDIUM,,affected,glibc: glibc: Application crash or uninitialized memory read via crafted DNS response,https://avd.aquasec.com/nvd/cve-2026-6238 +debian,libc6,2.36-9+deb12u14,CVE-2026-6368,MEDIUM,,fix_deferred,glibc: glibc: Process abort due to invalid memory in wordexp,https://avd.aquasec.com/nvd/cve-2026-6368 +debian,libc6,2.36-9+deb12u14,CVE-2026-6791,MEDIUM,,fix_deferred,glibc: Glibc: Denial of Service via stack exhaustion during tilde expansion,https://avd.aquasec.com/nvd/cve-2026-6791 +debian,libc6,2.36-9+deb12u14,CVE-2026-77117,MEDIUM,,fix_deferred,glibc: Non-progress DoS in SHIFT_JISX0213 ->,https://avd.aquasec.com/nvd/cve-2026-77117 +debian,libc6,2.36-9+deb12u14,CVE-2026-80489,MEDIUM,,fix_deferred,glibc: Non-progress DoS in EUC_JISX0213 -> UCS-4 conversion state,https://avd.aquasec.com/nvd/cve-2026-80489 +debian,libc6,2.36-9+deb12u14,CVE-2026-84243,MEDIUM,,affected,glibc: glibc: Arbitrary code execution via directory traversal in LANGUAGE environment variable,https://avd.aquasec.com/nvd/cve-2026-84243 +debian,libc6,2.36-9+deb12u14,CVE-2026-8674,MEDIUM,,fix_deferred,glibc: glibc DNS stub resolver: Denial of Service via long search domain in configuration,https://avd.aquasec.com/nvd/cve-2026-8674 +debian,libc6,2.36-9+deb12u14,CVE-2026-86805,MEDIUM,,affected,glibc: glibc: Privilege escalation and arbitrary code execution via TOCTOU race condition in dynamic loader,https://avd.aquasec.com/nvd/cve-2026-86805 +debian,libc6,2.36-9+deb12u14,CVE-2026-89092,MEDIUM,,fix_deferred,glibc: nscd stack overflow leads to degraded DNS resolution,https://avd.aquasec.com/nvd/cve-2026-89092 +debian,libc6,2.36-9+deb12u14,CVE-2026-95818,MEDIUM,,affected,glibc: glibc: Local attacker can cause denial of service and information disclosure via stack-based buffer overflow.,https://avd.aquasec.com/nvd/cve-2026-95818 +debian,libc6,2.36-9+deb12u14,CVE-2010-4756,LOW,,affected,glibc: glob implementation can cause excessive CPU and memory consumption due to crafted glob expressions,https://avd.aquasec.com/nvd/cve-2010-4756 +debian,libc6,2.36-9+deb12u14,CVE-2018-20796,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2018-20796 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010022,LOW,,affected,glibc: stack guard protection bypass,https://avd.aquasec.com/nvd/cve-2019-1010022 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010023,LOW,,affected,glibc: running ldd on malicious ELF leads to code execution because of wrong size computation,https://avd.aquasec.com/nvd/cve-2019-1010023 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010024,LOW,,affected,glibc: ASLR bypass using cache of thread stack and heap,https://avd.aquasec.com/nvd/cve-2019-1010024 +debian,libc6,2.36-9+deb12u14,CVE-2019-1010025,LOW,,affected,glibc: information disclosure of heap addresses of pthread_created thread,https://avd.aquasec.com/nvd/cve-2019-1010025 +debian,libc6,2.36-9+deb12u14,CVE-2019-9192,LOW,,affected,glibc: uncontrolled recursion in function check_dst_limits_calc_pos_1 in posix/regexec.c,https://avd.aquasec.com/nvd/cve-2019-9192 +debian,libc6,2.36-9+deb12u14,CVE-2026-100290,LOW,,affected,glibc: glibc: Denial of Service via memory allocation failure during regular expression processing,https://avd.aquasec.com/nvd/cve-2026-100290 +debian,libc6,2.36-9+deb12u14,CVE-2026-126765,LOW,,affected,glibc: glibc: Denial of Service via double free in glob functions,https://avd.aquasec.com/nvd/cve-2026-126765 +debian,libc6,2.36-9+deb12u14,CVE-2026-97399,LOW,,affected,glibc: glibc: Denial of Service via out-of-bounds read in strncasecmp,https://avd.aquasec.com/nvd/cve-2026-97399 +debian,libc6,2.36-9+deb12u14,CVE-2026-121758,UNKNOWN,,affected,Converting crafted ISO-2022-CN-EXT input in the GNU C Library version ...,https://avd.aquasec.com/nvd/cve-2026-121758 +debian,libc6,2.36-9+deb12u14,CVE-2026-124024,UNKNOWN,,affected,Converting crafted input from UCS-4 to IBM1390 or IBM1399 character en ...,https://avd.aquasec.com/nvd/cve-2026-124024 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-102010,MEDIUM,,fix_deferred,gcc-toolset-15-gcc: gcc: gcc-toolset-16: gcc: Denial of Service via use-after-free in binary heap erase_if,https://avd.aquasec.com/nvd/cve-2026-102010 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-114690,MEDIUM,,affected,gcc: Confirmed out-of-bounds read/write in libstdc++ parallel `std,https://avd.aquasec.com/nvd/cve-2026-114690 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-114691,MEDIUM,,affected,gcc: Integer wrap in `std,https://avd.aquasec.com/nvd/cve-2026-114691 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-125709,MEDIUM,,fix_deferred,libstdc++: overflow leaves streambuf in inconsistent state on I/O error.,https://avd.aquasec.com/nvd/cve-2026-125709 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-95619,MEDIUM,,fix_deferred,gcc: libstdc++ integer overflow in `new` operator,https://avd.aquasec.com/nvd/cve-2026-95619 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2022-27943,LOW,,affected,binutils: libiberty/rust-demangle.c in GNU GCC 11.2 allows stack exhaustion in demangle_const,https://avd.aquasec.com/nvd/cve-2022-27943 +debian,libgcc-s1,12.2.0-14+deb12u1,CVE-2026-115456,LOW,,fix_deferred,gcc: Out-of-bounds read in std::from_chars,https://avd.aquasec.com/nvd/cve-2026-115456 +debian,libgcrypt20,1.10.1-3+deb12u1,CVE-2018-6829,LOW,,affected,libgcrypt: ElGamal implementation doesn't have semantic security due to incorrectly encoded plaintexts possibly allowing to obtain sensitive information,https://avd.aquasec.com/nvd/cve-2018-6829 +debian,libgcrypt20,1.10.1-3+deb12u1,CVE-2024-2236,LOW,,affected,libgcrypt: vulnerable to Marvin Attack,https://avd.aquasec.com/nvd/cve-2024-2236 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2011-3389,LOW,,affected,HTTPS: block-wise chosen-plaintext attack against SSL/TLS (BEAST),https://avd.aquasec.com/nvd/cve-2011-3389 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-67693,LOW,,affected,gnutls: gnutls: Information disclosure via contradictory Key Usage and Extended Key Usage extensions,https://avd.aquasec.com/nvd/cve-2026-67693 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-88647,LOW,,affected,gnutls: gnutls: Information disclosure via hostname verification bypass,https://avd.aquasec.com/nvd/cve-2026-88647 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-88648,LOW,,affected,gnutls: gnutls: Cross-domain certificate restriction bypass via incomplete X.509 validation,https://avd.aquasec.com/nvd/cve-2026-88648 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-95184,LOW,,affected,gnutls: gnutls: legitimate user certificates incorrectly rejected causing denial of service,https://avd.aquasec.com/nvd/cve-2026-95184 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-95210,LOW,,affected,gnutls: gnutls: certificates with invalid extensions incorrectly accepted,https://avd.aquasec.com/nvd/cve-2026-95210 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-127039,UNKNOWN,,fix_deferred,The certificate authentication info handling in gnutls from 2.5.9 up t ...,https://avd.aquasec.com/nvd/cve-2026-127039 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-127040,UNKNOWN,,fix_deferred,The RSA-PSK ClientKeyExchange handler in gnutls before 3.8.14 does not ...,https://avd.aquasec.com/nvd/cve-2026-127040 +debian,libgnutls30,3.7.9-2+deb12u7,CVE-2026-127231,UNKNOWN,,fix_deferred,A double free in the X.509 name constraints enforcement of GnuTLS 3.8. ...,https://avd.aquasec.com/nvd/cve-2026-127231 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libgssapi-krb5-2,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libk5crypto3,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libkrb5-3,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107364,HIGH,,affected,krb5: Unauthenticated KDC DoS based on ASN.1 decoder read overrun,https://avd.aquasec.com/nvd/cve-2026-107364 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112315,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS in RPCSEC_GSS buffer decode failure,https://avd.aquasec.com/nvd/cve-2026-112315 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112316,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory leak DoS in xdr_krb5_tl_data() decode failure,https://avd.aquasec.com/nvd/cve-2026-112316 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112317,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB keytab key decryption error path,https://avd.aquasec.com/nvd/cve-2026-112317 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112318,HIGH,,affected,krb5: MIT krb5 kadmind authenticated DoS exploiting dereference of null policy name pointers,https://avd.aquasec.com/nvd/cve-2026-112318 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112319,HIGH,,affected,krb5: MIT krb5 kadmind authenticated memory exhaustion DoS via unbounded RPC XDR allocation,https://avd.aquasec.com/nvd/cve-2026-112319 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112320,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via GSS-RPC auth flavor switching,https://avd.aquasec.com/nvd/cve-2026-112320 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112321,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory leak DoS via AUTH_GSSAPI_INIT error paths,https://avd.aquasec.com/nvd/cve-2026-112321 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112322,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated CPU DoS via AUTH_GSSAPI client states cleanup,https://avd.aquasec.com/nvd/cve-2026-112322 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112323,HIGH,,affected,krb5: MIT krb5 kadmind unauthenticated memory exhaustion via failed AUTH_GSSAPI_INIT requests,https://avd.aquasec.com/nvd/cve-2026-112323 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-118380,HIGH,,affected,krb5: kadmind: request alteration and protected information disclosure,https://avd.aquasec.com/nvd/cve-2026-118380 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-119079,HIGH,,affected,krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic ASN.1 SEQUENCE OF decoding,https://avd.aquasec.com/nvd/cve-2026-119079 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-71199,HIGH,,affected,krb5: Alteration of authentication indicators in CAMMAC container,https://avd.aquasec.com/nvd/cve-2026-71199 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-71200,HIGH,,affected,krb5: Unauthenticated KDC NULL pointer dereference KDC DoS via crafted PKINIT pre-auth request,https://avd.aquasec.com/nvd/cve-2026-71200 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107708,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via malformed PAC in S4U2Proxy requests,https://avd.aquasec.com/nvd/cve-2026-107708 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107778,MEDIUM,,fix_deferred,krb5: krb5: Denial of Service via crafted forwarded credentials,https://avd.aquasec.com/nvd/cve-2026-107778 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-107884,MEDIUM,,affected,krb5: Unauthorized key reset of protected principal via kpasswd,https://avd.aquasec.com/nvd/cve-2026-107884 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-111423,MEDIUM,,affected,krb5: Improper authorization via flawed PAC checksum verification,https://avd.aquasec.com/nvd/cve-2026-111423 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-112314,MEDIUM,,affected,krb5: MIT krb5 GSS-RPC client memory leak on XID mismatch retries,https://avd.aquasec.com/nvd/cve-2026-112314 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2018-5709,LOW,,affected,krb5: integer overflow in dbentry->n_key_data in kadmin/dbutil/dump.c,https://avd.aquasec.com/nvd/cve-2018-5709 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2024-26458,LOW,,affected,krb5: Memory leak at /krb5/src/lib/rpc/pmap_rmt.c,https://avd.aquasec.com/nvd/cve-2024-26458 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2024-26461,LOW,,affected,krb5: Memory leak at /krb5/src/lib/gssapi/krb5/k5sealv3.c,https://avd.aquasec.com/nvd/cve-2024-26461 +debian,libkrb5support0,1.20.1-2+deb12u5,CVE-2026-11850,LOW,,affected,krb5: krb5: integer underflow in berval2tl_data() leads to heap out-of-bounds read,https://avd.aquasec.com/nvd/cve-2026-11850 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libmount1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libmount1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libmount1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libncursesw6,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,libncursesw6,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,libncursesw6,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,libp11-kit0,0.24.1-2,CVE-2026-13757,MEDIUM,,fix_deferred,p11-kit: Stack exhaustion via unbounded recursion in RPC attribute parsing,https://avd.aquasec.com/nvd/cve-2026-13757 +debian,libp11-kit0,0.24.1-2,CVE-2026-18938,MEDIUM,,fix_deferred,p11-kit: Integer overflow in RPC attribute-array length calculation can under-allocate nested attribute storage on 32 bit systems,https://avd.aquasec.com/nvd/cve-2026-18938 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam-modules,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam-modules-bin,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam-runtime,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2025-6020,HIGH,1.5.2-6+deb12u3,fixed,linux-pam: Linux-pam directory Traversal,https://avd.aquasec.com/nvd/cve-2025-6020 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2024-10041,MEDIUM,,will_not_fix,pam: libpam: Libpam vulnerable to read hashed password,https://avd.aquasec.com/nvd/cve-2024-10041 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2024-22365,MEDIUM,1.5.2-6+deb12u3,fixed,pam: allowing unprivileged user to block another user namespace,https://avd.aquasec.com/nvd/cve-2024-22365 +debian,libpam0g,1.5.2-6+deb12u2,CVE-2026-54411,MEDIUM,,fix_deferred,linux-pam: Plaintext password recovery via timing discrepancy in pam_userdb module,https://avd.aquasec.com/nvd/cve-2026-54411 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-402D17,UNKNOWN,,affected,[GHSA-4q85-33p6-j5g6: Incorrect 64-bit comparison merge in libseccomp can weaken seccomp filters],https://security-tracker.debian.org/tracker/TEMP-0000000-402D17 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-414660,UNKNOWN,,affected,[GHSA-35x7-vh54-jvqf: Incorrect accumulator reloads when comparing arguments can lead to erroneous actions],https://security-tracker.debian.org/tracker/TEMP-0000000-414660 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-43231F,UNKNOWN,,affected,[GHSA-2hqh-5c36-grrm: Oversized seccomp filters can trigger libseccomp heap corruption],https://security-tracker.debian.org/tracker/TEMP-0000000-43231F +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-AE2C66,UNKNOWN,,affected,[GHSA-84vx-jqqr-h4f2: Unmatched seccomp transaction rejections can result in a segmentation fault],https://security-tracker.debian.org/tracker/TEMP-0000000-AE2C66 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-ED49F3,UNKNOWN,,affected,[GHSA-q75f-27j4-2h7j: Missing syscall-number load in BPF filter can bypass seccomp restrictions],https://security-tracker.debian.org/tracker/TEMP-0000000-ED49F3 +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-F88C7E,UNKNOWN,,affected,[GHSA-qxh5-4cq9-6mjx: Crafted seccomp rules can trigger an infinite loop in libseccomp],https://security-tracker.debian.org/tracker/TEMP-0000000-F88C7E +debian,libseccomp2,2.5.4-1+deb12u1,TEMP-0000000-FCA4C0,UNKNOWN,,affected,[GHSA-46fr-jh49-xvhx: Oversized seccomp filters can trigger libseccomp double free],https://security-tracker.debian.org/tracker/TEMP-0000000-FCA4C0 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libsmartcols1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-7458,CRITICAL,,affected,sqlite: SQLite integer overflow,https://avd.aquasec.com/nvd/cve-2025-7458 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-11822,HIGH,,fix_deferred,sqlite: SQLite: Arbitrary code execution via crafted FTS5 full-text search data,https://avd.aquasec.com/nvd/cve-2026-11822 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-11824,HIGH,,fix_deferred,sqlite: SQLite: Arbitrary code execution and crash via heap-based buffer overflow in FTS5,https://avd.aquasec.com/nvd/cve-2026-11824 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119373,HIGH,,affected,sqlite: sqlite: Denial of service via heap-based buffer overflow in FTS5,https://avd.aquasec.com/nvd/cve-2026-119373 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119374,HIGH,,affected,sqlite: sqlite: Arbitrary code execution via corrupted FTS5 index,https://avd.aquasec.com/nvd/cve-2026-119374 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119379,HIGH,,affected,sqlite: sqlite: Arbitrary code execution via crafted session changesets,https://avd.aquasec.com/nvd/cve-2026-119379 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-7709,MEDIUM,,affected,An integer overflow exists in the FTS5 https://sqlite.org/fts5.html e ...,https://avd.aquasec.com/nvd/cve-2025-7709 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119371,MEDIUM,,affected,sqlite: sqlite: Denial of Service via stack exhaustion from deeply nested Common Table Expressions,https://avd.aquasec.com/nvd/cve-2026-119371 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119372,MEDIUM,,affected,sqlite: sqlite: Denial of Service via use-after-free in full-text search,https://avd.aquasec.com/nvd/cve-2026-119372 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119375,MEDIUM,,affected,sqlite: sqlite: Information disclosure via undersized WAL page size,https://avd.aquasec.com/nvd/cve-2026-119375 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119376,MEDIUM,,affected,sqlite: sqlite: Denial of Service via stack exhaustion from chained COLLATE operators,https://avd.aquasec.com/nvd/cve-2026-119376 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119378,MEDIUM,,affected,sqlite: sqlite: Denial of Service via use-after-free in R-Tree extension,https://avd.aquasec.com/nvd/cve-2026-119378 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119591,MEDIUM,,affected,sqlite: sqlite: Denial of Service via stack exhaustion in countOfViewOptimization(),https://avd.aquasec.com/nvd/cve-2026-119591 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-50812,MEDIUM,,fix_deferred,sqlite: SQLite: Denial of Service via malformed changeset in Session Extension,https://avd.aquasec.com/nvd/cve-2026-50812 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-50813,MEDIUM,,fix_deferred,sqlite: SQLite: Information disclosure via Session Extension changeset merge path,https://avd.aquasec.com/nvd/cve-2026-50813 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2021-45346,LOW,,affected,sqlite: crafted SQL query allows a malicious user to obtain sensitive information,https://avd.aquasec.com/nvd/cve-2021-45346 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-29088,LOW,,affected,sqlite: Denial of Service in SQLite,https://avd.aquasec.com/nvd/cve-2025-29088 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2025-70873,LOW,,affected,sqlite: SQLite: Information Disclosure via Crafted ZIP File,https://avd.aquasec.com/nvd/cve-2025-70873 +debian,libsqlite3-0,3.40.1-2+deb12u2,CVE-2026-119377,LOW,,fix_deferred,sqlite: sqlite: Authorization bypass via USING clause in JOIN queries,https://avd.aquasec.com/nvd/cve-2026-119377 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-107496,MEDIUM,,affected,openssl: openssl: Denial of Service via crafted EC certificate in CMS encryption,https://avd.aquasec.com/nvd/cve-2026-107496 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-84786,MEDIUM,,affected,openssl: OpenSSL: Denial of Service via NULL pointer dereference during DANE TLSA record processing,https://avd.aquasec.com/nvd/cve-2026-84786 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-95690,MEDIUM,,affected,openssl: openssl: Denial of service via crafted out-of-sequence DTLS handshake fragments,https://avd.aquasec.com/nvd/cve-2026-95690 +debian,libssl3,3.0.22-1~deb12u2,CVE-2025-27587,LOW,,affected,OpenSSL 3.0.0 through 3.3.2 on the PowerPC architecture is vulnerable ...,https://avd.aquasec.com/nvd/cve-2025-27587 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-107493,LOW,,affected,openssl: openssl: Denial of Service via malformed PEM data in PEM_X509_INFO_read_bio_ex,https://avd.aquasec.com/nvd/cve-2026-107493 +debian,libssl3,3.0.22-1~deb12u2,CVE-2026-121481,LOW,,affected,openssl: openssl: Out-of-bounds write via integer overflow in EVP_EncodeBlock(),https://avd.aquasec.com/nvd/cve-2026-121481 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-102010,MEDIUM,,fix_deferred,gcc-toolset-15-gcc: gcc: gcc-toolset-16: gcc: Denial of Service via use-after-free in binary heap erase_if,https://avd.aquasec.com/nvd/cve-2026-102010 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-114690,MEDIUM,,affected,gcc: Confirmed out-of-bounds read/write in libstdc++ parallel `std,https://avd.aquasec.com/nvd/cve-2026-114690 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-114691,MEDIUM,,affected,gcc: Integer wrap in `std,https://avd.aquasec.com/nvd/cve-2026-114691 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-125709,MEDIUM,,fix_deferred,libstdc++: overflow leaves streambuf in inconsistent state on I/O error.,https://avd.aquasec.com/nvd/cve-2026-125709 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-95619,MEDIUM,,fix_deferred,gcc: libstdc++ integer overflow in `new` operator,https://avd.aquasec.com/nvd/cve-2026-95619 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2022-27943,LOW,,affected,binutils: libiberty/rust-demangle.c in GNU GCC 11.2 allows stack exhaustion in demangle_const,https://avd.aquasec.com/nvd/cve-2022-27943 +debian,libstdc++6,12.2.0-14+deb12u1,CVE-2026-115456,LOW,,fix_deferred,gcc: Out-of-bounds read in std::from_chars,https://avd.aquasec.com/nvd/cve-2026-115456 +debian,libsystemd0,252.39-1~deb12u2,CVE-2026-16742,HIGH,,fix_deferred,systemd: systemd-homed: Local privilege escalation via missing home-record signature verification,https://avd.aquasec.com/nvd/cve-2026-16742 +debian,libsystemd0,252.39-1~deb12u2,CVE-2026-15059,MEDIUM,,fix_deferred,systemd: systemd-oomd: Unprivileged users can terminate arbitrary processes via IPC API,https://avd.aquasec.com/nvd/cve-2026-15059 +debian,libsystemd0,252.39-1~deb12u2,CVE-2013-4392,LOW,,affected,systemd: TOCTOU race condition when updating file permissions and SELinux security contexts,https://avd.aquasec.com/nvd/cve-2013-4392 +debian,libsystemd0,252.39-1~deb12u2,CVE-2023-31437,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify a seale ...,https://avd.aquasec.com/nvd/cve-2023-31437 +debian,libsystemd0,252.39-1~deb12u2,CVE-2023-31438,LOW,,affected,An issue was discovered in systemd 253. An attacker can truncate a sea ...,https://avd.aquasec.com/nvd/cve-2023-31438 +debian,libsystemd0,252.39-1~deb12u2,CVE-2023-31439,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify the con ...,https://avd.aquasec.com/nvd/cve-2023-31439 +debian,libtasn1-6,4.19.0-2+deb12u1,CVE-2025-13151,LOW,,affected,libtasn1: libtasn1: Denial of Service via stack-based buffer overflow in asn1_expend_octet_string,https://avd.aquasec.com/nvd/cve-2025-13151 +debian,libtinfo6,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,libtinfo6,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,libtinfo6,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,libtirpc-common,1.3.3+ds-1,CVE-2026-104357,MEDIUM,,affected,libtirpc: libtirpc: SunRPC UDP datagram-boundary violation (stale buffer bytes decoded as current request),https://avd.aquasec.com/nvd/cve-2026-104357 +debian,libtirpc-common,1.3.3+ds-1,CVE-2026-85231,MEDIUM,,affected,libtirpc: libtirpc: Denial of service via unbounded memory allocation during RPCSEC_GSS decoding,https://avd.aquasec.com/nvd/cve-2026-85231 +debian,libtirpc-common,1.3.3+ds-1,CVE-2026-85977,MEDIUM,,affected,libtirpc: libtirpc: Denial of Service via unbounded memory allocation during portmapper response decoding,https://avd.aquasec.com/nvd/cve-2026-85977 +debian,libtirpc3,1.3.3+ds-1,CVE-2026-104357,MEDIUM,,affected,libtirpc: libtirpc: SunRPC UDP datagram-boundary violation (stale buffer bytes decoded as current request),https://avd.aquasec.com/nvd/cve-2026-104357 +debian,libtirpc3,1.3.3+ds-1,CVE-2026-85231,MEDIUM,,affected,libtirpc: libtirpc: Denial of service via unbounded memory allocation during RPCSEC_GSS decoding,https://avd.aquasec.com/nvd/cve-2026-85231 +debian,libtirpc3,1.3.3+ds-1,CVE-2026-85977,MEDIUM,,affected,libtirpc: libtirpc: Denial of Service via unbounded memory allocation during portmapper response decoding,https://avd.aquasec.com/nvd/cve-2026-85977 +debian,libudev1,252.39-1~deb12u2,CVE-2026-16742,HIGH,,fix_deferred,systemd: systemd-homed: Local privilege escalation via missing home-record signature verification,https://avd.aquasec.com/nvd/cve-2026-16742 +debian,libudev1,252.39-1~deb12u2,CVE-2026-15059,MEDIUM,,fix_deferred,systemd: systemd-oomd: Unprivileged users can terminate arbitrary processes via IPC API,https://avd.aquasec.com/nvd/cve-2026-15059 +debian,libudev1,252.39-1~deb12u2,CVE-2013-4392,LOW,,affected,systemd: TOCTOU race condition when updating file permissions and SELinux security contexts,https://avd.aquasec.com/nvd/cve-2013-4392 +debian,libudev1,252.39-1~deb12u2,CVE-2023-31437,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify a seale ...,https://avd.aquasec.com/nvd/cve-2023-31437 +debian,libudev1,252.39-1~deb12u2,CVE-2023-31438,LOW,,affected,An issue was discovered in systemd 253. An attacker can truncate a sea ...,https://avd.aquasec.com/nvd/cve-2023-31438 +debian,libudev1,252.39-1~deb12u2,CVE-2023-31439,LOW,,affected,An issue was discovered in systemd 253. An attacker can modify the con ...,https://avd.aquasec.com/nvd/cve-2023-31439 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,libuuid1,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,libzstd1,1.5.4+dfsg2-5,CVE-2026-124851,HIGH,,affected,zstd: Zstandard Information Disclosure via Uninitialized Buffer,https://avd.aquasec.com/nvd/cve-2026-124851 +debian,login,1:4.13+dfsg1-1+deb12u2,CVE-2007-5686,LOW,,affected,initscripts in rPath Linux 1 sets insecure permissions for the /var/lo ...,https://avd.aquasec.com/nvd/cve-2007-5686 +debian,login,1:4.13+dfsg1-1+deb12u2,CVE-2024-56433,LOW,,affected,shadow-utils: Default subordinate ID configuration in /etc/login.defs could lead to compromise,https://avd.aquasec.com/nvd/cve-2024-56433 +debian,login,1:4.13+dfsg1-1+deb12u2,TEMP-0628843-DBAD28,LOW,,affected,[more related to CVE-2005-4890],https://security-tracker.debian.org/tracker/TEMP-0628843-DBAD28 +debian,login,1:4.13+dfsg1-1+deb12u2,CVE-2026-135901,UNKNOWN,,affected,[shadow: Security fix for newgidmap],https://avd.aquasec.com/nvd/cve-2026-135901 +debian,mount,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,mount,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,mount,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,mount,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,mount,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,mount,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,mount,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,mount,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,ncurses-base,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,ncurses-base,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,ncurses-base,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,ncurses-bin,6.4-4,CVE-2025-69720,HIGH,,affected,ncurses: ncurses: Buffer overflow vulnerability may lead to arbitrary code execution.,https://avd.aquasec.com/nvd/cve-2025-69720 +debian,ncurses-bin,6.4-4,CVE-2023-50495,MEDIUM,,affected,ncurses: segmentation fault via _nc_wrap_entry(),https://avd.aquasec.com/nvd/cve-2023-50495 +debian,ncurses-bin,6.4-4,CVE-2025-6141,LOW,,affected,gnu-ncurses: ncurses Stack Buffer Overflow,https://avd.aquasec.com/nvd/cve-2025-6141 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-107496,MEDIUM,,affected,openssl: openssl: Denial of Service via crafted EC certificate in CMS encryption,https://avd.aquasec.com/nvd/cve-2026-107496 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-84786,MEDIUM,,affected,openssl: OpenSSL: Denial of Service via NULL pointer dereference during DANE TLSA record processing,https://avd.aquasec.com/nvd/cve-2026-84786 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-95690,MEDIUM,,affected,openssl: openssl: Denial of service via crafted out-of-sequence DTLS handshake fragments,https://avd.aquasec.com/nvd/cve-2026-95690 +debian,openssl,3.0.22-1~deb12u2,CVE-2025-27587,LOW,,affected,OpenSSL 3.0.0 through 3.3.2 on the PowerPC architecture is vulnerable ...,https://avd.aquasec.com/nvd/cve-2025-27587 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-107493,LOW,,affected,openssl: openssl: Denial of Service via malformed PEM data in PEM_X509_INFO_read_bio_ex,https://avd.aquasec.com/nvd/cve-2026-107493 +debian,openssl,3.0.22-1~deb12u2,CVE-2026-121481,LOW,,affected,openssl: openssl: Out-of-bounds write via integer overflow in EVP_EncodeBlock(),https://avd.aquasec.com/nvd/cve-2026-121481 +debian,passwd,1:4.13+dfsg1-1+deb12u2,CVE-2007-5686,LOW,,affected,initscripts in rPath Linux 1 sets insecure permissions for the /var/lo ...,https://avd.aquasec.com/nvd/cve-2007-5686 +debian,passwd,1:4.13+dfsg1-1+deb12u2,CVE-2024-56433,LOW,,affected,shadow-utils: Default subordinate ID configuration in /etc/login.defs could lead to compromise,https://avd.aquasec.com/nvd/cve-2024-56433 +debian,passwd,1:4.13+dfsg1-1+deb12u2,TEMP-0628843-DBAD28,LOW,,affected,[more related to CVE-2005-4890],https://security-tracker.debian.org/tracker/TEMP-0628843-DBAD28 +debian,passwd,1:4.13+dfsg1-1+deb12u2,CVE-2026-135901,UNKNOWN,,affected,[shadow: Security fix for newgidmap],https://avd.aquasec.com/nvd/cve-2026-135901 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-9538,HIGH,,fix_deferred,perl-Archive-Tar: perl-Archive-Tar: Denial of Service via crafted tar header with large entry size,https://avd.aquasec.com/nvd/cve-2026-9538 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-15534,MEDIUM,,fix_deferred,perl: Perl: Arbitrary code execution via out-of-bounds memory access in regular expression engine.,https://avd.aquasec.com/nvd/cve-2026-15534 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-82560,MEDIUM,,fix_deferred,Pod::Text versions before 6.1.1 for Perl allow CPU and memory exhausti ...,https://avd.aquasec.com/nvd/cve-2026-82560 +debian,perl-base,5.36.0-7+deb12u4,CVE-2011-4116,LOW,,affected,perl: File:: Temp insecure temporary file handling,https://avd.aquasec.com/nvd/cve-2011-4116 +debian,perl-base,5.36.0-7+deb12u4,CVE-2023-31486,LOW,,affected,http-tiny: perl: insecure TLS cert default,https://avd.aquasec.com/nvd/cve-2023-31486 +debian,perl-base,5.36.0-7+deb12u4,CVE-2026-40558,UNKNOWN,,affected,CVE-2026-40558,https://avd.aquasec.com/nvd/cve-2026-40558 +debian,sysvinit-utils,3.06-4,TEMP-0517018-A83CE6,LOW,,affected,[sysvinit: no-root option in expert installer exposes locally exploitable security flaw],https://security-tracker.debian.org/tracker/TEMP-0517018-A83CE6 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2026-18477,MEDIUM,,fix_deferred,tar: tar: TOCTOU in incremental dumpdir 'X' rename handling allows restore path escape,https://avd.aquasec.com/nvd/cve-2026-18477 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2026-18508,MEDIUM,,fix_deferred,tar: tar: --one-top-level hardlink targets not confined to top-level directory enabling arbitrary file overwrite,https://avd.aquasec.com/nvd/cve-2026-18508 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2026-5704,MEDIUM,,affected,tar: tar: Hidden file injection via crafted archives,https://avd.aquasec.com/nvd/cve-2026-5704 +debian,tar,1.34+dfsg-1.2+deb12u1,CVE-2005-2541,LOW,,affected,tar: does not properly warn the user when extracting setuid or setgid files,https://avd.aquasec.com/nvd/cve-2005-2541 +debian,tar,1.34+dfsg-1.2+deb12u1,TEMP-0290435-0B57B5,LOW,,affected,[tar's rmt command may have undesired side effects],https://security-tracker.debian.org/tracker/TEMP-0290435-0B57B5 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,util-linux,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,util-linux,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,util-linux,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-53613,HIGH,,affected,util-linux: TOCTOU in the mount program via ancestor directory swap on target path,https://avd.aquasec.com/nvd/cve-2026-53613 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-53615,HIGH,,affected,util-linux: util-linux: Partition metadata compromise via integer overflow in DOS partition parser,https://avd.aquasec.com/nvd/cve-2026-53615 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-78410,HIGH,,affected,"util-linux: util-linux: restricted bind mounts do not pin the source, allowing X-mount.owner/group/mode redirection",https://avd.aquasec.com/nvd/cve-2026-78410 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-13595,MEDIUM,,affected,util-linux: util-linux: heap use-after-free in libblkid nested partition probing,https://avd.aquasec.com/nvd/cve-2026-13595 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-27456,MEDIUM,,affected,util-linux: TOCTOU in the mount program when setting up loop devices,https://avd.aquasec.com/nvd/cve-2026-27456 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2026-3184,MEDIUM,,will_not_fix,util-linux: util-linux: Access control bypass due to improper hostname canonicalization,https://avd.aquasec.com/nvd/cve-2026-3184 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2022-0563,LOW,,affected,util-linux: partial disclosure of arbitrary files in chfn and chsh when compiled with libreadline,https://avd.aquasec.com/nvd/cve-2022-0563 +debian,util-linux-extra,2.38.1-5+deb12u3,CVE-2025-14104,LOW,,affected,util-linux: util-linux: Heap buffer overread in setpwnam() when processing 256-byte usernames,https://avd.aquasec.com/nvd/cve-2025-14104 +debian,zlib1g,1:1.2.13.dfsg-1,CVE-2023-45853,CRITICAL,,will_not_fix,zlib: integer overflow and resultant heap-based buffer overflow in zipOpenNewFileInZip4_6,https://avd.aquasec.com/nvd/cve-2023-45853 +debian,zlib1g,1:1.2.13.dfsg-1,CVE-2026-85091,HIGH,,affected,zlib: zlib: Heap buffer overflow in gz_vacate() allows arbitrary code execution,https://avd.aquasec.com/nvd/cve-2026-85091 +debian,zlib1g,1:1.2.13.dfsg-1,CVE-2026-27171,MEDIUM,,affected,zlib: zlib: Denial of Service via infinite loop in CRC32 combine functions,https://avd.aquasec.com/nvd/cve-2026-27171 +python-pkg,opentelemetry-api,1.38.0,CVE-2026-114603,MEDIUM,1.45.1,fixed,opentelemetry-api: opentelemetry-api: Denial of Service via regular expression backtracking in header parsing,https://avd.aquasec.com/nvd/cve-2026-114603 +python-pkg,opentelemetry-api,1.38.0,CVE-2026-126360,MEDIUM,1.45.2,fixed,opentelemetry-api: opentelemetry-api: Denial of Service via regular expression backtracking,https://avd.aquasec.com/nvd/cve-2026-126360 +python-pkg,pip,25.0.1,CVE-2025-8869,MEDIUM,25.3,fixed,pip: pip missing checks on symbolic link extraction,https://avd.aquasec.com/nvd/cve-2025-8869 +python-pkg,pip,25.0.1,CVE-2026-13346,MEDIUM,26.2.0,fixed,pip: pip: Arbitrary file installation via malicious package indexes,https://avd.aquasec.com/nvd/cve-2026-13346 +python-pkg,pip,25.0.1,CVE-2026-3219,MEDIUM,26.1,fixed,pip: pip: Incorrect file installation due to improper archive handling,https://avd.aquasec.com/nvd/cve-2026-3219 +python-pkg,pip,25.0.1,CVE-2026-6357,MEDIUM,26.1,fixed,pip: pip: Arbitrary code execution or information disclosure via malicious wheel package installation,https://avd.aquasec.com/nvd/cve-2026-6357 +python-pkg,pip,25.0.1,CVE-2026-8643,MEDIUM,26.1.2,fixed,python-pip: Path traversal via malicious entry point name in pip wheel installation allows arbitrary file overwrite,https://avd.aquasec.com/nvd/cve-2026-8643 +python-pkg,pip,25.0.1,CVE-2026-1703,LOW,26.0,fixed,pip: pip: Information disclosure via path traversal when installing crafted wheel archives,https://avd.aquasec.com/nvd/cve-2026-1703 +python-pkg,starlette,0.41.3,CVE-2025-62727,HIGH,0.49.1,fixed,starlette: Starlette DoS via Range header merging,https://avd.aquasec.com/nvd/cve-2025-62727 +python-pkg,starlette,0.41.3,CVE-2026-48818,HIGH,1.1.0,fixed,starlette: Starlette: SSRF and NTLM credential theft via UNC paths in StaticFiles on Windows,https://avd.aquasec.com/nvd/cve-2026-48818 +python-pkg,starlette,0.41.3,CVE-2026-54283,HIGH,1.3.1,fixed,starlette: Starlette: request.form() limits silently ignored for application/x-www-form-urlencoded enable DoS,https://avd.aquasec.com/nvd/cve-2026-54283 +python-pkg,starlette,0.41.3,CVE-2025-54121,MEDIUM,0.47.2,fixed,starlette: Starlette denial-of-service,https://avd.aquasec.com/nvd/cve-2025-54121 +python-pkg,starlette,0.41.3,CVE-2026-48710,MEDIUM,1.0.1,fixed,starlette: Starlette: Security restriction bypass via malformed HTTP Host header,https://avd.aquasec.com/nvd/cve-2026-48710 +python-pkg,starlette,0.41.3,CVE-2026-48817,MEDIUM,1.1.0,fixed,starlette: Starlette: Information disclosure and unintended method execution via non-standard HTTP methods,https://avd.aquasec.com/nvd/cve-2026-48817 +python-pkg,starlette,0.41.3,CVE-2026-54282,LOW,1.3.0,fixed,starlette: Starlette: Information disclosure due to improper HTTP request path validation,https://avd.aquasec.com/nvd/cve-2026-54282 diff --git a/evidence/scan-summary.json b/evidence/scan-summary.json new file mode 100644 index 0000000..76da73e --- /dev/null +++ b/evidence/scan-summary.json @@ -0,0 +1,40 @@ +{ + "before": { + "image_id": "sha256:0c0f7c060303d5c1157ca12f6c058b0475866c0a4852cb9a65de4df3289e784f", + "counts": { + "debian": { + "HIGH": 145, + "LOW": 164, + "MEDIUM": 232, + "UNKNOWN": 25, + "CRITICAL": 9 + }, + "python-pkg": { + "MEDIUM": 30, + "CRITICAL": 5, + "HIGH": 40, + "LOW": 2 + } + } + }, + "after": { + "image_id": "sha256:6e8a0e258485d21c9b4f239cf2856de6b9d0aefc0b34853dc82a74d28f7d1842", + "counts": { + "debian": { + "LOW": 114, + "HIGH": 100, + "MEDIUM": 148, + "UNKNOWN": 18, + "CRITICAL": 2 + }, + "python-pkg": { + "MEDIUM": 10, + "LOW": 2, + "HIGH": 3 + } + }, + "docker_manifest_id": "sha256:8ce282347ac73e6fd187038941b84d16df7cceede5a47e8310f381ae0275e3f6", + "scanner": "Trivy 0.76.2", + "scanned_at": "2026-11-27T18:52:12.467848599Z" + } +} diff --git a/evidence/security.txt b/evidence/security.txt new file mode 100644 index 0000000..ff2e222 --- /dev/null +++ b/evidence/security.txt @@ -0,0 +1 @@ +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 0000000..b484213 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1 @@ +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/telemetry.json b/evidence/telemetry.json new file mode 100644 index 0000000..23e227e --- /dev/null +++ b/evidence/telemetry.json @@ -0,0 +1,9 @@ +{ + "metric_series": 161, + "log_streams": 328, + "trace_results": 100, + "checked_trace_bodies": 20, + "credential_canaries_absent": true, + "grafana_write_denied": true, + "grafana_datasource_health": true +} \ No newline at end of file diff --git a/evidence/verification.txt b/evidence/verification.txt new file mode 100644 index 0000000..4523940 --- /dev/null +++ b/evidence/verification.txt @@ -0,0 +1,17 @@ +Verification date: 2026-11-27 (Europe/Moscow) +$ python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +PASS: Python syntax in 44 application/operator/test modules +PASS: public tests and OpenAPI unchanged; assignment README retained +PASS: staged files contain no generated secret values/private keys or temporary archives/caches/raw scans +PASS: REPORT and PR template filled; local Markdown links resolve +$ python scripts/lab7.py bootstrap +PASS: repeated bootstrap with existing volumes; HTTPS readiness 200 +$ python scripts/lab7.py verify +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. +PASS: 114 internal checks and 16 lifecycle checks; suite complete +PASS: all 26 running service containers inspected after suite; HTTPS readiness 200 with CA verification +PASS: Trivy 0.76.2 final image scan complete; config digest matched docker-save archive +$ git diff --cached --check +PASS: staged diff has no whitespace errors diff --git a/infra/grafana/provisioning/datasources/sources.yaml b/infra/grafana/provisioning/datasources/sources.yaml index 2a3dc75..68fb32c 100644 --- a/infra/grafana/provisioning/datasources/sources.yaml +++ b/infra/grafana/provisioning/datasources/sources.yaml @@ -1,41 +1,53 @@ +# Public template. lab7.py injects cert/key into ignored secrets/grafana-datasources. apiVersion: 1 datasources: - - name: Prometheus - uid: prometheus - type: prometheus - access: proxy - url: http://prometheus:9090 - isDefault: true - jsonData: - timeInterval: 5s - exemplarTraceIdDestinations: - - name: trace_id - datasourceUid: tempo - - name: Loki - uid: loki - type: loki - access: proxy - url: http://loki:3100 - jsonData: - derivedFields: - - name: trace_id - matcherType: label - matcherRegex: trace_id - datasourceUid: tempo - url: '$${__value.raw}' - urlDisplayLabel: View trace - - name: Tempo - uid: tempo - type: tempo - access: proxy - url: http://tempo:3200 - jsonData: - tracesToLogsV2: - datasourceUid: loki - spanStartTimeShift: '-5m' - spanEndTimeShift: '5m' - tags: [{key: service.name, value: service_name}] - filterByTraceID: true - filterBySpanID: false - nodeGraph: - enabled: true +- name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:19090 + isDefault: true + jsonData: + timeInterval: 5s + exemplarTraceIdDestinations: + - name: trace_id + datasourceUid: tempo + tlsAuth: true + tlsAuthWithCACert: true + serverName: prometheus +- name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:13100 + jsonData: + derivedFields: + - name: trace_id + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: $${__value.raw} + urlDisplayLabel: View trace + tlsAuth: true + tlsAuthWithCACert: true + serverName: loki +- name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:13200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -5m + spanEndTimeShift: 5m + tags: + - key: service.name + value: service_name + filterByTraceID: true + filterBySpanID: false + nodeGraph: + enabled: true + tlsAuth: true + tlsAuthWithCACert: true + serverName: tempo diff --git a/infra/nginx.conf b/infra/nginx.conf deleted file mode 100644 index 1cc308b..0000000 --- a/infra/nginx.conf +++ /dev/null @@ -1,38 +0,0 @@ -worker_processes 1; -worker_shutdown_timeout 8s; -events { worker_connections 1024; } -http { - upstream messenger { - zone messenger 64k; - include /etc/nginx/ready-backends.conf; - } - log_format upstream '$request_method $uri $status upstream=$upstream_addr ' - 'upstream_status=$upstream_status time=$request_time'; - access_log /var/log/nginx/access.log upstream; - server { - listen 8080; - # API enforces the byte limit and returns the contracted JSON error. - client_max_body_size 0; - client_body_timeout 5s; - client_header_timeout 5s; - keepalive_timeout 5s; - location / { - proxy_pass http://messenger; - proxy_http_version 1.1; - proxy_request_buffering off; - proxy_buffering off; - proxy_set_header Host $host; - proxy_set_header Connection close; - proxy_connect_timeout 1s; - proxy_send_timeout 35s; - proxy_read_timeout 120s; - # A 503 is an API response (for example, S3 is unavailable), so - # preserve it for the client instead of marking every replica down. - proxy_next_upstream error timeout http_502 http_504; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 8s; - # Never transparently retry a POST already sent to an API. - # A client retries messages using the original Idempotency-Key. - } - } -} diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 0850e23..db49ea9 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,7 +1,5 @@ -# OpenBao — реализовать конфигурацию и политики +# OpenBao -Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. - -Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения. - -Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md. +Non-dev file storage и TLS: config.hcl. Scoped KV policies: api/worker/dispatcher/cleanup.hcl. +Bootstrap, init/unseal и lifecycle: [инструкция оператора](../../security/OPERATIONS.md). +Секреты и ключи генерируются локально; в этом каталоге их нет. diff --git a/infra/openbao/api.hcl b/infra/openbao/api.hcl new file mode 100644 index 0000000..e880a9e --- /dev/null +++ b/infra/openbao/api.hcl @@ -0,0 +1,2 @@ +path "secret/data/api" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/cleanup.hcl b/infra/openbao/cleanup.hcl new file mode 100644 index 0000000..723539d --- /dev/null +++ b/infra/openbao/cleanup.hcl @@ -0,0 +1,2 @@ +path "secret/data/cleanup" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/config.hcl b/infra/openbao/config.hcl new file mode 100644 index 0000000..283c3a4 --- /dev/null +++ b/infra/openbao/config.hcl @@ -0,0 +1,11 @@ +ui = false +api_addr = "https://openbao:8200" +storage "file" { path = "/bao/data" } +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/identity/tls.crt" + tls_key_file = "/run/identity/tls.key" + tls_client_ca_file = "/run/identity/ca.crt" + tls_min_version = "tls12" + tls_max_version = "tls12" +} diff --git a/infra/openbao/dispatcher.hcl b/infra/openbao/dispatcher.hcl new file mode 100644 index 0000000..ca57393 --- /dev/null +++ b/infra/openbao/dispatcher.hcl @@ -0,0 +1,2 @@ +path "secret/data/dispatcher" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/worker.hcl b/infra/openbao/worker.hcl new file mode 100644 index 0000000..1a5e177 --- /dev/null +++ b/infra/openbao/worker.hcl @@ -0,0 +1,2 @@ +path "secret/data/worker" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index 529a107..8b336d9 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -2,8 +2,7 @@ receivers: otlp: protocols: http: - endpoint: 0.0.0.0:4318 - + endpoint: 127.0.0.1:4318 processors: memory_limiter: check_interval: 1s @@ -13,17 +12,16 @@ processors: timeout: 1s send_batch_size: 128 send_batch_max_size: 256 - exporters: prometheus: - endpoint: 0.0.0.0:8889 + endpoint: 127.0.0.1:8889 resource_to_telemetry_conversion: enabled: true enable_open_metrics: true metric_expiration: 30s translation_strategy: UnderscoreEscapingWithSuffixes otlphttp/loki: - endpoint: http://loki:3100/otlp + endpoint: https://loki:13100/otlp timeout: 2s sending_queue: queue_size: 32 @@ -33,8 +31,12 @@ exporters: initial_interval: 1s max_interval: 5s max_elapsed_time: 15s + tls: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key otlphttp/tempo: - endpoint: http://tempo:4318 + endpoint: https://tempo:14318 timeout: 2s sending_queue: queue_size: 32 @@ -44,26 +46,41 @@ exporters: initial_interval: 1s max_interval: 5s max_elapsed_time: 15s - + tls: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key service: telemetry: metrics: readers: - - pull: - exporter: - prometheus: - host: 0.0.0.0 - port: 8888 + - pull: + exporter: + prometheus: + host: 127.0.0.1 + port: 8888 pipelines: metrics: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [prometheus] + receivers: + - otlp + processors: + - memory_limiter + - batch + exporters: + - prometheus logs: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [otlphttp/loki] + receivers: + - otlp + processors: + - memory_limiter + - batch + exporters: + - otlphttp/loki traces: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [otlphttp/tempo] + receivers: + - otlp + processors: + - memory_limiter + - batch + exporters: + - otlphttp/tempo diff --git a/infra/otel/loki.yaml b/infra/otel/loki.yaml index b5cf04f..6d6df22 100644 --- a/infra/otel/loki.yaml +++ b/infra/otel/loki.yaml @@ -1,7 +1,10 @@ auth_enabled: false server: http_listen_port: 3100 + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 common: + instance_addr: 127.0.0.1 path_prefix: /loki replication_factor: 1 ring: @@ -13,13 +16,13 @@ common: rules_directory: /loki/rules schema_config: configs: - - from: 2024-01-01 - store: tsdb - object_store: filesystem - schema: v13 - index: - prefix: index_ - period: 24h + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h limits_config: allow_structured_metadata: true retention_period: 72h @@ -27,8 +30,10 @@ limits_config: resource_attributes: ignore_defaults: true attributes_config: - - action: index_label - attributes: [service.name, deployment.environment.name] + - action: index_label + attributes: + - service.name + - deployment.environment.name compactor: working_directory: /loki/compactor retention_enabled: true diff --git a/infra/otel/prometheus.yaml b/infra/otel/prometheus.yaml index 5613d18..547cb37 100644 --- a/infra/otel/prometheus.yaml +++ b/infra/otel/prometheus.yaml @@ -2,11 +2,23 @@ global: scrape_interval: 5s evaluation_interval: 5s rule_files: - - /etc/prometheus/alerts.yaml +- /etc/prometheus/alerts.yaml scrape_configs: - - job_name: messenger - static_configs: - - targets: ['otel-collector:8889'] - - job_name: collector - static_configs: - - targets: ['otel-collector:8888'] +- job_name: messenger + static_configs: + - targets: + - otel-collector:18889 + scheme: https + tls_config: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key +- job_name: collector + static_configs: + - targets: + - otel-collector:18888 + scheme: https + tls_config: + ca_file: /run/identity/ca.crt + cert_file: /run/identity/tls.crt + key_file: /run/identity/tls.key diff --git a/infra/otel/tempo.yaml b/infra/otel/tempo.yaml index 9653bf2..496f1b4 100644 --- a/infra/otel/tempo.yaml +++ b/infra/otel/tempo.yaml @@ -1,12 +1,16 @@ server: http_listen_port: 3200 + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 distributor: receivers: otlp: protocols: http: - endpoint: 0.0.0.0:4318 + endpoint: 127.0.0.1:4318 ingester: + lifecycler: + address: 127.0.0.1 trace_idle_period: 10s max_block_duration: 5m compactor: diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..6c31017 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,3 @@ +local all all trust +hostssl messenger all 0.0.0.0/0 scram-sha-256 +hostssl messenger all ::/0 scram-sha-256 diff --git a/infra/postgres/start.sh b/infra/postgres/start.sh new file mode 100644 index 0000000..d049130 --- /dev/null +++ b/infra/postgres/start.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +cp /run/identity/tls.key /tmp/server.key +chown postgres:postgres /tmp/server.key +chmod 600 /tmp/server.key +exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/run/identity/tls.crt -c ssl_key_file=/tmp/server.key -c hba_file=/etc/pg_hba.conf diff --git a/infra/readiness.sh b/infra/readiness.sh deleted file mode 100644 index 9a2e627..0000000 --- a/infra/readiness.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/sh -# Only ready API addresses enter the upstream, including at nginx startup. -update_backends() { - next=/etc/nginx/ready-backends.conf.next - : > "$next" - for address in $(getent ahostsv4 api | awk '{print $1}' | sort -u); do - if wget -q -T 1 -O /dev/null "http://$address:8080/health/ready"; then - echo "server $address:8080;" >> "$next" - fi - done - # If every running API temporarily loses a shared dependency (for example - # S3), retain the last addresses. The API can then return the contracted - # 503 instead of Nginx replacing it with a 502. At initial startup there - # is no previous healthy set, so use an inert placeholder. - if [ ! -s "$next" ]; then - if [ -s /etc/nginx/ready-backends.conf ] && ! grep -q '127.0.0.1:9 down' /etc/nginx/ready-backends.conf; then - rm -f "$next" - return - fi - echo 'server 127.0.0.1:9 down;' > "$next" - fi - if ! cmp -s "$next" /etc/nginx/ready-backends.conf; then - mv "$next" /etc/nginx/ready-backends.conf - if [ "${1:-}" = reload ] && [ -f /var/run/nginx.pid ]; then - nginx -s reload - fi - else - rm -f "$next" - fi -} - -update_backends -( - while sleep 2; do - update_backends reload - done -) & -exec nginx -g 'daemon off;' diff --git a/infra/s3-api-policy.json b/infra/s3-api-policy.json new file mode 100644 index 0000000..2496f64 --- /dev/null +++ b/infra/s3-api-policy.json @@ -0,0 +1 @@ +{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]}, {"Effect": "Allow", "Action": ["s3:PutObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/originals/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/variants/*"]}]} diff --git a/infra/s3-bootstrap.sh b/infra/s3-bootstrap.sh deleted file mode 100644 index c0baf62..0000000 --- a/infra/s3-bootstrap.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -set -eu -test "$MINIO_ROOT_USER" != "$S3_ACCESS_KEY_ID" -mc alias set local http://s3:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null -mc mb --ignore-existing local/messenger-attachments -mc anonymous set none local/messenger-attachments -mc admin user add local "$S3_ACCESS_KEY_ID" "$S3_SECRET_ACCESS_KEY" >/dev/null -mc admin policy info local attachments >/dev/null 2>&1 || mc admin policy create local attachments /policy.json -mc admin policy attach local attachments --user "$S3_ACCESS_KEY_ID" diff --git a/infra/s3-cleanup-policy.json b/infra/s3-cleanup-policy.json new file mode 100644 index 0000000..240313a --- /dev/null +++ b/infra/s3-cleanup-policy.json @@ -0,0 +1 @@ +{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]}, {"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/originals/*"]}, {"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/variants/*"]}]} diff --git a/infra/s3-policy.json b/infra/s3-policy.json deleted file mode 100644 index 8e77546..0000000 --- a/infra/s3-policy.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["s3:ListBucket", "s3:GetBucketLocation"], - "Resource": ["arn:aws:s3:::messenger-attachments"] - }, - { - "Effect": "Allow", - "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], - "Resource": ["arn:aws:s3:::messenger-attachments/originals/*", - "arn:aws:s3:::messenger-attachments/staging/*", - "arn:aws:s3:::messenger-attachments/variants/*"] - } - ] -} diff --git a/infra/s3-worker-policy.json b/infra/s3-worker-policy.json new file mode 100644 index 0000000..8d38ec9 --- /dev/null +++ b/infra/s3-worker-policy.json @@ -0,0 +1 @@ +{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]}, {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}, {"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/originals/*"]}, {"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/variants/*"]}]} diff --git a/infra/tls/api1.cfg b/infra/tls/api1.cfg new file mode 100644 index 0000000..9210b8a --- /dev/null +++ b/infra/tls/api1.cfg @@ -0,0 +1,20 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port8443 + bind :8443 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str lb } + server local 127.0.0.1:8080 diff --git a/infra/tls/api2.cfg b/infra/tls/api2.cfg new file mode 100644 index 0000000..9210b8a --- /dev/null +++ b/infra/tls/api2.cfg @@ -0,0 +1,20 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port8443 + bind :8443 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str lb } + server local 127.0.0.1:8080 diff --git a/infra/tls/broker.cfg b/infra/tls/broker.cfg new file mode 100644 index 0000000..19f7d19 --- /dev/null +++ b/infra/tls/broker.cfg @@ -0,0 +1,20 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port6380 + bind :6380 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str api dispatcher worker } + server local 127.0.0.1:6379 diff --git a/infra/tls/grafana.cfg b/infra/tls/grafana.cfg new file mode 100644 index 0000000..97b2d45 --- /dev/null +++ b/infra/tls/grafana.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port3443 + bind :3443 ssl crt /run/identity/tls.pem + server local 127.0.0.1:3000 diff --git a/infra/tls/lb.cfg b/infra/tls/lb.cfg new file mode 100644 index 0000000..f36b111 --- /dev/null +++ b/infra/tls/lb.cfg @@ -0,0 +1,34 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +frontend ingress + mode http + bind :8443 ssl crt /run/identity/tls.pem + http-request set-header X-Forwarded-Proto https + http-response set-header Strict-Transport-Security max-age=31536000 + default_backend apis +backend apis + mode http + balance roundrobin + option redispatch 1 + retries 1 + timeout connect 1s + option httpchk GET /health/ready + timeout check 1s + http-check expect status 200 + default-server inter 1s fall 1 rise 1 on-marked-down shutdown-sessions + server api1 api1:8443 ssl verify required ca-file /run/identity/ca.crt crt /run/identity/tls.pem verifyhost api1 sni str(api1) check check-sni api1 resolvers docker init-addr libc,none + server api2 api2:8443 ssl verify required ca-file /run/identity/ca.crt crt /run/identity/tls.pem verifyhost api2 sni str(api2) check check-sni api2 resolvers docker init-addr libc,none diff --git a/infra/tls/loki.cfg b/infra/tls/loki.cfg new file mode 100644 index 0000000..feede3e --- /dev/null +++ b/infra/tls/loki.cfg @@ -0,0 +1,24 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port13100 + bind :13100 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str otel-collector grafana operator } + mode http + http-request deny if { ssl_c_s_dn(CN) -m str grafana operator } !{ method GET HEAD } + http-request deny if { ssl_c_s_dn(CN) -m str otel-collector } !{ path /otlp/v1/logs } + http-request deny if { ssl_c_s_dn(CN) -m str otel-collector } !{ method POST } + server local 127.0.0.1:3100 diff --git a/infra/tls/otel-collector.cfg b/infra/tls/otel-collector.cfg new file mode 100644 index 0000000..8477cdd --- /dev/null +++ b/infra/tls/otel-collector.cfg @@ -0,0 +1,30 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port44318 + bind :44318 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str api worker dispatcher } + server local 127.0.0.1:4318 + +listen port18889 + bind :18889 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str prometheus } + server local 127.0.0.1:8889 + +listen port18888 + bind :18888 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str prometheus } + server local 127.0.0.1:8888 diff --git a/infra/tls/prometheus.cfg b/infra/tls/prometheus.cfg new file mode 100644 index 0000000..5feed70 --- /dev/null +++ b/infra/tls/prometheus.cfg @@ -0,0 +1,24 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port19090 + bind :19090 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str grafana operator } + mode http + acl read_post method POST + acl read_path path /api/v1/query /api/v1/query_range /api/v1/series + http-request deny unless { method GET HEAD } or read_post read_path + server local 127.0.0.1:9090 diff --git a/infra/tls/redis.cfg b/infra/tls/redis.cfg new file mode 100644 index 0000000..b683045 --- /dev/null +++ b/infra/tls/redis.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port6380 + bind :6380 ssl crt /run/identity/tls.pem + server local 127.0.0.1:6379 diff --git a/infra/tls/s3.cfg b/infra/tls/s3.cfg new file mode 100644 index 0000000..1e178f3 --- /dev/null +++ b/infra/tls/s3.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port9443 + bind :9443 ssl crt /run/identity/tls.pem + server local 127.0.0.1:9000 diff --git a/infra/tls/tempo.cfg b/infra/tls/tempo.cfg new file mode 100644 index 0000000..4b7d04d --- /dev/null +++ b/infra/tls/tempo.cfg @@ -0,0 +1,29 @@ +global + maxconn 256 + ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + mode tcp + timeout connect 2s + timeout client 120s + timeout server 120s +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + +listen port13200 + bind :13200 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str grafana operator } + mode http + http-request deny unless { method GET HEAD } + server local 127.0.0.1:3200 + +listen port14318 + bind :14318 ssl crt /run/identity/tls.pem ca-file /run/identity/ca.crt crl-file /run/identity/ca.crl verify required + tcp-request content reject unless { ssl_c_s_dn(CN) -m str otel-collector } + mode http + http-request deny unless { method POST } { path /v1/traces } + server local 127.0.0.1:4318 diff --git a/requirements-operator.txt b/requirements-operator.txt new file mode 100644 index 0000000..e621012 --- /dev/null +++ b/requirements-operator.txt @@ -0,0 +1,3 @@ +cryptography==50.0.2 +PyYAML==6.0.3 +requests==2.34.2 diff --git a/requirements.txt b/requirements.txt index 01c2cf2..e0f5a6d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,7 +16,7 @@ SQLAlchemy==2.0.41 redis==5.2.1 argon2-cffi==23.1.0 boto3==1.40.70 -Pillow==12.0.0 +Pillow==13.0.0 opentelemetry-api==1.38.0 opentelemetry-sdk==1.38.0 opentelemetry-exporter-otlp-proto-http==1.38.0 diff --git a/scripts/lab7.py b/scripts/lab7.py new file mode 100644 index 0000000..d89f21f --- /dev/null +++ b/scripts/lab7.py @@ -0,0 +1,328 @@ +"""Local operator: bootstrap, unseal, rotate. Never print secret material.""" +import argparse +import datetime as dt +import ipaddress +import json +import os +from pathlib import Path +import secrets +import subprocess +import sys +import time + +import requests +import yaml +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID + +ROOT = Path(__file__).resolve().parents[1] +os.chdir(ROOT) +PRIVATE = ROOT / 'secrets/operator-private' +ROLES = ['api', 'worker', 'dispatcher', 'cleanup'] +IDENTITIES = ROLES + ['api1','api2','lb','postgres','redis','broker','s3','openbao', + 'otel-collector','prometheus','loki','tempo','grafana','operator','outsider'] + + +def write(path, data): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data, encoding='utf-8', newline='\n') + if os.name != 'nt': path.chmod(0o600) + + +def docker(*args, data=None, check=True): + result = subprocess.run(['docker', *args], input=data.encode('utf-8') if data is not None else None, capture_output=True) + result.stdout = result.stdout.decode('utf-8', errors='replace') + result.stderr = result.stderr.decode('utf-8', errors='replace') + if check and result.returncode: + # Commands/stdin/output can contain credentials; keep failure messages bounded. + diagnostic=result.stderr + def hide(value): + nonlocal diagnostic + if isinstance(value,dict): + for child in value.values(): hide(child) + elif isinstance(value,list): + for child in value: hide(child) + elif isinstance(value,str) and len(value)>8: diagnostic=diagnostic.replace(value,'[redacted]') + for file in PRIVATE.glob('*.json'): hide(json.loads(file.read_text())) + for file in (ROOT/'secrets').glob('*-admin/*'): hide(file.read_text()) + raise RuntimeError('Docker operation failed: ' + ' '.join(args[:3])+'\n'+diagnostic[-1500:]) + return result + + +def compose(*args, **kw): + return docker('compose', *args, **kw) + + +def ca(): + return (serialization.load_pem_private_key((PRIVATE/'ca.key').read_bytes(), password=None), + x509.load_pem_x509_certificate((ROOT/'secrets/ca.crt').read_bytes())) + + +def issue(name, expired=False, identity=None, untrusted=False): + key, authority = ca() + identity = identity or name + issuer = authority.subject + if untrusted: + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + issuer = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Untrusted CA')]) + leaf_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + now = dt.datetime.now(dt.timezone.utc) + names = [x509.DNSName(identity)] + if identity in ('lb','openbao','grafana'): + names += [x509.DNSName('localhost'),x509.IPAddress(ipaddress.ip_address('127.0.0.1'))] + cert = (x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,identity)])) + .issuer_name(issuer).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now-dt.timedelta(days=2) if expired else now-dt.timedelta(minutes=5)) + .not_valid_after(now-dt.timedelta(days=1) if expired else now+dt.timedelta(hours=24)) + .add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),critical=False) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()),critical=False) + .add_extension(x509.KeyUsage(True,False,True,False,False,False,False,False,False),critical=True) + .add_extension(x509.SubjectAlternativeName(names),critical=False) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False) + .sign(key,hashes.SHA256())) + folder=ROOT/'secrets'/name + cert_pem=cert.public_bytes(serialization.Encoding.PEM).decode() + key_pem=leaf_key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()).decode() + for filename,content in [('tls.crt',cert_pem),('tls.key',key_pem),('tls.pem',cert_pem+key_pem),('ca.crt',authority.public_bytes(serialization.Encoding.PEM).decode())]: + write(folder/filename,content) + return cert + + +def crl(serials=()): + key,authority=ca() + now=dt.datetime.now(dt.timezone.utc) + builder=x509.CertificateRevocationListBuilder().issuer_name(authority.subject).last_update(now).next_update(now+dt.timedelta(days=7)) + for serial in serials: + builder=builder.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(serial).revocation_date(now).build()) + pem=builder.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode() + for folder in (ROOT/'secrets').iterdir(): + if folder.is_dir() and (folder/'tls.crt').exists(): write(folder/'ca.crl',pem) + + +def generate(): + if (PRIVATE/'ca.key').exists(): + print('Existing local secrets preserved'); return + PRIVATE.mkdir(parents=True,exist_ok=True) + if os.name=='nt': + user = subprocess.check_output(['whoami'],text=True).strip() + subprocess.run(['icacls',str(ROOT/'secrets'),'/inheritance:r','/grant:r',user+':(OI)(CI)F'],check=True,capture_output=True) + key=rsa.generate_private_key(public_exponent=65537,key_size=3072) + name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Lab7 local CA')]) + now=dt.datetime.now(dt.timezone.utc) + cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()) + .serial_number(x509.random_serial_number()).not_valid_before(now-dt.timedelta(minutes=5)).not_valid_after(now+dt.timedelta(days=30)) + .add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),critical=False) + .add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),critical=True).sign(key,hashes.SHA256())) + write(PRIVATE/'ca.key',key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()).decode()) + write(ROOT/'secrets/ca.crt',cert.public_bytes(serialization.Encoding.PEM).decode()) + for identity in IDENTITIES: issue(identity) + test_certificates() + crl() + config={role:{'db':secrets.token_hex(24),'s3':secrets.token_hex(24),'redis':secrets.token_hex(24),'broker':secrets.token_hex(24)} for role in ROLES} + write(PRIVATE/'credentials.json',json.dumps(config)) + for p in ['postgres-admin/postgres-password','s3-admin/password','grafana-admin/password']: + write(ROOT/'secrets'/p,secrets.token_hex(24)) + write(ROOT/'secrets/s3-admin/user','operator') + redis_config(config) + refresh_datasources() + print('Created local CA, 24-hour identities and independent service credentials') + + +def refresh_datasources(): + datasource=yaml.safe_load((ROOT/'infra/grafana/provisioning/datasources/sources.yaml').read_text()) + for ds in datasource['datasources']: + port={'prometheus':19090,'loki':13100,'tempo':13200}[ds['uid']] + ds['url']=f"https://{ds['uid']}:{port}" + ds.setdefault('jsonData',{}).update(tlsAuth=True,tlsAuthWithCACert=True,serverName=ds['uid']) + ds['secureJsonData']={'tlsCACert':(ROOT/'secrets/ca.crt').read_text(), + 'tlsClientCert':(ROOT/'secrets/grafana/tls.crt').read_text(), + 'tlsClientKey':(ROOT/'secrets/grafana/tls.key').read_text()} + write(ROOT/'secrets/grafana-datasources/sources.yaml',yaml.safe_dump(datasource,sort_keys=False)) + + +def test_certificates(): + # Keep the allowed role constant: isolate CA trust and expiry from the CN allowlist. + for identity in ['lb','worker','api']: + issue('expired-'+identity,expired=True,identity=identity) + issue('foreign-'+identity,identity=identity,untrusted=True) + + +def redis_config(config): + for name in ['redis','broker']: + lines=['user default off'] + if name=='redis': + lines.append(f"user api on >{config['api']['redis']} ~session:* ~history-v4:* ~login:* +ping +get +set +del +eval +incr +expire +pttl +ttl +client|setinfo") + else: + for role,commands in [('api','+ping'),('dispatcher','+ping +xadd +xgroup|create'), + ('worker','+ping +xgroup|create +xautoclaim +xreadgroup +xack +xdel +multi +exec')]: + lines.append(f"user {role} on >{config[role]['broker']} ~attachment-jobs {commands} +client|setinfo") + write(ROOT/f'secrets/{name}-config/users.acl','\n'.join(lines)+'\n') + write(ROOT/f'secrets/{name}-config/redis.conf','bind 127.0.0.1\nprotected-mode yes\nport 6379\nappendonly yes\nappendfsync always\nmaxmemory 128mb\nmaxmemory-policy noeviction\naclfile /run/config/users.acl\n') + + +def bao(method,path,payload=None,token=None,role=None): + session=requests.Session();session.trust_env=False + cert=None if role is None else (str(ROOT/f'secrets/{role}/tls.crt'),str(ROOT/f'secrets/{role}/tls.key')) + response=session.request(method,'https://127.0.0.1:8200/v1/'+path,json=payload, + headers={'X-Vault-Token':token} if token else {},cert=cert,verify=str(ROOT/'secrets/ca.crt'),timeout=5) + if response.status_code>=400: raise RuntimeError(f'OpenBao {path}: HTTP {response.status_code}') + return response.json() if response.content else {} + + +def unseal(): + state=json.loads((PRIVATE/'bao-init.json').read_text()) + if bao('GET','sys/seal-status')['sealed']: + bao('POST','sys/unseal',{'key':state['keys_base64'][0]}) + print('OpenBao unsealed by operator') + + +def initialize_bao(): + if not bao('GET','sys/init')['initialized']: + state=bao('POST','sys/init',{'secret_shares':1,'secret_threshold':1}) + write(PRIVATE/'bao-init.json',json.dumps(state)) + unseal() + state=json.loads((PRIVATE/'bao-init.json').read_text());token=state['root_token'] + mounts=bao('GET','sys/mounts',token=token) + if 'secret/' not in mounts: bao('POST','sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token) + auth=bao('GET','sys/auth',token=token) + if 'cert/' not in auth: bao('POST','sys/auth/cert',{'type':'cert'},token) + for role in ROLES: + policy=(ROOT/f'infra/openbao/{role}.hcl').read_text(encoding='utf-8') + bao('PUT','sys/policies/acl/'+role,{'policy':policy},token) + bao('POST','auth/cert/certs/'+role,{'certificate':(ROOT/'secrets/ca.crt').read_text(), + 'allowed_common_names':[role],'allowed_dns_sans':[role],'token_policies':[role], + 'token_ttl':60,'token_max_ttl':60,'token_explicit_max_ttl':60,'token_no_default_policy':True},token) + publish_secrets(token) + + +def publish_secrets(token): + config=json.loads((PRIVATE/'credentials.json').read_text()) + for role in ROLES: + c=config[role] + data={'DATABASE_URL':f"postgresql+psycopg://{role}:{c['db']}@postgres/messenger?sslmode=verify-full&sslrootcert=/run/identity/ca.crt"} + if role=='api': data['REDIS_URL']=f"rediss://api:{c['redis']}@redis:6380/0" + if role in ['api','worker','dispatcher']: data['BROKER_URL']=f"rediss://{role}:{c['broker']}@broker:6380/0" + if role in ['api','worker','cleanup']: + data.update(S3_ENDPOINT='https://s3:9443',S3_ACCESS_KEY_ID=role,S3_SECRET_ACCESS_KEY=c['s3']) + bao('POST','secret/data/'+role,{'data':data},token) + + +def prepare_volumes(): + volumes={'postgres':999,'redis':999,'broker':999,'s3':1000,'bao':100,'prometheus':65534,'loki':1000,'tempo':1000,'grafana':472} + for name,uid in volumes.items(): + docker('run','--rm','--network','none','--user','0','-v',f'mtusi2026lab7_{name}_data:/data', + '--entrypoint','sh','redis:7.4.2-bookworm','-c',f'chown {uid}:{uid} /data') + + +def database(): + config=json.loads((PRIVATE/'credentials.json').read_text()) + sql="CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY);\n" + for file in sorted((ROOT/'migrations').glob('*.sql')): + sql+=f"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version='{file.name}') AS applied \\gset\n\\if :applied\n\\else\nBEGIN;\n"+file.read_text()+f"\nINSERT INTO schema_migrations VALUES ('{file.name}'); COMMIT;\n\\endif\n" + sql+='REVOKE CREATE ON SCHEMA public FROM PUBLIC; REVOKE ALL ON DATABASE messenger FROM PUBLIC;\n' + for role in ROLES: + sql+=f"DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='{role}') THEN CREATE ROLE {role} LOGIN; END IF; END $$;\nALTER ROLE {role} PASSWORD '{config[role]['db']}'; GRANT CONNECT ON DATABASE messenger TO {role}; GRANT USAGE ON SCHEMA public TO {role};\n" + sql+='GRANT SELECT, INSERT, UPDATE ON users,chats,chat_members,messages,message_idempotency,attachments,attachment_jobs TO api;\n' + sql+='GRANT SELECT, UPDATE ON attachments,attachment_jobs TO worker,dispatcher;\nGRANT SELECT, UPDATE ON attachments TO cleanup;\n' + compose('exec','-T','postgres','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=sql) + + +def storage(): + cfg=json.loads((PRIVATE/'credentials.json').read_text()) + admin_user=(ROOT/'secrets/s3-admin/user').read_text();admin_pass=(ROOT/'secrets/s3-admin/password').read_text() + script=f"set -eu\nexport MC_CONFIG_DIR=/tmp/mc\nmc alias set local http://127.0.0.1:9000 {admin_user} {admin_pass} >/dev/null\nmc mb --ignore-existing local/messenger-attachments >/dev/null\nmc anonymous set none local/messenger-attachments >/dev/null\n" + for role in ['api','worker','cleanup']: + policy=(ROOT/f'infra/s3-{role}-policy.json').read_text(encoding='utf-8').strip() + script+=f"cat > /tmp/{role}.json <<'POLICY'\n{policy}\nPOLICY\nmc admin user add local {role} {cfg[role]['s3']} >/dev/null\nmc admin policy create local {role} /tmp/{role}.json >/dev/null\nmc admin policy attach local {role} --user {role} >/dev/null\n" + compose('exec','-T','s3','sh',data=script) + + +def wait_service(test,seconds=60): + deadline=time.monotonic()+seconds + while True: + try: + if test(): return + except (requests.RequestException,RuntimeError): pass + if time.monotonic()>deadline: raise RuntimeError('Service readiness timeout') + time.sleep(1) + + +def bootstrap(): + generate() + compose('config','--quiet') + prepare_volumes() + compose('up','-d','postgres','redis','broker','s3','openbao') + wait_service(lambda: bao('GET','sys/init') is not None) + initialize_bao() + wait_service(lambda: compose('exec','-T','postgres','pg_isready','-U','postgres',check=False).returncode==0) + database() + wait_service(lambda: compose('exec','-T','s3','curl','-sf','http://127.0.0.1:9000/minio/health/live',check=False).returncode==0) + storage() + compose('up','-d','--build') + wait_service(lambda: requests.get('https://localhost:8443/health/ready',verify=str(ROOT/'secrets/ca.crt'),timeout=3).status_code==200,90) + print('PASS: https://localhost:8443/health/ready; CA: secrets/ca.crt') + + +def rotate_secret(): + cfg=json.loads((PRIVATE/'credentials.json').read_text()) + cfg['api']['db']=secrets.token_hex(24) + write(PRIVATE/'credentials.json',json.dumps(cfg)) + compose('exec','-T','postgres','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=f"ALTER ROLE api PASSWORD '{cfg['api']['db']}'; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='api';") + publish_secrets(json.loads((PRIVATE/'bao-init.json').read_text())['root_token']) + print('API database credential rotated; existing connections terminated; supervisor reload <=10s') + + +def rotate_leaf(): + archive=ROOT/'secrets/old-lb';archive.mkdir(exist_ok=True) + for name in ['tls.crt','tls.key','ca.crt']: write(archive/name,(ROOT/'secrets/lb'/name).read_text()) + old=x509.load_pem_x509_certificate((archive/'tls.crt').read_bytes()) + revoked_file=PRIVATE/'revoked.json' + revoked=json.loads(revoked_file.read_text()) if revoked_file.exists() else [] + revoked.append(old.serial_number);write(revoked_file,json.dumps(revoked)) + issue('lb');crl(revoked) + compose('restart','api1-tls','api2-tls','lb') + print('LB leaf rotated, old serial revoked; TLS listeners restarted to close old sessions') + + +def verify(): + for name in ['smoke','security']: + result=compose('run','--rm','--no-deps','audit',f'/tests/{name}.py', + '--base-url','https://lb:8443','--ca-file','/audit-secrets/ca.crt') + write(ROOT/f'evidence/{name}.txt',result.stdout) + print(result.stdout.strip()) + subprocess.run([sys.executable,'-X','utf8','-u',str(ROOT/'student-tests/lifecycle.py')],check=True) + + +def restart_stack(): + services=json.loads(compose('config','--format','json').stdout)['services'] + proxies=[n for n in services if n.endswith('-tls')]+['lb'] + owners=[n for n,spec in services.items() if n not in proxies and not spec.get('profiles')] + compose('stop',*proxies) + compose('restart',*owners) + wait_service(lambda: bao('GET','sys/seal-status')['sealed'],30) + unseal() + compose('start',*proxies) + print('Restarted owners before TLS sidecars; data volumes preserved') + + +def renew_leaves(): + """Operator renewal before 24h expiry; not an automated PKI service.""" + for identity in IDENTITIES: issue(identity) + revoked_file=PRIVATE/'revoked.json' + crl(json.loads(revoked_file.read_text()) if revoked_file.exists() else []) + refresh_datasources() + restart_stack() + print('24-hour service identities renewed; no image rebuild') + + +if __name__=='__main__': + sys.stdout.reconfigure(line_buffering=True) + parser=argparse.ArgumentParser() + parser.add_argument('command',choices=['generate','bootstrap','unseal','rotate-secret','rotate-leaf','status','verify','renew-leaves','restart']) + args=parser.parse_args() + {'generate':generate,'bootstrap':bootstrap,'unseal':unseal,'rotate-secret':rotate_secret,'rotate-leaf':rotate_leaf,'status':lambda: print(bao('GET','sys/init')),'verify':verify,'renew-leaves':renew_leaves,'restart':restart_stack}[args.command]() diff --git a/security/OPERATIONS.md b/security/OPERATIONS.md new file mode 100644 index 0000000..feb26f8 --- /dev/null +++ b/security/OPERATIONS.md @@ -0,0 +1,86 @@ +# Запуск и проверка lab7 на 4 + +Нужны Docker Compose и Python 3.12+ у оператора. Из корня репозитория: + +```sh +python -m pip install -r requirements-operator.txt +python scripts/lab7.py bootstrap +python scripts/lab7.py verify +``` + +Bootstrap генерирует CA/leaf и независимые credentials, готовит named volumes, +поднимает PostgreSQL/Redis/S3/OpenBao, выполняет init/unseal, настраивает cert auth, +политики KV, DB grants/S3 policies и запускает приложение. Повторный bootstrap +сохраняет существующие данные и secrets. Результаты и ограничения описаны в REPORT.md. + +API: https://localhost:8443. CA: secrets/ca.crt. Grafana: https://localhost:3443, +логин admin, пароль в secrets/grafana-admin/password. OpenBao: https://127.0.0.1:8200. +Все опубликованные порты привязаны к loopback host. Доступ из браузера требует доверия +локальному CA; тесты передают CA явно и никогда не отключают проверку TLS. + +## Bootstrap trust и renewal + +Оператор создаёт CA private key и хранит его в secrets/operator-private. Каталог secrets +исключён из Git и Docker build context; на Windows bootstrap ограничивает NTFS ACL +текущим пользователем. Не передавать эту папку вместе с проектом. Сервисам монтируется +только их identity, CA public certificate и CRL. Operator/audit инструмент имеет более +широкие права для воспроизводимых отрицательных тестов и не является рабочим сервисом. + +OpenBao использует persistent file storage, не dev-mode. Для одного учебного оператора +init создаёт один unseal share (threshold=1). Он и root token остаются в локальном +operator-private/bao-init.json, не монтируются в OpenBao/API/worker. Это ручной bootstrap, +не auto-unseal. После перезапуска OpenBao: + +```sh +python scripts/lab7.py unseal +``` + +Сервисы используют cert auth, читают только свой KV path, получают token с TTL/maxTTL +60s и повторяют аутентификацию каждые 10s. Token после чтения отзывается; конфигурация +кешируется в памяти не более 60s. При изменении secret supervisor перезапускает child; +при sealed/unavailable OpenBao прекращает его работу после истечения cache. После +unseal повторный cert auth восстанавливает сервис. Ни постоянного SecretID, ни root +токена, ни fallback password в образе приложения нет. + +Leaf действует 24 часа, CA 30 дней. Renewal выполняет оператор до expiry; пример +проверенной ротации LB с отзывом предыдущего serial: + +```sh +python scripts/lab7.py rotate-leaf +python scripts/lab7.py rotate-secret +``` + +Первый вызов заменяет LB leaf, публикует CRL и перезапускает оба API TLS listener и LB, +закрывая старые TLS-сессии/resumption. Второй меняет API DB password, разрывает существующие +DB connections и обновляет KV. Новые секреты подхватываются <=10s. Образы не пересобираются. +Для остальных identities используется renew-leaves; ключ CA переиздаётся отдельно при +истечении 30 дней на новом учебном стенде. Автоматическая PKI/CA rollover — не трек этой работы. + +## Hardening и ограничения + +У всех сервисов read_only, no-new-privileges, cap_drop ALL, CPU/RAM limits и /tmp tmpfs. +API/worker и TLS proxies работают non-root. PostgreSQL стартует entrypoint с CHOWN, +DAC_OVERRIDE/FOWNER/SETUID/SETGID для подготовки volume и приватного server key, затем +переходит в postgres. Stateful volumes остаются writable: это необходимые данные, +а не writable root filesystem. Bootstrap chown выполняется отдельным operator container. + +Приложение слушает только loopback; TLS sidecar делит с ним namespace. При restart +основного контейнера следует restart его sidecar после запуска: это важно для Docker +namespace lifecycle. Полный verify делает это явно. Для полного restart используйте `python scripts/lab7.py restart`: сначала owners, затем TLS sidecars, без гонки network namespaces. TLS1.2 у OpenBao совместим с локальным +Python/OpenSSL; остальной transport допускает TLS1.2/1.3. Проверка CA/SAN везде обязательна. + +Argon2id: m=19456 KiB, t=2, p=1, random salt; старые параметры обновляются после успешного +входа. Измерение времени в evidence/internal.json выполнено в audit-контейнере (0.5 CPU/256MiB); это latency, не гарантия RPS. не более двух hash operations на API +(около 38 MiB под Argon2), не более 32/s на весь стенд и 8/10s на username через общий Redis. +При недоступности Redis вход fail-closed с 503; 429 содержит Retry-After: 1. + +Upload worker: 2 CPU, 2GiB, два subprocess, 768MiB RLIMIT_AS и timeout 60s на задачу. +Изображения только PNG/JPEG, ограничены bytes/pixels; варианты JPEG/WebP. + +## Evidence + +verify выполняет публичные smoke/security, отрицательный TLS/ACL аудит, rehash/expiry, +последовательный отказ обеих API, restart с сохранением sessions/messages/attachments, +ротацию DB password и LB leaf, OpenBao token expiry/seal/unseal, проверку трёх сигналов +и отсутствия секретов в telemetry. Только синтетические данные; секреты не записываются +в evidence. Scan и применимость CVE описаны в SCAN_TRIAGE.md. diff --git a/security/SCAN_TRIAGE.md b/security/SCAN_TRIAGE.md new file mode 100644 index 0000000..9aabdb2 --- /dev/null +++ b/security/SCAN_TRIAGE.md @@ -0,0 +1,38 @@ +# Dependency/image scan и применимость + +Проверен **собранный образ приложения**, включая Debian packages и Python dependencies, +Trivy 0.76.2, vulnerability DB загружена 27.11.2026. Сканер получает docker-save archive, +не Docker socket и не secrets. Полные локальные отчёты: evidence/raw/image-scan.json (до), +evidence/raw/image-scan-updated.json (после). В Git сохранены evidence/scan-findings.csv +со всеми находками повторного scan и evidence/scan-summary.json с итогами до/после. +Это не полный scan всех сторонних инфраструктурных images; их pinned версии перечислены +в compose.yaml. Не заявляется отсутствие CVE или промышленная готовность. + +Воспроизведение из PowerShell, путь к archive можно выбрать локально: + +```powershell +docker save -o C:\vnp\lab7-app-scan.tar mtusi2026lab7-api:local +New-Item -ItemType Directory -Force evidence/raw +docker run --rm --cap-drop ALL --security-opt no-new-privileges -v C:\vnp\lab7-app-scan.tar:/scan/image.tar:ro -v C:\vnp\mtusi2026lab7\evidence\raw:/out -v lab7_trivy_cache:/root/.cache aquasec/trivy:0.76.2 image --input /scan/image.tar --scanners vuln --format json --output /out/image-scan-updated.json --quiet +``` + +| Finding | Реальная применимость | Решение / оставшийся риск | +| --- | --- | --- | +| Pillow 12.0.0, в т.ч. CVE-2026-112403 JPEG decode и семейство CVE-2026-11239x/11240x | JPEG/PNG из пользовательских uploads реально декодируются API и worker; просто лимит размера не устраняет memory corruption | Обновлён до 13.0.0; повторены smoke/варианты. Python-dependency CRITICAL: 5 → 0 | +| Старая базовая ОС/Python 3.12.8 | TLS, standard library и native dependencies реально используются | База обновлена до python:3.12.16-slim-bookworm. Debian CRITICAL 9 → 2, HIGH 145 → 100; это не доказательство неприменимости остальных | +| OpenTelemetry API CVE-2026-114603, CVE-2026-126360 | Наш TraceContextTextMapPropagator принимает HTTP и JSON-carrier; regex DoS был достижим | Перед extract ограничены traceparent ровно 55 символами и tracestate 512 символами, остальные поля отброшены. Применено и к worker/dispatcher. Сканер всё ещё видит старую версию; это локальная mitigation, не исправление зависимости upstream | +| Starlette CVE-2025-62727 Range merging | Требует FileResponse; приложение использует StreamingResponse без Range processing | Уязвимая ветка не вызывается. При добавлении FileResponse потребуется обновить совместимые FastAPI/Starlette | +| Starlette CVE-2026-48818 Windows StaticFiles/UNC | Runtime Linux, StaticFiles не используется | Неприменимо к текущим маршрутам | +| Starlette CVE-2025-54121/CVE-2026-54283 multipart/form parsing | request.form(), multipart и urlencoded не используются; JSON/raw upload имеют собственные byte limits | Неприменимо к текущему input path; добавление forms требует обновления | +| Остальные Starlette path/Host/method findings | Приложение не использует Host для authorization; FastAPI routing, UUID validation и DB ACL остаются обязательными | Публичный smoke/ACL проверяют контракт, но это не полное доказательство для произвольного HTTP parser attack; остаточный риск принят в учебной модели | +| pip 25.0.1 installation findings | В рабочем контейнере packages не устанавливаются: non-root/read_only/no network egress; установка только на build с pinned direct dependencies | Runtime path отсутствует; supply-chain риск сборки остаётся, transitive packages не hash-locked | +| libsqlite3-0 CVE-2025-7458, CRITICAL | Приложение использует PostgreSQL; SQLite API не вызывается | Пакет присутствует в base image, опасный SQL path приложением не экспонирован | +| zlib1g CVE-2023-45853, CRITICAL | Finding относится к minizip zipOpenNewFileInZip4_6, не к обычному zlib inflate | Приложение ZIP/minizip не создаёт; не считать весь zlib безопасным по одному этому выводу | +| PAM CVE-2025-6020, HIGH с доступным исправлением | Локальный PAM login/pam_namespace не используется, shell login не публикуется; app non-root без caps | Не достигается бизнес-API; исправление пакета необходимо при расширении модели до локального login | +| Kerberos libraries и остальные Debian findings | DB auth SCRAM, не GSSAPI/Kerberos; util-linux/mount не вызываются приложением; app без capabilities | Все находки сохранены в CSV. Для libc/OpenSSL и других используемых библиотек нельзя объявлять blanket false-positive: остаточный риск base image, нужен отдельный upstream patch review перед production | + +Принимается только учебный стенд с доверенным оператором/host, закрытыми внутренними +портами и ограниченными ресурсами. Исходные CVE, versions, fixed version и ссылки на +advisory сохранены построчно в CSV: неподтверждённые находки не скрыты allowlist-файлом. +Документация сканирования: https://trivy.dev/docs/v0.68/guide/target/container_image/. +Релиз исправленного Pillow: https://pypi.org/project/pillow/13.0.0/. diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..04ebe0e 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,26 @@ -# Модель угроз — заполнить +# Модель угроз учебного стенда -## Активы и акторы +Активы: пароли и сессии, сообщения и вложения, очередь обработки, service credentials, +CA/ключи и telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, +скомпрометированный сервис и оператор Docker-host. Оператор и host доверенные. +Один host не защищён от собственной компрометации или потери. Ключ CA и unseal material +не монтируются в рабочие контейнеры. Сетевые границы: [матрица](../contracts/trust-matrix.md). -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +| Путь атаки | Инвариант и контроль | Отрицательная проверка | Остаточное ограничение | +| --- | --- | --- | --- | +| Eve читает metadata/content Alice или прикрепляет файл другого чата | Bearer + членство в PostgreSQL, 404 | smoke и lifecycle cross-chat | Администратор БД доверенный | +| Подстановка X-User-Id | Header не определяет пользователя | smoke | Украденный Bearer действует до logout/expiry | +| Обход LB прямым вызовом API | Loopback приложения, mTLS CN=lb и CRL | internal: no cert, foreign, outsider, expired, old-lb и plaintext bypass | Root host может войти в namespace | +| Worker публикует поддельные задания | mTLS identity + отдельные Redis producer/consumer ACL | internal: worker/API XADD и dispatcher XREADGROUP запрещены | Worker имеет права на рабочую очередь | +| Worker читает password hashes или получает admin secrets | DB grants, S3 prefix policies, scoped KV paths | internal: SELECT users, DDL, чужой KV, policy write, PutObject запрещены | Нет построчной изоляции задач worker | +| Login DoS на двух репликах | Redis: 32/s глобально, 8/10s на username; 2 hash slots/API | internal: две реплики, 429/Retry-After, измерение Argon2 | Атакующий может исчерпать общий бюджет и задержать законный вход | +| Подмена сервера зависимости | CA + hostname, verify-full, без plaintext fallback | internal: неверный hostname, TLS и закрытые plaintext ports | Локальный hop доверяет процессам одного namespace | +| Grafana пытается писать telemetry | mTLS CN grafana, GET/HEAD и POST только query/query_range/series Prometheus; отдельный ingest Collector | lifecycle: POST denied | Grafana вправе читать диагностику | +| Повторное использование старого secret/cert | Смена DB password с разрывом сессий, CRL + restart listeners | lifecycle: старые credentials отклонены на новых соединениях | Краткий перерыв при ротации допустим | +| OpenBao sealed, недоступен или token истёк | Token TTL 60s, cert auth каждые 10s, остановка child после 60s без secrets | lifecycle: expiry/seal/unseal | Restart OpenBao требует operator unseal | +| Изображение расходует CPU/RAM | Worker 2 CPU/2GiB, 2 subprocess, 768MiB address space и 60s на задачу, bytes/pixels limits | Compose, image_processor/worker, smoke обработки | Image decoder остаётся attack surface; Pillow обновлён после scan | +| Credentials попадают в error/log/trace | Технический allowlist, SQL hide_parameters, общие API errors | lifecycle: поиск реальных synthetic canaries/service secrets в logs/Loki/Tempo | Оператор может прочитать память процесса | -## Границы доверия - -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. - -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | -| --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | - -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. - -## Lifecycle и инциденты - -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +Bootstrap/renewal и исключения hardening: [OPERATIONS.md](OPERATIONS.md). +Результаты — в evidence, применимость CVE — в SCAN_TRIAGE.md. Это учебная модель, +а не заявление о промышленной готовности. diff --git a/src/auth.py b/src/auth.py index ab93a9f..568b8c8 100644 --- a/src/auth.py +++ b/src/auth.py @@ -3,6 +3,7 @@ import json import os import re import secrets +from threading import BoundedSemaphore from datetime import datetime, timedelta, timezone from argon2 import PasswordHasher @@ -11,7 +12,28 @@ from redis import Redis from .errors import APIError -password_hasher = PasswordHasher() +hash_slots = BoundedSemaphore(2) + + +class BoundedHasher(PasswordHasher): + def hash(self, password, **kwargs): + if not hash_slots.acquire(blocking=False): + raise APIError(429, 'rate_limited', 'Повторите попытку позже') + try: + return super().hash(password, **kwargs) + finally: + hash_slots.release() + + def verify(self, encoded, password): + if not hash_slots.acquire(blocking=False): + raise APIError(429, 'rate_limited', 'Повторите попытку позже') + try: + return super().verify(encoded, password) + finally: + hash_slots.release() + + +password_hasher = BoundedHasher(time_cost=2, memory_cost=19456, parallelism=1) dummy_hash = password_hasher.hash(secrets.token_urlsafe(32)) @@ -32,6 +54,7 @@ class Sessions: os.getenv('REDIS_URL', 'redis://redis:6379/0'), decode_responses=True, socket_connect_timeout=1, socket_timeout=1, max_connections=20, retry_on_timeout=False, + ssl_ca_certs='/run/identity/ca.crt', ssl_check_hostname=True, ) self.ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600')) if self.ttl < 1: @@ -66,3 +89,18 @@ class Sessions: sessions = Sessions() + + +def password_budget(subject): + """Atomic, shared fixed windows before any expensive hash (including registration).""" + digest = hashlib.sha256(subject.encode()).hexdigest() + allowed = sessions.client.eval(''' + local global = redis.call('INCR', KEYS[1]) + if global == 1 then redis.call('EXPIRE', KEYS[1], 1) end + local account = redis.call('INCR', KEYS[2]) + if account == 1 then redis.call('EXPIRE', KEYS[2], 10) end + if global > 32 or account > 8 then return 0 end + return 1 + ''', 2, 'login:global', 'login:' + digest) + if not allowed: + raise APIError(429, 'rate_limited', 'Повторите попытку позже') diff --git a/src/image_processor.py b/src/image_processor.py index 8533d88..fadf1b2 100644 --- a/src/image_processor.py +++ b/src/image_processor.py @@ -102,7 +102,7 @@ def main(): otel.setup(child=True) engine = create_db_engine() try: - with otel.span('image.process', context=otel.propagator.extract({ + with otel.span('image.process', context=otel.extract({ 'traceparent': os.getenv('TRACEPARENT', ''), 'tracestate': os.getenv('TRACESTATE', '')})): process(sessionmaker(engine, expire_on_commit=False), sys.argv[1], sys.argv[2]) otel.event('image_completed') diff --git a/src/jobs.py b/src/jobs.py index 0757b2c..315cf13 100644 --- a/src/jobs.py +++ b/src/jobs.py @@ -32,7 +32,9 @@ def now(): def broker(): return Redis.from_url(os.getenv('BROKER_URL', 'redis://broker:6379/0'), - decode_responses=True, socket_connect_timeout=2, socket_timeout=5) + decode_responses=True, socket_connect_timeout=2, socket_timeout=5, + ssl_ca_certs='/run/identity/ca.crt', ssl_check_hostname=True, + ssl_certfile='/run/identity/tls.crt', ssl_keyfile='/run/identity/tls.key') def ensure_group(client): @@ -83,7 +85,7 @@ def dispatch_once(sessions, client): continue if job.published_at is None: with otel.span('attachment-jobs publish', kind=otel.SpanKind.PRODUCER, - context=otel.propagator.extract(job.trace_context), attributes={ + context=otel.extract(job.trace_context), attributes={ 'messaging.system': 'redis', 'messaging.destination.name': STREAM, 'messaging.operation.type': 'publish', 'job.attempt': job.attempt + 1}): client.xadd(STREAM, {'job': json.dumps({**envelope(job), **otel.carrier()})}) diff --git a/src/object_storage.py b/src/object_storage.py index 924a837..f7d071e 100644 --- a/src/object_storage.py +++ b/src/object_storage.py @@ -16,6 +16,7 @@ def s3_client(): region_name=os.getenv('S3_REGION', 'us-east-1'), aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'], aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'], + verify='/run/identity/ca.crt', config=Config(connect_timeout=2, read_timeout=5, retries={'total_max_attempts': 1}, s3={'addressing_style': 'path'}, diff --git a/src/secure_run.py b/src/secure_run.py new file mode 100644 index 0000000..8898b49 --- /dev/null +++ b/src/secure_run.py @@ -0,0 +1,82 @@ +"""Cert-auth OpenBao supervisor. Secrets stay in memory; fail closed at lease expiry.""" +import json +import os +import signal +import subprocess +import sys +import time + +import requests + + +def main(): + role = os.environ['SERVICE_ROLE'] + client = requests.Session() + client.trust_env = False + client.verify = '/run/identity/ca.crt' + client.cert = ('/run/identity/tls.crt', '/run/identity/tls.key') + child = None + stopping = False + token = None + deadline = 0 + current = None + + def stop(*_): + nonlocal stopping + stopping = True + + def stop_child(): + nonlocal child + if child is not None: + if child.poll() is not None: + child = None + return + os.killpg(child.pid, signal.SIGTERM) + try: + child.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(child.pid, signal.SIGKILL) + child.wait() + child = None + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + while not stopping: + try: + # Fresh cert authentication bounds revocation; no permanent bootstrap password. + response = client.post('https://openbao:8200/v1/auth/cert/login', + json={'name': role}, timeout=3) + response.raise_for_status() + auth = response.json()['auth'] + token = auth['client_token'] + response = client.get(f'https://openbao:8200/v1/secret/data/{role}', + headers={'X-Vault-Token': token}, timeout=3) + response.raise_for_status() + config = response.json()['data']['data'] + deadline = time.monotonic() + min(auth['lease_duration'], 60) + if config != current: + stop_child() + current = config + if child is None: + child = subprocess.Popen(sys.argv[1:], env={**os.environ, **config}, start_new_session=True) + print('Service started with scoped secrets', flush=True) + # Each poll uses a new short lease; revoke the used token to avoid accumulation. + client.post('https://openbao:8200/v1/auth/token/revoke-self', + headers={'X-Vault-Token': token}, timeout=3) + except (requests.RequestException, KeyError, ValueError): + print('Secrets temporarily unavailable', flush=True) + if time.monotonic() >= deadline: + stop_child() + current = None + if child is not None and child.poll() is not None: + return child.returncode + for _ in range(10): + if stopping: + break + time.sleep(1) + stop_child() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/store.py b/src/store.py index b273f4c..f91c9ec 100644 --- a/src/store.py +++ b/src/store.py @@ -7,7 +7,7 @@ from uuid import UUID from sqlalchemy import select, tuple_, update from sqlalchemy.exc import IntegrityError -from .auth import password_hasher, verify_password, unauthorized +from .auth import password_hasher, verify_password, unauthorized, password_budget from .errors import APIError from .cache import history_cache from .models import User, Chat, ChatMember, Message, IdempotencyRecord, Attachment @@ -57,6 +57,7 @@ class PostgresStore: self.cache = cache def create_user(self, username, display_name, password): + password_budget(username) user = User(username=username, display_name=display_name, password_hash=password_hasher.hash(password)) try: with self.sessions.begin() as session: @@ -74,12 +75,18 @@ class PostgresStore: return serialize(session.get(User, ensure_uuid(user_id)), *USER_FIELDS) def login(self, username, password): + password_budget(username) with self.sessions() as session: user = session.scalar(select(User).where(User.username == username)) encoded = user.password_hash if user else None result = serialize(user, *USER_FIELDS) if not verify_password(encoded, password): raise unauthorized() + if password_hasher.check_needs_rehash(encoded): + replacement = password_hasher.hash(password) + with self.sessions.begin() as session: + session.execute(update(User).where(User.id == result['id'], User.password_hash == encoded) + .values(password_hash=replacement)) return result def create_chat(self, actor_id, title, member_ids): diff --git a/src/telemetry.py b/src/telemetry.py index bc285bf..7382ea0 100644 --- a/src/telemetry.py +++ b/src/telemetry.py @@ -136,6 +136,14 @@ def seed_http(routes): http_requests.add(0, {'method': method, 'route': route.path, 'status_class': status}) +def extract(carrier): + # Bound regex work in both HTTP headers and JSON broker carriers (CVE-2026-114603/126360). + bounded = {key: value for key, value in carrier.items() if isinstance(value, str) + and ((key == 'traceparent' and len(value) == 55) + or (key == 'tracestate' and len(value) <= 512))} + return propagator.extract(bounded) + + def carrier(): result = {} propagator.inject(result) @@ -174,11 +182,12 @@ class HttpTelemetry: if scope['type'] != 'http' or scope['path'].startswith('/health/'): return await self.app(scope, receive, send) headers = {k.decode('latin1'): v.decode('latin1') for k, v in scope['headers'] - if k in (b'traceparent', b'tracestate')} + if (k == b'traceparent' and len(v) == 55) + or (k == b'tracestate' and len(v) <= 512)} method = scope['method'] if scope['method'] in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'} else 'OTHER' status = 500 started = time.monotonic() - with span('HTTP ' + method, kind=SpanKind.SERVER, context=propagator.extract(headers)) as current: + with span('HTTP ' + method, kind=SpanKind.SERVER, context=extract(headers)) as current: async def response(message): nonlocal status if message['type'] == 'http.response.start': diff --git a/src/worker.py b/src/worker.py index 118c885..b28ce9b 100644 --- a/src/worker.py +++ b/src/worker.py @@ -26,7 +26,7 @@ def handle(sessions, client, message_id, fields): acknowledge(client, message_id) return with otel.span('attachment-jobs process', kind=otel.SpanKind.CONSUMER, - context=otel.propagator.extract(message), attributes={ + context=otel.extract(message), attributes={ 'messaging.system': 'redis', 'messaging.destination.name': STREAM, 'messaging.operation.type': 'process', 'job.attempt': message.get('attempt', 0)}): process_message(sessions, client, message_id, message) diff --git a/student-tests/internal.py b/student-tests/internal.py new file mode 100644 index 0000000..ebab6f5 --- /dev/null +++ b/student-tests/internal.py @@ -0,0 +1,185 @@ +"""Operator-only, real network negative tests; no credentials in result files.""" +import base64 +import hashlib +import json +import resource +from pathlib import Path +import socket +import ssl +import statistics +import sys +import time +import uuid + +import boto3 +from botocore.exceptions import ClientError +import psycopg +from redis import Redis +from redis.exceptions import ResponseError +import requests +from argon2 import PasswordHasher + +S=Path('/audit-secrets') +sys.path.insert(0, '/app') +CA=str(S/'ca.crt') +config=json.loads((S/'operator-private/credentials.json').read_text()) +results=[] + + +def record(name, condition=True, **details): + assert condition, name + results.append({'test':name,'passed':True,**details}) + print('PASS: '+name,flush=True) + + +def http(method,url,role=None,**kw): + client=requests.Session();client.trust_env=False + cert=(str(S/role/'tls.crt'),str(S/role/'tls.key')) if role else None + return client.request(method,url,verify=CA,cert=cert,timeout=8,**kw) + + +def tls(host,port,identity,body,hostname=None): + ctx=ssl.create_default_context(cafile=CA) + if identity: ctx.load_cert_chain(str(S/identity/'tls.crt'),str(S/identity/'tls.key')) + with socket.create_connection((host,port),timeout=3) as raw: + with ctx.wrap_socket(raw,server_hostname=hostname or host) as conn: + conn.sendall(body) + return conn.recv(8192) + + +def rejection(host,port,identity,body): + try: response=tls(host,port,identity,body) + except (ssl.SSLError,ConnectionResetError): response=b'' + # Timeouts/refused connections are NOT accepted as proof of authorization denial. + return not response + + +def db(role): + return psycopg.connect(host='postgres',dbname='messenger',user=role,password=config[role]['db'], + sslmode='verify-full',sslrootcert=CA,connect_timeout=3,autocommit=True) + + +def redis(role,broker=False): + return Redis(host='broker' if broker else 'redis',port=6380,username=role, + password=config[role]['broker' if broker else 'redis'],ssl=True,ssl_ca_certs=CA, + ssl_check_hostname=True,ssl_certfile=str(S/role/'tls.crt') if broker else None, + ssl_keyfile=str(S/role/'tls.key') if broker else None,decode_responses=True, + socket_timeout=3,socket_connect_timeout=3) + + +def main(): + from src.telemetry import extract, trace + start=time.perf_counter() + for _ in range(20): + extract({'traceparent':'00-'+' '*100000+'\n','tracestate':' '*100000+'x'}) + record('Oversized HTTP/JSON trace context has bounded parsing cost',time.perf_counter()-start<1) + context=extract({'traceparent':'00-'+'1'*32+'-'+'2'*16+'-01'}) + record('Valid trace context remains supported',trace.get_current_span(context).get_span_context().is_valid) + body=b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' + ingest=b'POST /v1/traces HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}' + matrix=[('api1',8443,'lb',body),('api2',8443,'lb',body), + ('broker',6380,'worker',b'*1\r\n$4\r\nPING\r\n'),('otel-collector',44318,'api',ingest)] + for host,port,allowed,payload in matrix: + record(host+' accepts allowed identity',bool(tls(host,port,allowed,payload))) + for forbidden in [None,'foreign-'+allowed,'outsider','expired-'+allowed]: + record(host+' rejects '+str(forbidden),rejection(host,port,forbidden,payload)) + if host.startswith('api') and (S/'old-lb/tls.crt').exists(): + record(host+' rejects revoked LB serial',rejection(host,port,'old-lb',payload)) + for role in ['worker','dispatcher']: + record('Collector accepts '+role,b'200' in tls('otel-collector',44318,role,ingest)) + for host,port in [('lb',8443),('redis',6380),('s3',9443),('grafana',3443),('openbao',8200)]: + ctx=ssl.create_default_context(cafile=CA) + with socket.create_connection((host,port),timeout=3) as raw: + with ctx.wrap_socket(raw,server_hostname=host) as conn: + record(host+' server TLS verified',True,protocol=conn.version()) + try: tls(host,port,None,b'GET / HTTP/1.0\r\n\r\n',hostname='wrong.invalid') + except ssl.SSLCertVerificationError: record(host+' rejects wrong hostname') + else: raise AssertionError('hostname accepted') + for host,port,local,role,path in [('prometheus',19090,9090,'grafana','/-/ready'), + ('loki',13100,3100,'grafana','/ready'),('tempo',13200,3200,'grafana','/ready'), + ('otel-collector',18889,8889,'prometheus','/metrics'),('otel-collector',18888,8888,'prometheus','/metrics'), + ('tempo',14318,4318,'otel-collector','/v1/traces')]: + payload=(f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n').encode() + record(f'{host}:{port} trusted identity',bool(tls(host,port,role,payload))) + record(f'{host}:{port} rejects outsider',rejection(host,port,'outsider',payload)) + for host,port in [('api1',8080),('api2',8080),('broker',6379),('redis',6379),('s3',9000), + ('otel-collector',4318),('otel-collector',8888),('otel-collector',8889), + ('prometheus',9090),('loki',3100),('loki',9095),('tempo',3200),('tempo',4318),('tempo',9095),('grafana',3000)]: + try: + with socket.create_connection((host,port),timeout=2): pass + except ConnectionRefusedError: record(f'No plaintext bypass {host}:{port}') + else: raise AssertionError('plaintext listener exposed') + for role in ['api','worker','dispatcher','cleanup']: + with db(role) as conn: + record('PostgreSQL TLS '+role,conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]) + try: conn.execute('CREATE TABLE forbidden_probe(id int)') + except psycopg.errors.InsufficientPrivilege: record('DB no DDL '+role) + else: raise AssertionError('DDL allowed') + if role!='api': + try: conn.execute('SELECT password_hash FROM users LIMIT 1') + except psycopg.errors.InsufficientPrivilege: record('DB password hashes denied '+role) + else: raise AssertionError('password hashes exposed') + auth=http('POST','https://openbao:8200/v1/auth/cert/login',role,json={'name':role}) + record('OpenBao cert auth '+role,auth.status_code==200) + token=auth.json()['auth']['client_token'];headers={'X-Vault-Token':token} + record('OpenBao short TTL '+role,0'},count=1))]: + client=redis(role,True);record('Broker authenticated '+role,client.ping()) + try:cmd(client) + except ResponseError as exc: record('Broker ACL denied '+role,'permissions' in str(exc).lower() or 'noperm' in str(exc).lower()) + else:raise AssertionError('broker command allowed') + for role,prefix in [('api','variants'),('worker','staging'),('cleanup','staging')]: + client=boto3.client('s3',endpoint_url='https://s3:9443',verify=CA, + aws_access_key_id=role,aws_secret_access_key=config[role]['s3'],region_name='us-east-1') + try:client.put_object(Bucket='messenger-attachments',Key=prefix+'/forbidden',Body=b'x') + except ClientError as exc:record('S3 denied write prefix '+role,exc.response['Error']['Code']=='AccessDenied') + else:raise AssertionError('S3 write allowed') + # Real rehash via the public API and a synthetic old Argon2id record. + username='rehash_'+uuid.uuid4().hex[:12];password='synthetic-'+uuid.uuid4().hex + old=PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(password) + user_id=str(uuid.uuid4()) + with db('api') as conn: + conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',(user_id,username,'Rehash test',old)) + response=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,password)) + record('Old Argon2 login succeeds',response.status_code==201) + token=response.json()['token'] + with db('api') as conn: + encoded=conn.execute('SELECT password_hash FROM users WHERE id=%s',(user_id,)).fetchone()[0] + record('Password rehashed',encoded.startswith('$argon2id$v=19$m=19456,t=2,p=1$')) + client=redis('api');key='session:'+hashlib.sha256(token.encode()).hexdigest() + stored=client.get(key) + record('Session stores digest key, no credential',stored is not None and token not in stored and password not in stored) + client.expire(key,1);time.sleep(1.1) + record('Expired session rejected',http('GET','https://lb:8443/api/v1/users/me',headers={'Authorization':'Bearer '+token}).status_code==401) + # Same account alternates replicas. Eight accepted attempts total, not per replica. + username='missing_'+uuid.uuid4().hex[:12];statuses=[];instances=set() + for _ in range(12): + r=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,'synthetic-password')) + statuses.append(r.status_code);instances.add(r.headers.get('X-Instance-Id')) + if r.status_code==429:record('Rate limit carries Retry-After',r.headers.get('Retry-After')=='1') + record('Rate limit shared across replicas',statuses.count(401)==8 and statuses.count(429)==4 and len(instances)==2,instances=len(instances),statuses=statuses) + samples=[];hasher=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1) + hasher.verify(encoded,password) # One warmup; sequential measurements, no HTTP load. + wall_start=time.perf_counter();cpu_start=time.process_time() + for _ in range(20): + start=time.perf_counter();hasher.verify(encoded,password);samples.append(time.perf_counter()-start) + record('Measured Argon2 budget',True,memory_kib=19456,time_cost=2,parallelism=1, + median_ms=round(statistics.median(samples)*1000,2),p95_ms=round(sorted(samples)[18]*1000,2), + p99_ms=round(max(samples)*1000,2),samples_ms=[round(s*1000,3) for s in samples], + duration_seconds=round(time.perf_counter()-wall_start,3), + cpu_seconds=round(time.process_time()-cpu_start,3), + process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + global_limit_per_second=32,account_limit_per_10seconds=8,hash_concurrency_per_api=2) + # Every secret is checked as a value, but never serialized in evidence. + (Path('/evidence')/'internal.json').write_text(json.dumps({'checks':results},indent=2)) + print(f'PASS: {len(results)} internal checks') + + +if __name__=='__main__':main() diff --git a/student-tests/lifecycle.py b/student-tests/lifecycle.py new file mode 100644 index 0000000..53c78c1 --- /dev/null +++ b/student-tests/lifecycle.py @@ -0,0 +1,127 @@ +"""Operator-driven lifecycle tests. Synthetic data; volumes are never deleted.""" +import hashlib +import json +import sys +import time +from pathlib import Path + +ROOT=Path(__file__).resolve().parents[1] +sys.path[:0]=[str(ROOT),str(ROOT/'tests')] +from scripts import lab7 as op +from client import Client + + +def main(): + evidence=ROOT/'evidence';evidence.mkdir(exist_ok=True) + checks=[] + def ok(name,condition=True,**details): + assert condition,name + checks.append({'test':name,'passed':True,**details});print('PASS: '+name,flush=True) + (evidence/'lifecycle.json').write_text(json.dumps(checks,indent=2),encoding='utf-8') + def audit(code): + return op.compose('run','--rm','--no-deps','-T','audit','-',data=code).stdout + def ready(): + try:return c.call('GET','/health/ready',schema='Health')['status']==200 + except Exception:return False + def saved(): + c.call('GET','/api/v1/users/me',actor=alice,schema='User') + history=c.call('GET',f"/api/v1/chats/{chat['id']}/messages?limit=100",actor=bob,schema='MessagePage')['json']['items'] + assert original in history + content=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content",actor=bob)['bytes'] + assert content==blob + thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes'] + assert thumbnail==original_thumbnail + c=Client('https://127.0.0.1:8443',str(ROOT/'secrets/ca.crt'),timeout=5) + alice,bob,eve,chat=c.bootstrap() + canary='private-message-'+hashlib.sha256(alice['token'].encode()).hexdigest() + original=c.message(alice,chat,canary)['json'] + attachment,blob=c.attachment(alice,chat);c.wait_ready(alice,attachment) + original_thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes'] + foreign=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other chat','member_ids':[eve['id']]},schema='Chat')['json'] + c.call('POST',f"/api/v1/chats/{foreign['id']}/messages",404,actor=eve, + body={'text':'','attachment_ids':[attachment['id']]},headers={'Idempotency-Key':'cross-chat-probe'}) + ok('Cannot attach another chat file') + c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'}) + ok('Request size is bounded') + ids={name:op.compose('exec','-T',name,'hostname').stdout.strip() for name in ['api1','api2']} + for target in ['api1','api2']: + op.compose('stop',target) + start=time.monotonic() + try: + successes=0;failures=0 + while successes<5: + try: + response=c.call('GET','/api/v1/users/me',actor=alice) + assert response['headers']['X-Instance-Id']!=ids[target] + successes+=1 + except Exception: + failures+=1;successes=0 + assert time.monotonic()-start<10,'failover did not recover within 10s' + saved() + ok('Replica failover '+target,recovery_seconds=round(time.monotonic()-start,2),failed_attempts=failures) + finally: + op.compose('start',target);op.compose('restart',target+'-tls') + time.sleep(12) + # Restart the complete stack, including sealed persistent OpenBao. + op.restart_stack() + op.wait_service(ready,90);saved() + ok('Full restart preserves sessions, messages, original and processed attachment') + old=json.loads((op.PRIVATE/'credentials.json').read_text())['api']['db'] + image_before=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip() + op.rotate_secret();time.sleep(12);op.wait_service(ready,30) + code="""import psycopg +try: + psycopg.connect(host='postgres',dbname='messenger',user='api',password=OLD,sslmode='verify-full',sslrootcert='/audit-secrets/ca.crt',connect_timeout=3) +except psycopg.OperationalError as e: + assert 'password authentication failed' in str(e) + print('old DB password rejected') +else:raise AssertionError('old DB password accepted') +""".replace('password=OLD','password='+repr(old)) + audit(code);saved();ok('Working DB secret rotated; old password rejected on new connection') + op.rotate_leaf();op.wait_service(ready,30);saved() + output=op.compose('run','--rm','--no-deps','audit','/audit/internal.py').stdout + (evidence/'internal.txt').write_text(output,encoding='utf-8') + ok('Leaf rotated and old LB identity revoked on both replicas') + image_after=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip() + ok('Rotations do not rebuild image',image_before==image_after,image=image_after) + # Obtain a real scoped token, let it expire, then demonstrate sealed fail-closed. + auth=op.bao('POST','auth/cert/login',{'name':'api'},role='api')['auth'] + started=time.monotonic() + time.sleep(auth['lease_duration']+2) + try:op.bao('GET','secret/data/api',token=auth['client_token'],role='api') + except RuntimeError as exc:ok('Expired OpenBao token denied','HTTP 403' in str(exc)) + else:raise AssertionError('expired token accepted') + admin=json.loads((op.PRIVATE/'bao-init.json').read_text())['root_token'] + op.bao('PUT','sys/seal',token=admin) + started=time.monotonic() + try: + time.sleep(70) + ok('Sealed OpenBao stops API within bounded secret cache',not ready(),elapsed_seconds=round(time.monotonic()-started,2)) + for name in ['worker','dispatcher','cleanup']: + code="import pathlib; x=[p.read_bytes() for p in pathlib.Path('/proc').glob('[0-9]*/cmdline')]; assert not any(b'python\\x00-m\\x00src.' in v and b'src.secure_run' not in v for v in x)" + op.compose('exec','-T',name,'python','-c',code) + ok('Sealed OpenBao stops background consumers too') + finally: + op.unseal() + op.wait_service(ready,45);saved();ok('Unseal recovers without baked-in fallback secret') + # Public API errors and telemetry must not contain actual secrets or canaries. + credentials=json.loads((op.PRIVATE/'credentials.json').read_text()) + values=[v for role in credentials.values() for v in role.values()] + values += [alice['token'],alice['registration']['password'],canary] + logs=op.compose('logs','--no-color','--since','30m','api1','api2','worker','dispatcher','cleanup','otel-collector','loki','tempo').stdout + ok('Container logs do not expose credentials or private message',not any(v in logs for v in values)) + telemetry_code="import sys; sys.path.insert(0,'/audit'); from telemetry import check; check("+repr(values)+")" + print(audit(telemetry_code),flush=True);ok('Live metrics/logs/traces have no credential leaks; datasource writes denied') + deployed=json.loads(op.compose('config','--format','json').stdout)['services'] + for name,spec in deployed.items(): + assert spec['read_only'] and 'ALL' in spec['cap_drop'] and 'no-new-privileges:true' in spec['security_opt'] + assert spec.get('mem_limit') and spec.get('cpus') + ok('All services have read_only, no-new-privileges, cap_drop and limits') + hardware=json.loads(op.docker('info','--format','{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"os":{{json .OperatingSystem}},"architecture":{{json .Architecture}}}').stdout) + hardware['app_image']=image_after + hardware['services']={name:{key:spec.get(key) for key in ['image','cpus','mem_limit','user','read_only','cap_drop','cap_add','security_opt']} for name,spec in deployed.items()} + (evidence/'environment.json').write_text(json.dumps(hardware,indent=2),encoding='utf-8') + ok('Complete lifecycle suite') + + +if __name__=='__main__':main() diff --git a/student-tests/telemetry.py b/student-tests/telemetry.py new file mode 100644 index 0000000..fe3abb0 --- /dev/null +++ b/student-tests/telemetry.py @@ -0,0 +1,47 @@ +"""Verify live encrypted telemetry paths and inspect content without printing it.""" +import json +import time +from pathlib import Path +from internal import http, config, S + + +def check(needles=()): + deadline=time.monotonic()+30 + while True: + bodies=[] + for url,params in [ + ('https://prometheus:19090/api/v1/query',{'query':'http_requests_total'}), + ('https://loki:13100/loki/api/v1/query_range',{'query':'{service_name=~"messenger-.*"}','limit':1000}), + ('https://tempo:13200/api/search',{'limit':100})]: + r=http('GET',url,'operator',params=params) + assert r.status_code==200, f'{url}: HTTP {r.status_code}' + bodies.append(r.text) + metrics=json.loads(bodies[0])['data']['result'] + logs=json.loads(bodies[1])['data']['result'] + traces=json.loads(bodies[2]).get('traces',[]) + if (metrics and logs and traces) or time.monotonic()>=deadline: break + time.sleep(1) + assert metrics and logs and traces, f'Signal counts: metrics={len(metrics)}, logs={len(logs)}, traces={len(traces)}' + for trace in traces[:20]: + r=http('GET','https://tempo:13200/api/traces/'+trace['traceID'],'operator') + assert r.status_code==200 + bodies.append(r.text) + values=list(needles)+[v for role in config.values() for v in role.values()] + assert not any(value in body for value in values for body in bodies),'Telemetry credential/private-message leak' + for host,port,path in [('loki',13100,'/otlp/v1/logs'),('prometheus',19090,'/api/v1/write'),('tempo',13200,'/anything')]: + assert http('POST',f'https://{host}:{port}{path}','grafana',json={}).status_code==403 + password=(S/'grafana-admin/password').read_text() + for name in ['prometheus','loki','tempo']: + path=(f'/api/datasources/uid/{name}/health' if name!='tempo' + else '/api/datasources/proxy/uid/tempo/api/search?limit=1') + response=http('GET','https://grafana:3443'+path, + auth=('admin',password)) + assert response.status_code==200, f'Grafana datasource {name}: HTTP {response.status_code}' + result={'metric_series':len(metrics),'log_streams':len(logs),'trace_results':len(traces), + 'checked_trace_bodies':min(20,len(traces)),'credential_canaries_absent':True, + 'grafana_write_denied':True,'grafana_datasource_health':True} + Path('/evidence/telemetry.json').write_text(json.dumps(result,indent=2)) + print('PASS: live metrics/logs/traces; no credential/message leaks; Grafana read-only TLS sources') + + +if __name__=='__main__':check() -- 2.54.0