diff --git a/.env.example b/.env.example index 2e9f054..bd3289b 100644 --- a/.env.example +++ b/.env.example @@ -1,41 +1,104 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Copy to .env for a local synthetic environment. Never commit .env. 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 + +# Public traffic terminates as HTTPS at nginx. Generate the certificate and +# private key locally with scripts/bootstrap-tls.*; never add secrets/ to Git. +PUBLIC_BIND_ADDRESS=127.0.0.1 +PUBLIC_HTTPS_PORT=8443 +PUBLIC_BASE_URL=https://localhost:8443 + +DATABASE_NAME=messenger +DATABASE_USER=messenger +DATABASE_PASSWORD=replace-with-a-long-random-database-password +DATABASE_API_PASSWORD=replace-with-a-different-api-database-password +DATABASE_WORKER_PASSWORD=replace-with-a-different-worker-database-password +DATABASE_MIGRATION_PASSWORD=replace-with-a-different-migration-database-password + +RABBITMQ_USER=messenger +RABBITMQ_PASSWORD=replace-with-a-long-random-rabbitmq-password +RABBITMQ_ADMIN_USER=operator +RABBITMQ_ADMIN_PASSWORD=replace-with-a-long-random-rabbitmq-admin-password +RABBITMQ_API_PASSWORD=replace-with-a-different-rabbitmq-api-password +RABBITMQ_WORKER_PASSWORD=replace-with-a-different-rabbitmq-worker-password +RABBITMQ_VHOST=/ +ATTACHMENT_JOB_EXCHANGE=attachments.v1 +ATTACHMENT_JOB_QUEUE=attachments.process.level4.v1 +ATTACHMENT_JOB_ROUTING_KEY=attachment.process.v1 +ATTACHMENT_DLQ_EXCHANGE=attachments.dlx.v1 +ATTACHMENT_DLQ_QUEUE=attachments.failed.v1 +ATTACHMENT_DLQ_ROUTING_KEY=attachment.failed.v1 +ATTACHMENT_PIPELINE_VERSION=2 +WORKER_CONCURRENCY=2 +WORKER_PREFETCH=1 +JOB_MAX_ATTEMPTS=5 +JOB_RETRY_BASE_DELAY=1s +JOB_RETRY_MAX_DELAY=30s +JOB_TIMEOUT=60s +JOB_LEASE_DURATION=90s +JOB_LEASE_REAPER_INTERVAL=5s +WORKER_MAX_IMAGE_PIXELS=40000000 +WORKER_MEMORY_BUDGET_BYTES=536870912 +WORKER_MEMORY_WAIT=2s + +# Fault injection is opt-in and intended only for an isolated test stand. +FAULT_CRASH_AFTER_OUTBOX_COMMIT=false +FAULT_CRASH_BEFORE_SIDE_EFFECT=false +FAULT_CRASH_AFTER_SIDE_EFFECT=false +FAULT_CRASH_AFTER_RESULT_COMMIT=false + 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. +S3_ACCESS_KEY_ID=messenger-api +S3_SECRET_ACCESS_KEY=replace-with-a-long-random-api-secret +S3_WORKER_ACCESS_KEY_ID=messenger-worker +S3_WORKER_SECRET_ACCESS_KEY=replace-with-a-different-long-random-worker-secret +MINIO_ROOT_USER=minio-root +MINIO_ROOT_PASSWORD=replace-with-a-different-long-random-root-secret +REDIS_API_PASSWORD=replace-with-a-long-random-redis-api-password +REDIS_WORKER_PASSWORD=replace-with-a-different-random-redis-worker-password + +SESSION_TTL_SECONDS=3600 +SESSION_MAXIMUM_ACTIVE=3 +# Shared Redis-backed login guard across all API replicas. +LOGIN_ATTEMPTS_PER_USERNAME=5 +LOGIN_ATTEMPTS_PER_SOURCE=100 +LOGIN_RATE_WINDOW_SECONDS=60 ARGON2_MEMORY_KIB=19456 ARGON2_ITERATIONS=2 ARGON2_PARALLELISM=1 +IDEMPOTENCY_TTL_SECONDS=86400 +MAX_UPLOAD_BYTES=10485760 +MAX_IMAGE_PIXELS=40000000 +MAX_CONCURRENT_UPLOADS=3 +UPLOAD_PERMIT_WAIT_MILLIS=10000 + +# Staging objects are deleted only after the final result is committed. +# A separate lifecycle/cleanup policy may remove abandoned staging objects +# after this retention interval; it must never remove active jobs. +STAGING_RETENTION_SECONDS=86400 +ATTACHMENT_CLEANUP_GRACE_SECONDS=3600 +ATTACHMENT_CLEANUP_DRY_RUN=false +ATTACHMENT_RECONCILE_INTERVAL_MILLIS=600000 +ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS=60000 + +# Observability (lab6). The worker must set a distinct OTEL_SERVICE_NAME. +OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 +OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf +OTEL_TRACES_SAMPLER=parentbased_traceidratio +# Balanced lab profile: keep 25% of complete parent-based traces; keep all logs/metrics. +OTEL_TRACES_SAMPLER_ARG=0.25 +OTEL_METRIC_EXPORT_INTERVAL=30000 +OTEL_BSP_MAX_QUEUE_SIZE=2048 +OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512 +OTEL_BSP_EXPORT_TIMEOUT=5000 +OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT=256 +OBSERVABILITY_QUEUE_POLL_INTERVAL=5s + +GRAFANA_PORT=3000 +GRAFANA_ADMIN_USER=admin +GRAFANA_ADMIN_PASSWORD=replace-with-a-long-random-grafana-password +PROMETHEUS_PORT=9090 +LOKI_PORT=3100 +TEMPO_PORT=3200 diff --git a/.gitignore b/.gitignore index b5a7189..556778d 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ volumes/ data/ backups/ # Runtime/build artifacts +.gradle/ .venv/ __pycache__/ *.py[cod] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b59be4c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,43 @@ +# Stage 1: Build +FROM eclipse-temurin:23-jdk AS build + +WORKDIR /app + +COPY gradlew . +COPY gradle gradle +COPY build.gradle settings.gradle ./ + +COPY src src + +RUN --mount=type=cache,target=/root/.gradle \ + chmod +x gradlew && ./gradlew bootJar --no-daemon + + +# Stage 2: Runtime +FROM eclipse-temurin:23-jre + +WORKDIR /app + +COPY --from=build /app/build/libs/*.jar app.jar + +ARG OTEL_JAVA_AGENT_VERSION=2.33.1 + +RUN apt-get update \ + && apt-get install --yes --no-install-recommends curl \ + && curl --fail --location --silent --show-error \ + "https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v${OTEL_JAVA_AGENT_VERSION}/opentelemetry-javaagent.jar" \ + --output /opt/opentelemetry-javaagent.jar \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --create-home messenger + +COPY --chmod=0755 infra/otel/docker-entrypoint.sh /usr/local/bin/messenger-entrypoint + +USER messenger + +EXPOSE 8080 + +STOPSIGNAL SIGTERM + +HEALTHCHECK NONE + +ENTRYPOINT ["messenger-entrypoint"] diff --git a/Makefile b/Makefile index 5ad43ad..c7460da 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover test-security +.PHONY: help check validate test load test-persistence test-failover test-security test-mtls help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -31,3 +31,6 @@ test-failover: test-security: $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-mtls: + powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-mtls.ps1 diff --git a/README.md b/README.md index b329f91..9105eac 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,33 @@ ## Как начать и проверить +Перенесённое приложение lab6 собирается из `src/` и доступно только через +HTTPS-ingress. Перед первым запуском создайте локальные ключи (каталог +`secrets/` игнорируется Git): + +```powershell +.\scripts\bootstrap-secrets.ps1 +.\scripts\bootstrap-pki.ps1 +docker compose --env-file .env up -d openbao +# Один раз: operator init; при каждом старте: ручной unseal двумя долями. +# Затем временно задайте BAO_TOKEN и выполните bootstrap политик/AppRole: +.\scripts\bootstrap-openbao.ps1 +docker compose --env-file .env up -d --build --scale api=2 +make test CA_FILE=$PWD/secrets/pki/public-ca/ca.crt +``` + +`bootstrap-pki.ps1` создаёт отдельные public/service/client CA и leaf identities +для ingress, LB, API, workload-клиентов и зависимостей. Приватные ключи и +готовые credentials в репозиторий не поставляются. LB→API, API/worker→Collector, +RabbitMQ, Redis и telemetry backends используют mTLS с раздельными identities; +PostgreSQL и MinIO принимают только проверяемый TLS, а runtime-роли получают +разные credentials по матрице доверия. + +Полная безопасная последовательность `init`/`unseal`, правила хранения root +token и долей, ротация SecretID и policy allow/deny test описаны в +[`infra/openbao/README.md`](infra/openbao/README.md). Root token задаётся только +в окружении текущего процесса оператора на время bootstrap и сразу удаляется. + ```sh # Работает прямо в skeleton, Python 3.9+; приложение не запускается: make check diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..a45c46b --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(23) + } +} + +repositories { + mavenCentral() +} + +dependencies { +// implementation 'org.springframework.boot:spring-boot-starter-data-jpa' +// implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + implementation 'org.springframework.boot:spring-boot-starter-amqp' + implementation 'org.springframework.boot:spring-boot-flyway' + implementation 'org.flywaydb:flyway-core' + implementation 'org.flywaydb:flyway-database-postgresql' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.bouncycastle:bcprov-jdk18on:1.84' + implementation 'org.apache.commons:commons-pool2' + implementation 'io.minio:minio:8.6.0' + implementation 'net.coobird:thumbnailator:0.4.20' + implementation 'org.sejda.imageio:webp-imageio:0.1.6' + // The runtime SDK is supplied by the pinned OpenTelemetry Java agent. + // The API dependency keeps custom business metrics vendor-neutral. + implementation 'io.opentelemetry:opentelemetry-api:1.67.0' + runtimeOnly 'org.postgresql:postgresql' + + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.3' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + annotationProcessor 'org.projectlombok:lombok' +// testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' +// testImplementation 'org.springframework.boot:spring-boot-starter-security-test' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' + + implementation("com.github.f4b6a3:uuid-creator:6.1.1") + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..b1c40a8 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,598 @@ +name: hla-lab7 + +x-api-environment: &api-environment + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_TRACES_EXPORTER: otlp + OTEL_METRICS_EXPORTER: otlp + OTEL_LOGS_EXPORTER: otlp + OTEL_PROPAGATORS: tracecontext,baggage + OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} + OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_traceidratio} + OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-0.25} + OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-30000} + OTEL_BSP_MAX_QUEUE_SIZE: ${OTEL_BSP_MAX_QUEUE_SIZE:-2048} + OTEL_BSP_MAX_EXPORT_BATCH_SIZE: ${OTEL_BSP_MAX_EXPORT_BATCH_SIZE:-512} + OTEL_BSP_EXPORT_TIMEOUT: ${OTEL_BSP_EXPORT_TIMEOUT:-5000} + OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: ${OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:-256} + OTEL_RESOURCE_ATTRIBUTES: service.version=0.0.1,deployment.environment.name=${APP_ENV:-lab} + SERVICE_TLS_CA: /run/pki/service-ca/ca.crt + OTEL_INSTRUMENTATION_LOGBACK_APPENDER_EXPERIMENTAL_MDC_ATTRIBUTES_INCLUDED: request_id + OTEL_INSTRUMENTATION_COMMON_LOGGING_STRUCTURED_ATTRIBUTES_INCLUDED: event,job.type,outcome,attempt,error.code,http.request.method,http.route,http.response.status_code + OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_REQUEST_HEADERS: "" + OTEL_INSTRUMENTATION_HTTP_SERVER_CAPTURE_RESPONSE_HEADERS: "" + DATABASE_URL: jdbc:postgresql://postgres:5432/${DATABASE_NAME:-messenger}?sslmode=verify-full&sslrootcert=/run/pki/service-ca/ca.crt + DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10} + DATABASE_MIN_IDLE: ${DATABASE_MIN_IDLE:-2} + DATABASE_QUERY_TIMEOUT_SECONDS: ${DATABASE_QUERY_TIMEOUT_SECONDS:-5} + DATABASE_TRANSACTION_TIMEOUT_SECONDS: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:-5} + REDIS_HOST: redis + REDIS_PORT: 6379 + REDIS_SSL_ENABLED: "true" + REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-1s} + REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-500ms} + REDIS_POOL_MAX_ACTIVE: ${REDIS_POOL_MAX_ACTIVE:-8} + REDIS_POOL_MAX_IDLE: ${REDIS_POOL_MAX_IDLE:-8} + REDIS_POOL_MIN_IDLE: ${REDIS_POOL_MIN_IDLE:-0} + REDIS_POOL_MAX_WAIT: ${REDIS_POOL_MAX_WAIT:-500ms} + USER_CACHE_TTL_SECONDS: ${USER_CACHE_TTL_SECONDS:-300} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_MAXIMUM_ACTIVE: ${SESSION_MAXIMUM_ACTIVE:-3} + LOGIN_ATTEMPTS_PER_USERNAME: ${LOGIN_ATTEMPTS_PER_USERNAME:-5} + LOGIN_ATTEMPTS_PER_SOURCE: ${LOGIN_ATTEMPTS_PER_SOURCE:-100} + LOGIN_RATE_WINDOW_SECONDS: ${LOGIN_RATE_WINDOW_SECONDS:-60} + ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456} + ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2} + ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + S3_ENDPOINT: https://minio:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + MAX_CONCURRENT_UPLOADS: ${MAX_CONCURRENT_UPLOADS:-3} + UPLOAD_PERMIT_WAIT_MILLIS: ${UPLOAD_PERMIT_WAIT_MILLIS:-10000} + RABBITMQ_HOST: rabbitmq + RABBITMQ_PORT: 5671 + RABBITMQ_SSL_ENABLED: "true" + RABBITMQ_VHOST: ${RABBITMQ_VHOST:-/} + ATTACHMENT_JOB_EXCHANGE: ${ATTACHMENT_JOB_EXCHANGE:-attachments.v1} + ATTACHMENT_JOB_QUEUE: ${ATTACHMENT_JOB_QUEUE:-attachments.process.level4.v1} + ATTACHMENT_JOB_ROUTING_KEY: ${ATTACHMENT_JOB_ROUTING_KEY:-attachment.process.v1} + ATTACHMENT_DLQ_EXCHANGE: ${ATTACHMENT_DLQ_EXCHANGE:-attachments.dlx.v1} + ATTACHMENT_DLQ_QUEUE: ${ATTACHMENT_DLQ_QUEUE:-attachments.failed.v1} + ATTACHMENT_DLQ_ROUTING_KEY: ${ATTACHMENT_DLQ_ROUTING_KEY:-attachment.failed.v1} + ATTACHMENT_PIPELINE_VERSION: ${ATTACHMENT_PIPELINE_VERSION:-2} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + WORKER_PREFETCH: ${WORKER_PREFETCH:-1} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_RETRY_BASE_DELAY: ${JOB_RETRY_BASE_DELAY:-1s} + JOB_RETRY_MAX_DELAY: ${JOB_RETRY_MAX_DELAY:-30s} + JOB_TIMEOUT: ${JOB_TIMEOUT:-60s} + JOB_LEASE_DURATION: ${JOB_LEASE_DURATION:-90s} + JOB_LEASE_REAPER_INTERVAL: ${JOB_LEASE_REAPER_INTERVAL:-5s} + WORKER_MAX_IMAGE_PIXELS: ${WORKER_MAX_IMAGE_PIXELS:-40000000} + WORKER_MEMORY_BUDGET_BYTES: ${WORKER_MEMORY_BUDGET_BYTES:-536870912} + WORKER_MEMORY_WAIT: ${WORKER_MEMORY_WAIT:-2s} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + ATTACHMENT_CLEANUP_GRACE_SECONDS: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:-3600} + ATTACHMENT_CLEANUP_DRY_RUN: ${ATTACHMENT_CLEANUP_DRY_RUN:-false} + ATTACHMENT_RECONCILE_INTERVAL_MILLIS: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:-600000} + ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:-60000} + +services: + openbao: + image: ghcr.io/openbao/openbao:2.7.3 + command: ["server", "-config=/openbao/config/openbao.hcl"] + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /run/pki/service-ca/ca.crt + ports: + - "127.0.0.1:${OPENBAO_PORT:-8200}:8200" + volumes: + - openbao-data:/openbao/data + - ./infra/openbao:/openbao/config:ro + - ./secrets/pki:/run/pki:ro + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "bao status >/dev/null 2>&1; code=$$?; test $$code -eq 0 -o $$code -eq 2"] + interval: 5s + timeout: 3s + retries: 30 + networks: [backend] + + openbao-agent-api: + image: ghcr.io/openbao/openbao:2.7.3 + user: "0:0" + command: ["agent", "-config=/openbao/config/agent.hcl"] + depends_on: + openbao: + condition: service_started + volumes: + - ./infra/openbao/agent-api.hcl:/openbao/config/agent.hcl:ro + - ./secrets/pki:/run/pki:ro + - ./secrets/openbao/api:/run/bootstrap:ro + - api-runtime-secrets:/run/rendered + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + restart: unless-stopped + networks: [backend] + + openbao-agent-worker: + image: ghcr.io/openbao/openbao:2.7.3 + user: "0:0" + command: ["agent", "-config=/openbao/config/agent.hcl"] + depends_on: + openbao: + condition: service_started + volumes: + - ./infra/openbao/agent-worker.hcl:/openbao/config/agent.hcl:ro + - ./secrets/pki:/run/pki:ro + - ./secrets/openbao/worker:/run/bootstrap:ro + - worker-runtime-secrets:/run/rendered + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + restart: unless-stopped + networks: [backend] + + postgres: + image: postgres:16.4-bookworm + environment: + POSTGRES_DB: ${DATABASE_NAME:-messenger} + POSTGRES_USER: ${DATABASE_USER:-messenger} + POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env} + DATABASE_API_PASSWORD: ${DATABASE_API_PASSWORD:?Set DATABASE_API_PASSWORD in .env} + DATABASE_WORKER_PASSWORD: ${DATABASE_WORKER_PASSWORD:?Set DATABASE_WORKER_PASSWORD in .env} + DATABASE_MIGRATION_PASSWORD: ${DATABASE_MIGRATION_PASSWORD:?Set DATABASE_MIGRATION_PASSWORD in .env} + volumes: + - postgres-data:/var/lib/postgresql/data + - ./secrets/pki:/run/pki:ro + - ./infra/postgres/entrypoint-tls.sh:/usr/local/bin/entrypoint-tls:ro + - ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro + - ./infra/postgres/01-roles.sh:/docker-entrypoint-initdb.d/01-roles.sh:ro + entrypoint: ["/bin/sh", "/usr/local/bin/entrypoint-tls"] + healthcheck: + test: ["CMD-SHELL", "PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/service-ca/ca.crt pg_isready -h postgres -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + cpus: 1.0 + mem_limit: 768m + networks: [backend] + + redis: + image: redis:7.4-bookworm + environment: + REDIS_API_PASSWORD: ${REDIS_API_PASSWORD:?Set REDIS_API_PASSWORD in .env} + REDIS_WORKER_PASSWORD: ${REDIS_WORKER_PASSWORD:?Set REDIS_WORKER_PASSWORD in .env} + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + umask 077 + printf 'user default off\nuser messenger-api on >%s ~* +@all -@admin -flushall -flushdb\nuser messenger-worker on >%s ~* +@all -@admin -flushall -flushdb\n' "$$REDIS_API_PASSWORD" "$$REDIS_WORKER_PASSWORD" >/tmp/users.acl + exec redis-server --port 0 --tls-port 6379 --tls-cert-file /run/pki/redis/tls.crt --tls-key-file /run/pki/redis/tls.key --tls-ca-cert-file /run/pki/workload-client-ca/ca.crt --tls-auth-clients yes --aclfile /tmp/users.acl --appendonly yes --appendfsync everysec + volumes: + - redis-data:/data + - ./secrets/pki:/run/pki:ro + healthcheck: + test: ["CMD-SHELL", "redis-cli --tls --cacert /run/pki/service-ca/ca.crt --cert /run/pki/api-client/tls.crt --key /run/pki/api-client/tls.key --user messenger-api --pass \"$$REDIS_API_PASSWORD\" ping | grep PONG"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + cpus: 0.25 + mem_limit: 256m + networks: [backend] + + rabbitmq: + image: rabbitmq:4.1.4-management-alpine + environment: + RABBITMQ_DEFAULT_USER: ${RABBITMQ_ADMIN_USER:-operator} + RABBITMQ_DEFAULT_PASS: ${RABBITMQ_ADMIN_PASSWORD:?Set RABBITMQ_ADMIN_PASSWORD in .env} + RABBITMQ_DEFAULT_VHOST: ${RABBITMQ_VHOST:-/} + RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "+S 2:2" + volumes: + - rabbitmq-data:/var/lib/rabbitmq + - ./secrets/pki:/run/pki:ro + - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 10s + timeout: 10s + start_period: 60s + retries: 12 + restart: unless-stopped + cpus: 0.5 + mem_limit: 1024m + networks: [backend] + + rabbitmq-init: + image: curlimages/curl:8.12.1 + depends_on: + rabbitmq: + condition: service_healthy + environment: + ADMIN_USER: ${RABBITMQ_ADMIN_USER:-operator} + ADMIN_PASSWORD: ${RABBITMQ_ADMIN_PASSWORD:?Set RABBITMQ_ADMIN_PASSWORD in .env} + API_PASSWORD: ${RABBITMQ_API_PASSWORD:?Set RABBITMQ_API_PASSWORD in .env} + WORKER_PASSWORD: ${RABBITMQ_WORKER_PASSWORD:?Set RABBITMQ_WORKER_PASSWORD in .env} + volumes: + - ./secrets/pki/service-ca/ca.crt:/run/ca.crt:ro + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + base=https://rabbitmq:15671/api + auth="$$ADMIN_USER:$$ADMIN_PASSWORD" + curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/users/messenger-api" -d "{\"password\":\"$$API_PASSWORD\",\"tags\":\"\"}" + curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/users/messenger-worker" -d "{\"password\":\"$$WORKER_PASSWORD\",\"tags\":\"\"}" + curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/permissions/%2F/messenger-api" -d '{"configure":"^attachments\\..*","write":"^attachments\\..*","read":"^$"}' + curl --fail --silent --show-error --cacert /run/ca.crt -u "$$auth" -H content-type:application/json -X PUT "$$base/permissions/%2F/messenger-worker" -d '{"configure":"^attachments\\..*","write":"^attachments\\..*","read":"^attachments\\..*"}' + restart: "no" + networks: [backend] + + minio: + image: bitnamilegacy/minio:2025.4.22-debian-12-r1@sha256:d7cd0e172c4cc0870f4bdc3142018e2a37be9acf04d68f386600daad427e0cab + 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_SCHEME: https + MINIO_CERTS_DIR: /certs + volumes: + - minio-data:/bitnami/minio/data + - ./secrets/pki/minio/tls.crt:/certs/public.crt:ro + - ./secrets/pki/minio/tls.key:/certs/private.key:ro + - ./secrets/pki/service-ca/ca.crt:/certs/CAs/ca.crt:ro + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "--cacert", "/certs/CAs/ca.crt", "https://minio:9000/minio/health/live"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + cpus: 0.75 + mem_limit: 512m + networks: [backend] + + minio-init: + image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc + depends_on: + minio: + condition: service_healthy + 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_BUCKET: ${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} + S3_WORKER_ACCESS_KEY_ID: ${S3_WORKER_ACCESS_KEY_ID:?Set S3_WORKER_ACCESS_KEY_ID in .env} + S3_WORKER_SECRET_ACCESS_KEY: ${S3_WORKER_SECRET_ACCESS_KEY:?Set S3_WORKER_SECRET_ACCESS_KEY in .env} + volumes: + - ./infra/minio-api-policy.json:/policy/minio-api-policy.json:ro + - ./secrets/pki/service-ca/ca.crt:/root/.mc/certs/CAs/service-ca.crt:ro + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + sed "s/__S3_BUCKET__/$$S3_BUCKET/g" /policy/minio-api-policy.json > /tmp/minio-api-policy.json + attempt=0 + until mc alias set local https://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" \ + && mc mb --ignore-existing "local/$$S3_BUCKET" \ + && mc anonymous set none "local/$$S3_BUCKET" \ + && (mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" \ + || mc admin user info local "$$S3_ACCESS_KEY_ID") \ + && (mc admin user add local "$$S3_WORKER_ACCESS_KEY_ID" "$$S3_WORKER_SECRET_ACCESS_KEY" \ + || mc admin user info local "$$S3_WORKER_ACCESS_KEY_ID") \ + && (mc admin policy create local messenger-attachments-rw /tmp/minio-api-policy.json \ + || mc admin policy info local messenger-attachments-rw) \ + && mc admin policy attach local messenger-attachments-rw --user "$$S3_ACCESS_KEY_ID" \ + && mc admin policy attach local messenger-attachments-rw --user "$$S3_WORKER_ACCESS_KEY_ID" + do + attempt=$$((attempt + 1)) + if [ "$$attempt" -ge 30 ]; then + echo "MinIO bootstrap did not complete after 30 attempts" >&2 + exit 1 + fi + sleep 2 + done + restart: "no" + networks: [backend] + + private-bucket-check: + profiles: ["verification"] + image: bitnamilegacy/minio-client:2025.4.16-debian-12-r0@sha256:28e38f52642c06a2344fa974cf55786b4c52601b6b9b0676c68d40ee0876a5bc + depends_on: + minio-init: + condition: service_completed_successfully + environment: + S3_BUCKET: ${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} + volumes: + - ./secrets/pki/service-ca/ca.crt:/root/.mc/certs/CAs/service-ca.crt:ro + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + mc alias set anonymous https://minio:9000 + if mc ls "anonymous/$$S3_BUCKET" >/dev/null 2>&1; then + echo "FAIL: anonymous bucket listing succeeded" >&2 + exit 1 + fi + mc alias set restricted https://minio:9000 "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY" + mc ls "restricted/$$S3_BUCKET" >/dev/null + if mc admin info restricted >/dev/null 2>&1; then + echo "FAIL: API credentials have administrative access" >&2 + exit 1 + fi + echo "PASS: bucket is private and API credentials are non-admin" + restart: "no" + networks: [backend] + + # One-shot Flyway runner. It is invoked explicitly before API replicas. + migrate: + image: hla-lab7-app:local + build: + context: . + environment: + <<: *api-environment + FLYWAY_ENABLED: "true" + MIGRATE_ONLY: "true" + MESSENGER_ROLE: migration + SPRING_MAIN_WEB_APPLICATION_TYPE: none + OTEL_SDK_DISABLED: "true" + DATABASE_USER: messenger_migration + DATABASE_PASSWORD: ${DATABASE_MIGRATION_PASSWORD:?Set DATABASE_MIGRATION_PASSWORD in .env} + CLIENT_TLS_CERTIFICATE: /run/pki/migration-client/tls.crt + CLIENT_TLS_PRIVATE_KEY: /run/pki/migration-client/tls.key + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + rabbitmq: + condition: service_healthy + volumes: + - ./secrets/pki:/run/pki:ro + restart: "no" + cpus: 0.75 + mem_limit: 768m + networks: [backend] + + api: + image: hla-lab7-app:local + build: + context: . + environment: + <<: *api-environment + FLYWAY_ENABLED: "false" + MESSENGER_ROLE: api + OTEL_SERVICE_NAME: messenger-api + APP_PORT: 8443 + SERVER_SSL_ENABLED: "true" + SERVER_SSL_CERTIFICATE: /run/pki/api/tls.crt + SERVER_SSL_PRIVATE_KEY: /run/pki/api/tls.key + SERVER_SSL_TRUST_CERTIFICATE: /run/pki/lb-client-ca/ca.crt + SERVER_SSL_CLIENT_AUTH: need + MTLS_ALLOWED_CLIENT_URI: spiffe://hla-lab7/lb + DATABASE_USER: messenger_api + CLIENT_TLS_CERTIFICATE: /run/pki/api-client/tls.crt + CLIENT_TLS_PRIVATE_KEY: /run/pki/api-client/tls.key + REDIS_USER: messenger-api + RABBITMQ_USER: messenger-api + OPENBAO_RENDERED_ENV: /run/openbao/runtime.env + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/pki/service-ca/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/pki/api-client/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/pki/api-client/tls.key + FAULT_CRASH_AFTER_OUTBOX_COMMIT: ${FAULT_CRASH_AFTER_OUTBOX_COMMIT:-false} + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + minio-init: + condition: service_completed_successfully + rabbitmq-init: + condition: service_completed_successfully + otel-collector: + condition: service_started + openbao-agent-api: + condition: service_started + volumes: + - ./secrets/pki:/run/pki:ro + - api-runtime-secrets:/run/openbao:ro + healthcheck: + disable: true + init: true + stop_grace_period: 12s + restart: unless-stopped + cpus: 0.75 + mem_limit: 768m + networks: [backend] + + worker: + image: hla-lab7-app:local + environment: + <<: *api-environment + FLYWAY_ENABLED: "false" + MESSENGER_ROLE: worker + OTEL_SERVICE_NAME: messenger-worker + SPRING_MAIN_WEB_APPLICATION_TYPE: none + JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=70 + DATABASE_USER: messenger_worker + CLIENT_TLS_CERTIFICATE: /run/pki/worker-client/tls.crt + CLIENT_TLS_PRIVATE_KEY: /run/pki/worker-client/tls.key + REDIS_USER: messenger-worker + RABBITMQ_USER: messenger-worker + OPENBAO_RENDERED_ENV: /run/openbao/runtime.env + OTEL_EXPORTER_OTLP_CERTIFICATE: /run/pki/service-ca/ca.crt + OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/pki/worker-client/tls.crt + OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/pki/worker-client/tls.key + FAULT_CRASH_BEFORE_SIDE_EFFECT: ${FAULT_CRASH_BEFORE_SIDE_EFFECT:-false} + FAULT_CRASH_AFTER_SIDE_EFFECT: ${FAULT_CRASH_AFTER_SIDE_EFFECT:-false} + FAULT_CRASH_AFTER_RESULT_COMMIT: ${FAULT_CRASH_AFTER_RESULT_COMMIT:-false} + depends_on: + migrate: + condition: service_completed_successfully + minio-init: + condition: service_completed_successfully + rabbitmq-init: + condition: service_completed_successfully + otel-collector: + condition: service_started + openbao-agent-worker: + condition: service_started + healthcheck: + disable: true + volumes: + - ./secrets/pki:/run/pki:ro + - worker-runtime-secrets:/run/openbao:ro + init: true + stop_grace_period: 20s + restart: unless-stopped + cpus: 1.0 + mem_limit: 1024m + networks: [backend] + + nginx: + image: nginx:1.27.4-bookworm + ports: + - "${PUBLIC_BIND_ADDRESS:-127.0.0.1}:${PUBLIC_HTTPS_PORT:-8443}:8443" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + - ./secrets/pki:/run/pki:ro + depends_on: + api: + condition: service_started + healthcheck: + test: ["CMD", "nginx", "-t"] + interval: 2s + timeout: 2s + retries: 15 + stop_grace_period: 10s + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + networks: [backend] + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.165.0 + command: ["--config=/etc/otelcol-contrib/collector.yaml"] + volumes: + - ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro + - ./secrets/pki:/run/pki:ro + depends_on: + prometheus: + condition: service_started + loki: + condition: service_started + tempo: + condition: service_started + restart: unless-stopped + cpus: 0.5 + mem_limit: 512m + networks: [backend] + + prometheus: + image: prom/prometheus:v3.14.0 + ports: + - "127.0.0.1:${PROMETHEUS_PORT:-9090}:9090" + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=3d + - --web.enable-lifecycle + - --web.config.file=/etc/prometheus/web.yaml + volumes: + - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro + - ./infra/otel/prometheus-alerts.yaml:/etc/prometheus/prometheus-alerts.yaml:ro + - ./infra/otel/prometheus-web.yaml:/etc/prometheus/web.yaml:ro + - ./secrets/pki:/run/pki:ro + - prometheus-data:/prometheus + restart: unless-stopped + cpus: 0.5 + mem_limit: 512m + networks: [backend] + + loki: + image: grafana/loki:3.7.8 + command: ["-config.file=/etc/loki/local-config.yaml"] + ports: + - "127.0.0.1:${LOKI_PORT:-3100}:3100" + volumes: + - ./infra/otel/loki.yaml:/etc/loki/local-config.yaml:ro + - ./secrets/pki:/run/pki:ro + - loki-data:/loki + restart: unless-stopped + cpus: 0.5 + mem_limit: 512m + networks: [backend] + + tempo: + image: grafana/tempo:3.1.1 + command: ["-config.file=/etc/tempo/tempo.yaml"] + ports: + - "127.0.0.1:${TEMPO_PORT:-3200}:3200" + volumes: + - ./infra/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro + - ./secrets/pki:/run/pki:ro + - tempo-data:/var/tempo + restart: unless-stopped + cpus: 0.5 + mem_limit: 512m + networks: [backend] + + grafana: + image: grafana/grafana:13.3.0 + ports: + - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" + environment: + GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin} + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env} + GF_USERS_ALLOW_SIGN_UP: "false" + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_UNIFIED_ALERTING_ENABLED: "true" + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /run/pki/grafana/tls.crt + GF_SERVER_CERT_KEY: /run/pki/grafana/tls.key + SSL_CERT_FILE: /run/pki/service-ca/ca.crt + entrypoint: ["/bin/sh", "/etc/grafana/grafana-entrypoint.sh"] + volumes: + - ./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/otel/grafana/dashboards:/var/lib/grafana/dashboards:ro + - ./infra/otel/grafana-entrypoint.sh:/etc/grafana/grafana-entrypoint.sh:ro + - grafana-data:/var/lib/grafana + - ./secrets/pki:/run/pki:ro + depends_on: + prometheus: + condition: service_started + loki: + condition: service_started + tempo: + condition: service_started + restart: unless-stopped + cpus: 0.5 + mem_limit: 512m + networks: [backend] + +networks: + backend: + driver: bridge + +volumes: + openbao-data: + api-runtime-secrets: + worker-runtime-secrets: + postgres-data: + redis-data: + minio-data: + rabbitmq-data: + prometheus-data: + loki-data: + tempo-data: + grafana-data: diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..68dc10a 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,75 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия HLA Lab 7 -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +Матрица фиксирует целевую архитектуру и текущее покрытие. **PASS** — контроль реализован; **PARTIAL** — реализована часть; **GAP** — связь пока не удовлетворяет минимуму lab7. Docker-сеть сама по себе не является аутентификацией. -| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | +Имена identities ниже являются контрактом для PKI/OpenBao bootstrap. Формат SAN — URI `spiffe://hla-lab7/`; проверяются chain, EKU и точное разрешённое значение SAN. Private keys, root token, unseal shares и SecretID не хранятся в Git. + +## Основные связи + +| Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус | +| --- | --- | --- | --- | --- | --- | --- | +| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/tls/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement revoke; leaf 30 d | `make test-security`; чужой/пустой CA, wrong hostname, expired leaf → certificate error; revoked token → 401; login burst → 429 + Retry-After | **PASS** для внешнего TLS/auth/session/rate-limit контракта | +| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1`: no cert, foreign CA, trusted cert SAN `.../worker` rejected; LB cert → health 200 | **PASS** | +| API → PostgreSQL | `postgres:5432` | TLS `verify-full`; service CA + SAN `DNS:postgres`; plaintext rejected by `pg_hba.conf` | `messenger_api`: runtime CRUD без superuser/DDL/role management | Static stand secret, rotate/reconnect; dynamic credentials remain extension | Wrong CA/hostname fails; DDL/role management denied | **PASS (уровень 3)** | +| Worker → PostgreSQL | `postgres:5432` | TLS `verify-full` | `messenger_worker`: jobs/attachments/variants; нет users password/session/membership | Отдельный secret | `SELECT password_hash`, update membership denied; job transitions allowed | **PASS (уровень 3)** | +| API → MinIO | `https://minio:9000` | TLS verify; service CA + SAN `DNS:minio` | `messenger-api`, без admin/policy | Static stand secret, отдельно от root | Anonymous и `mc admin` denied; allowed prefix succeeds | **PASS на 3; GAP:** OpenBao rotation/prefix split | +| Worker → MinIO | `https://minio:9000` | TLS verify | Отдельный `messenger-worker` key; без admin | Отдельный static secret | `mc admin` denied | **PARTIAL:** identity отдельная, prefix policy пока общая | +| API → RabbitMQ | `rabbitmq:5671` | mTLS: service CA + workload client CA | `messenger-api`, отдельный cert SAN `.../api` и regex permissions | Отдельный secret/cert; reconnect on rotation | No cert/foreign CA denied; broker ACL ограничивает операции | **PASS на 4** | +| Worker → RabbitMQ | `rabbitmq:5671` | mTLS | Отдельные `messenger-worker` cert/user/permissions | Отдельный secret/cert | No cert/foreign CA и запрещённые ACL operations rejected | **PASS на 4** | +| API/worker → Redis | mTLS `redis:6379` | service CA + workload client CA; plaintext port disabled | Раздельные cert/ACL users; admin/flush commands removed | Отдельные secrets/certs | No cert/foreign CA, CONFIG/ACL/FLUSHALL denied | **PASS на 4** | +| API → Collector | `https://otel-collector:4318` | mTLS, service/server CA + workload client CA | SAN `spiffe://hla-lab7/api`; distinct client leaf | Leaf 30 d | No cert/foreign CA rejected; valid OTLP accepted | **PASS на 4 (раздельный cert)** | +| Worker → Collector | `https://otel-collector:4318` | mTLS | SAN `spiffe://hla-lab7/worker`; distinct cert/service.name | Отдельный leaf/revoke | Foreign CA rejected; API/worker различимы | **PASS на 4 (раздельный cert)** | +| Prometheus → Collector metrics exporter | `https://otel-collector:8889` | mTLS, service CA + telemetry client CA | Отдельный cert SAN `spiffe://hla-lab7/prometheus` | Leaf 30 d | No cert/foreign CA denied | **PASS на 4** | +| Collector → Loki | `https://loki:3100/otlp` | mTLS, Loki service cert + telemetry client CA | Cert SAN `spiffe://hla-lab7/otel-collector` | Leaf 30 d | No cert/foreign CA denied | **PASS на 4** | +| Collector → Tempo | `https://tempo:4318` | mTLS, Tempo service cert + telemetry client CA | Cert SAN `spiffe://hla-lab7/otel-collector` | Leaf 30 d | No cert/foreign CA denied | **PASS на 4** | +| Grafana → backends | HTTPS/mTLS service endpoints | Service CA verify-full; datasource CA/cert/key injected at runtime from files | Отдельный cert SAN `spiffe://hla-lab7/grafana`; Prometheus exact SAN allowlist | Leaf 30 d, not stored in provisioning Git | No cert/foreign CA denied; query allowed | **PASS для transport/identity; backend fine-grained query ACL ограничен single-tenant режимом** | +| API Agent → OpenBao | `https://openbao:8200` | TLS verify; service CA + SAN `DNS:openbao` | AppRole `messenger-api`: read только собственного KV data/metadata; нет sys/auth/root/worker | Renewable token 15 min, max 1 h; re-auth; SecretID 24 h | `test-openbao-policies.ps1`: чужой path/policy write denied; own path allowed | **PASS по конфигурации; runtime test требует initialized стенд** | +| Worker Agent → OpenBao | `https://openbao:8200` | TLS verify | AppRole `messenger-worker`: read только собственного KV data/metadata | Независимые token, RoleID и SecretID с теми же TTL | API path/policy write denied; own path allowed | **PASS по конфигурации; runtime test требует initialized стенд** | +| Agent → API/worker runtime file | Отдельные named volumes | Локальный file handoff; volume не общий между ролями | Agent рендерит allowlisted keys; app mount read-only; неожиданный key отклоняется entrypoint | Render interval 5 min; приложение перечитывает при restart | Нет файла → controlled startup failure после 120 s; чужой volume не mounted | **PASS** | +| Operator → OpenBao | `https://localhost:8200`, только loopback | TLS + service CA, SAN `localhost` | Init/unseal/root только bootstrap/recovery; file audit включён | 3 shares, threshold 2; shares/root offline; root env удаляется после bootstrap | AppRole не может init/unseal/write policy; извне хоста порт не опубликован | **PASS по конфигурации; init/unseal остаётся ручной операцией** | +| Operator → Grafana | `https://localhost:3000` | TLS verify, service CA, SAN localhost, loopback only | Named admin; anonymous/signup disabled | Local generated password/rotation | Anonymous/app credential denied | **PASS** | +| Operator → MinIO admin | Не публикуется; bootstrap внутри сети | TLS verify | Root/operator отдельно; API/worker его не получают | Rotate after bootstrap/exposure | API/worker `mc admin info` denied | **PARTIAL:** port закрыт/policy test есть; HTTP и root env у init | +| Replication channels | N/A: все stateful services single-node | N/A | N/A | N/A | При добавлении replicas матрица пересматривается | **N/A** | + +## Health, scrape и bootstrap + +| Канал | Разрешение | Запрет / тест | Статус | | --- | --- | --- | --- | -| Клиент → 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 | +| Public `/health/live`, `/health/ready` | Только `{"status":"ok"}` без topology/secrets | Business routes требуют Bearer | **PASS** по API contract | +| nginx `/nginx-health` | Только probe | Не должен быть backend proxy; предпочтителен internal listener | **PARTIAL:** сейчас на public listener | +| API container health | Тот же mTLS `api:8443`, доступен только LB/probe identity | Health не создаёт plaintext bypass; отдельный listener остаётся hardening | **PARTIAL:** health и business routes разделяют listener, но оба закрыты mTLS | +| Collector `:13133` | Только orchestrator/internal network | Не принимает OTLP и не публикуется host | **PARTIAL:** общая backend network широкая | +| Store healthchecks | Минимальная readiness без secret output | Не создают anonymous admin access | **PARTIAL:** TLS ещё не включён | +| MinIO bootstrap | One-shot operator workflow | Root не печатается и не остаётся API/worker | **PARTIAL:** root через env; заменить secret file/OpenBao workflow | +| Flyway migrate | Отдельная `messenger_migration` DDL identity и client cert | API/worker без DDL; migration container one-shot | **PASS;** static stand password rotation ещё ручная | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +## Обязательные отрицательные сценарии -## Обязательные отрицательные проверки +Каждый тест сохраняет команду, timestamp, ожидаемый и наблюдаемый результат без secret values. -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. Покажите новое подключение, иначе тест отзыва может ничего не проверить. +1. Доверенный CA + `localhost` проходит; пустой trust store, чужой CA, expired leaf и wrong hostname дают certificate verification error. `curl -k` запрещён. +2. Для каждой API replica: no client cert, foreign CA и trusted CA с SAN `.../worker` отклоняются; только SAN `.../lb` проходит. +3. Bob не читает metadata/content чата Alice, не отправляет туда сообщение и не прикрепляет attachment другого чата. Forged `X-User-Id` не меняет Bearer identity. +4. API DB role не выполняет DDL/role management; worker не читает users/session hashes и не меняет membership; migration credential отсутствует runtime. +5. Anonymous S3 list/get запрещены; API/worker без admin; worker не выходит за staging/variant prefixes. +6. API не consume/ack broker queue; worker не configure и не publish произвольный key. На уровне 4 повторяются no-cert/foreign-CA/wrong-SAN tests. +7. Неизвестная identity не ingest telemetry; ingest credential не query/delete; Grafana read-only. Canary Authorization/token отсутствует во всех signals. +8. API/worker OpenBao policies читают только свои paths; `sys/policies/*`, чужой KV и admin credentials дают 403. После revoke проверяется новое соединение с учётом pool/cache. +9. При rotation новый leaf/secret вводится overlap, clients reconnect, старый credential доказанно отклоняется, новый работает. +10. При остановке TLS proxy/OpenBao нет downgrade на plaintext/hardcoded fallback: сервис controlled-unready либо работает лишь до documented lease TTL. -## Bootstrap и эксплуатация +## Bootstrap и владение -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. +- В Git находятся только открытые configs, policy templates, scripts и при необходимости public CA. Private keys/secrets создаются в `secrets/` с ограниченными ACL и исключены из build context. +- Владелец root CA, OpenBao init/root token и unseal shares — оператор. Ручной unseal допустим; shares не лежат рядом со storage volume. +- API, worker, migration, Collector, Grafana datasource и operator имеют разные identities. Общий credential между ролями — дефект даже при TLS. +- OpenBao работает с persistent storage не в dev-mode. Root token не передаётся приложению. Service token ограничен named policy/TTL/max TTL. +- Rotation доказана только после закрытия старого соединения: pools, TLS resumption и caches могут маскировать отзыв. -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 — хорошее расширение, но не обязательное название технологии. +## Приоритет устранения GAP -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +1. Выделить отдельный безопасный API health listener, не содержащий business routes. +2. Разделить MinIO prefix policies API/worker и автоматизировать rotation runtime credentials. +3. Добавить отдельную узкую operator policy для ротации AppRole вместо root token после первичного bootstrap. +4. Добавить backend query-level ACL поверх уже включённого telemetry mTLS. +5. Расширить автоматизированные mTLS/rotation tests на broker, Redis и telemetry; внешний ACL/session/rate-limit сценарий находится в `tests/security.py`. diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ad7845b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a51ec4f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/infra/minio-api-policy.json b/infra/minio-api-policy.json new file mode 100644 index 0000000..0ee222d --- /dev/null +++ b/infra/minio-api-policy.json @@ -0,0 +1,27 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetBucketLocation", + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::__S3_BUCKET__" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": [ + "arn:aws:s3:::__S3_BUCKET__/attachments/*", + "arn:aws:s3:::__S3_BUCKET__/staging/*" + ] + } + ] +} diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 0000000..752f04e --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,115 @@ +worker_processes auto; +worker_shutdown_timeout 10s; + +events { + worker_connections 1024; +} + +http { + # Let the application enforce the exact 10 MiB contract and return JSON. + client_max_body_size 11m; + client_body_timeout 10s; + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log warn; + + # Docker embedded DNS returns current Compose replicas. Nginx OSS 1.27.3+ + # refreshes these addresses without a configuration reload. + resolver 127.0.0.11 valid=2s ipv6=off; + resolver_timeout 1s; + + upstream api_backend { + zone api_backend 64k; + least_conn; + server api:8443 resolve max_fails=1 fail_timeout=2s; + keepalive 32; + } + + server { + listen 8443 ssl; + server_name localhost; + ssl_certificate /run/pki/ingress/tls.crt; + ssl_certificate_key /run/pki/ingress/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_tickets off; + add_header Strict-Transport-Security "max-age=31536000" always; + proxy_ssl_certificate /run/pki/lb/tls.crt; + proxy_ssl_certificate_key /run/pki/lb/tls.key; + proxy_ssl_trusted_certificate /run/pki/service-ca/ca.crt; + proxy_ssl_verify on; + proxy_ssl_verify_depth 2; + proxy_ssl_server_name on; + proxy_ssl_name api; + proxy_intercept_errors on; + error_page 502 503 504 = @no_ready_api; + + location = /nginx-health { + access_log off; + default_type application/json; + return 200 '{"status":"ok"}'; + } + + # After both peers have refused traffic or become unreachable, Nginx + # would normally emit its own HTML 502. Keep the public API contract: + # no ready backend is a JSON 503 with the required tracing headers. + location @no_ready_api { + internal; + default_type application/json; + add_header X-Request-Id $request_id always; + add_header X-Instance-Id nginx always; + add_header Cache-Control "no-store" always; + return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}'; + } + + # Message POST is the only non-idempotent HTTP method that is safe to + # replay here: the API requires Idempotency-Key and commits the message + # together with its shared PostgreSQL idempotency record. + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ { + proxy_pass https://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent; + proxy_next_upstream_tries 2; + } + + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/attachments$ { + proxy_pass https://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + + proxy_connect_timeout 500ms; + proxy_send_timeout 20s; + proxy_read_timeout 20s; + # Upload is not replayed: it has no idempotency key. The client may retry explicitly. + proxy_next_upstream off; + } + + location / { + proxy_pass https://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + + # No sticky sessions. Failed/unready peers are retried elsewhere. + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 0850e23..e901ef9 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,7 +1,107 @@ -# OpenBao — реализовать конфигурацию и политики +# OpenBao: эксплуатация стенда -Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. +OpenBao запускается обычным `server`, а не `dev`: данные хранятся в named volume `openbao-data` через integrated Raft storage. TLS обязателен, порт опубликован только на loopback. После перезапуска данные сохраняются, но сервер снова sealed до ручного unseal. -Решение должно показать реальную сервисную аутентификацию и получение нужного 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. +1. Создайте локальные credentials и PKI: + + ```powershell + .\scripts\bootstrap-secrets.ps1 + .\scripts\bootstrap-pki.ps1 + ``` + +2. Запустите только OpenBao и проверьте состояние `uninitialized`: + + ```powershell + docker compose --env-file .env up -d openbao + docker compose --env-file .env exec openbao bao status + ``` + +3. Один раз выполните init из интерактивного терминала оператора: + + ```powershell + docker compose --env-file .env exec openbao bao operator init -key-shares=3 -key-threshold=2 + ``` + + Команда выводит три unseal share и initial root token. Оператор немедленно переносит их в защищённое внешнее хранилище; доли передаются разным хранителям. Их запрещено сохранять в `.env`, `secrets/`, shell history, отчёт, скриншот или Git. Скрипты проекта намеренно не автоматизируют и не перехватывают init. + +4. Введите любые две разные доли вручную. Значения вместо маркеров в команду не вставляйте: команда запросит их скрыто интерактивно. + + ```powershell + docker compose --env-file .env exec openbao bao operator unseal + docker compose --env-file .env exec openbao bao operator unseal + docker compose --env-file .env exec openbao bao status + ``` + +5. Только на время bootstrap задайте root token в окружении текущего PowerShell-процесса и создайте KV, политики и AppRole: + + ```powershell + $env:BAO_TOKEN = Read-Host 'OpenBao root token' + .\scripts\bootstrap-openbao.ps1 + Remove-Item Env:BAO_TOKEN + ``` + + Скрипт не печатает secret values. Он загружает их в KV v2 через stdin, включает file audit, создаёт отдельные `messenger-api` и `messenger-worker` policies и кладёт только стартовые AppRole RoleID/SecretID в игнорируемый каталог `secrets/openbao/`. + +6. Запустите весь стенд: + + ```powershell + docker compose --env-file .env up -d + ``` + +OpenBao Agent у API и worker аутентифицируется своим AppRole, получает renewable token с TTL 15 минут и max TTL 1 час и рендерит только разрешённый набор runtime credentials в отдельный named volume. Root token и unseal shares в контейнеры приложений не передаются. + +## Политики и проверяемые отказы + +- `messenger-api` читает только `secret/data/messenger/api` и его metadata. +- `messenger-worker` читает только `secret/data/messenger/worker` и его metadata. +- У ролей нет доступа к чужому KV, `sys/policies/*`, auth configuration, init или unseal. +- AppRole SecretID действует 24 часа; token TTL — 15 минут, max TTL — 1 час. `token_num_uses=0` необходим для renewal и повторного чтения Agent, но область доступа ограничивает named policy. + +После bootstrap выполните: + +```powershell +.\scripts\test-openbao-policies.ps1 +``` + +Тест требует существующие игнорируемые AppRole-файлы и доказывает allow для собственного пути, deny для чужого пути и deny изменения policy. Токены и SecretID не выводятся. + +## Перезапуск, seal и восстановление + +После перезапуска `openbao-data` сохраняется. Оператор снова выполняет две интерактивные команды `bao operator unseal`. Пока OpenBao sealed, agents не получают и не обновляют token; hardcoded или `.env` fallback у приложений отсутствует. После unseal agents повторяют authentication. Если приложение ещё не запущено, entrypoint ждёт rendered file до 120 секунд и завершает работу при его отсутствии. + +Статические DB/Redis/RabbitMQ/S3 credentials читаются приложением при старте. После создания новой KV version следует последовательно перезапустить API/worker, проверить новые соединения, затем отозвать старые credentials в зависимости. OpenBao token rotation выполняется Agent автоматически. + +## Ротация AppRole bootstrap credential + +SecretID нужно менять до истечения 24 часов: + +```powershell +$env:BAO_TOKEN = Read-Host 'OpenBao operator token' +.\scripts\rotate-openbao-secret-ids.ps1 +Remove-Item Env:BAO_TOKEN +docker compose --env-file .env restart openbao-agent-api openbao-agent-worker +``` + +Скрипт заменяет локальные SecretID-файлы и не печатает их. В production вместо root token для этой операции создаётся отдельная узкая operator policy; root token после первичного bootstrap хранится offline. + +## Эксплуатационные ограничения + +`disable_mlock=true` выбран для локального Docker Desktop стенда: контейнеру не выдаётся `IPC_LOCK`. Это осознанный компромисс лабораторного окружения; swap/дампы хоста остаются в зоне доверия оператора. Agents запускаются как root только для записи в выделенные named volumes, при этом имеют `cap_drop: ALL`, `no-new-privileges`, read-only mounts конфигурации/PKI/bootstrap и не получают Docker socket. + +Удаление volume уничтожает OpenBao storage и требует нового init. Выполнять следующую команду можно только при намеренном полном сбросе стенда и наличии решения оператора о судьбе старых shares: + +```powershell +docker compose --env-file .env down --volumes +``` + +## Что не хранится в репозитории + +- initial root token; +- unseal shares; +- AppRole SecretID и RoleID стенда; +- private keys и рабочие service credentials; +- содержимое Raft storage и audit log. + +Справка: [operator init](https://openbao.org/docs/commands/operator/init/), [AppRole](https://openbao.org/docs/auth/approle/), [Agent auto-auth](https://openbao.org/docs/agent-and-proxy/autoauth/), [Raft storage](https://openbao.org/docs/configuration/storage/raft/), [KV CLI stdin](https://openbao.org/docs/commands/). diff --git a/infra/openbao/agent-api.hcl b/infra/openbao/agent-api.hcl new file mode 100644 index 0000000..5655852 --- /dev/null +++ b/infra/openbao/agent-api.hcl @@ -0,0 +1,31 @@ +vault { + address = "https://openbao:8200" + ca_cert = "/run/pki/service-ca/ca.crt" +} +auto_auth { + method "approle" { + mount_path = "auth/approle" + config = { + role_id_file_path = "/run/bootstrap/role-id" + secret_id_file_path = "/run/bootstrap/secret-id" + remove_secret_id_file_after_reading = false + } + } +} +template_config { + static_secret_render_interval = "5m" + exit_on_retry_failure = false +} +template { + contents = < OTLP/HTTP -> otel-collector -> Prometheus / Loki / Tempo -> Grafana`. -Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. +Версии закреплены в `compose.yaml`: Java agent 2.33.1 (SDK 1.67.0), Collector Contrib 0.165.0, Prometheus 3.14.0, Loki 3.7.8, Tempo 3.1.1 и Grafana 13.3.0. + +## Файлы + +- `collector.yaml` — OTLP receivers, memory limiter, redaction, batch и bounded retry queues; +- `prometheus.yaml` и `prometheus-alerts.yaml` — scrape, SLO/queue/worker/export alerts; +- `loki.yaml` — локальное хранилище структурных OTLP logs; +- `tempo.yaml` — локальное хранилище traces; +- `grafana/provisioning` — три datasources и dashboard provisioning; +- `grafana/dashboards/messenger-overview.json` — импортируемый dashboard; +- `runbooks.md` — локальные действия для каждого alert. + +Grafana доступна только на `127.0.0.1:3000`, Prometheus — на `127.0.0.1:9090`. Для автоматизированных incident snapshots Loki и Tempo доступны только на loopback-портах 3100 и 3200. OTLP Collector не публикуется на интерфейсы хоста. + +## Проверка корреляции + +1. Выполнить `python tests/smoke.py --base-url http://localhost:8080`. +2. В Tempo найти server span upload и перейти к RabbitMQ producer/consumer span. +3. Скопировать `trace_id` и выполнить в Loki `{service_name=~"messenger-(api|worker)"} | json | trace_id="..."`. +4. Убедиться, что у API и worker разные `service.name`, но общий trace context. + +Для durable retry `traceparent/tracestate` сохраняются рядом с job в PostgreSQL и восстанавливаются перед outbox republish. Проверяемый сценарий: `scripts/incident-retry-trace.ps1`; он требует минимум два producer/consumer span в одной trace и сохраняет их parent IDs. + +Collector удаляет потенциально чувствительные HTTP/message/body/DB parameter attributes. Java agent не настроен на захват request/response headers или bodies. Метрики используют только route template, status/method, job type/outcome и queue name. diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..addc49e --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,104 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /run/pki/otel-collector/tls.crt + key_file: /run/pki/otel-collector/tls.key + client_ca_file: /run/pki/workload-client-ca/ca.crt + min_version: "1.2" + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 384 + spike_limit_mib: 96 + attributes/redact: + actions: + - key: http.request.header.authorization + action: delete + - key: http.request.body + action: delete + - key: http.response.body + action: delete + - key: messaging.message.body + action: delete + - key: db.statement.parameters + action: delete + - key: url.query + action: delete + batch: + send_batch_size: 512 + timeout: 5s + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + tls: + cert_file: /run/pki/otel-collector/tls.crt + key_file: /run/pki/otel-collector/tls.key + client_ca_file: /run/pki/telemetry-client-ca/ca.crt + send_timestamps: true + resource_constant_labels: + included: ["service.*", "deployment.environment.name"] + otlp_http/tempo: + endpoint: https://tempo:4318 + tls: + ca_file: /run/pki/service-ca/ca.crt + cert_file: /run/pki/collector-client/tls.crt + key_file: /run/pki/collector-client/tls.key + sending_queue: + enabled: true + queue_size: 2048 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 60s + otlp_http/loki: + endpoint: https://loki:3100/otlp + tls: + ca_file: /run/pki/service-ca/ca.crt + cert_file: /run/pki/collector-client/tls.crt + key_file: /run/pki/collector-client/tls.key + sending_queue: + enabled: true + queue_size: 2048 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 60s + +service: + extensions: [health_check] + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + without_type_suffix: false + without_units: false + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, batch] + exporters: [otlp_http/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, batch] + exporters: [otlp_http/loki] diff --git a/infra/otel/docker-entrypoint.sh b/infra/otel/docker-entrypoint.sh new file mode 100644 index 0000000..4a88fde --- /dev/null +++ b/infra/otel/docker-entrypoint.sh @@ -0,0 +1,34 @@ +#!/bin/sh +set -eu + +if [ -n "${OPENBAO_RENDERED_ENV:-}" ]; then + deadline=$(( $(date +%s) + ${OPENBAO_STARTUP_TIMEOUT_SECONDS:-120} )) + while [ ! -s "$OPENBAO_RENDERED_ENV" ]; do + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "OpenBao did not render runtime credentials before startup deadline" >&2 + exit 1 + fi + sleep 1 + done + while IFS='=' read -r name value; do + case "$name" in + DATABASE_PASSWORD|REDIS_PASSWORD|RABBITMQ_PASSWORD|S3_ACCESS_KEY_ID|S3_SECRET_ACCESS_KEY) + export "$name=$value" ;; + '') ;; + *) echo "Unexpected key in OpenBao rendered environment: $name" >&2; exit 1 ;; + esac + done < "$OPENBAO_RENDERED_ENV" +fi + +if [ -f /run/pki/service-ca/ca.crt ]; then + keytool -importcert -noprompt -alias hla-lab7-service-ca \ + -file /run/pki/service-ca/ca.crt -keystore /tmp/service-truststore.p12 \ + -storetype PKCS12 -storepass changeit >/dev/null 2>&1 + export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:-} -Djavax.net.ssl.trustStore=/tmp/service-truststore.p12 -Djavax.net.ssl.trustStorePassword=changeit" +fi + +if [ "${OTEL_SDK_DISABLED:-false}" = "true" ]; then + exec java -jar /app/app.jar "$@" +fi + +exec java -javaagent:/opt/opentelemetry-javaagent.jar -jar /app/app.jar "$@" diff --git a/infra/otel/grafana-entrypoint.sh b/infra/otel/grafana-entrypoint.sh new file mode 100644 index 0000000..0277b22 --- /dev/null +++ b/infra/otel/grafana-entrypoint.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +export SERVICE_CA_PEM="$(cat /run/pki/service-ca/ca.crt)" +export GRAFANA_CLIENT_CERT_PEM="$(cat /run/pki/grafana-client/tls.crt)" +export GRAFANA_CLIENT_KEY_PEM="$(cat /run/pki/grafana-client/tls.key)" +exec /run.sh diff --git a/infra/otel/grafana/dashboards/messenger-overview.json b/infra/otel/grafana/dashboards/messenger-overview.json new file mode 100644 index 0000000..efdf757 --- /dev/null +++ b/infra/otel/grafana/dashboards/messenger-overview.json @@ -0,0 +1,141 @@ +{ + "annotations": {"list": []}, + "editable": false, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "id": null, + "links": [], + "liveNow": false, + "panels": [ + { + "id": 1, + "title": "API requests / second", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"refId": "A", "expr": "sum by (http_request_method) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m]))", "legendFormat": "{{http_request_method}}"}], + "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 0} + }, + { + "id": 2, + "title": "API 5xx ratio", + "description": "5xx business responses divided by all business responses over 5 minutes; health routes are excluded. Displayed as percent (0..100%).", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"refId": "A", "expr": "(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\",http_route!~\"/health/.*\"}[5m])) or vector(0)) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])), 0.001)", "legendFormat": "5xx / all"}], + "fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 0} + }, + { + "id": 3, + "title": "API duration p50 / p95 / p99", + "description": "Seconds. histogram_quantile is calculated from the summed Prometheus histogram buckets of all API replicas; replica percentiles are never averaged.", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [ + {"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p50"}, + {"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p95"}, + {"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p99"} + ], + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 0} + }, + { + "id": 4, + "title": "Job outcomes / second", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"refId": "A", "expr": "sum by (outcome) (rate(messenger_jobs_processed_total{service_name=\"messenger-worker\"}[5m]))", "legendFormat": "{{outcome}}"}], + "fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 8} + }, + { + "id": 5, + "title": "Job duration p95", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_processing_duration_seconds_bucket{service_name=\"messenger-worker\"}[5m])))", "legendFormat": "{{outcome}}"}], + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 8} + }, + { + "id": 6, + "title": "Time to ready p95", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[10m])))", "legendFormat": "p95"}], + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 8} + }, + { + "id": 7, + "title": "Queue depth and oldest age", + "description": "Left axis: durable queued jobs (count). Right axis: age of the oldest unfinished job (seconds). Backlog age is not processing latency.", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [ + {"refId": "A", "expr": "max(messenger_queue_depth{service_name=\"messenger-api\"})", "legendFormat": "depth"}, + {"refId": "B", "expr": "max(messenger_queue_oldest_job_age_seconds{service_name=\"messenger-api\"})", "legendFormat": "oldest age (s)"} + ], + "fieldConfig": { + "defaults": {}, + "overrides": [ + {"matcher": {"id": "byName", "options": "depth"}, "properties": [{"id": "unit", "value": "short"}, {"id": "custom.axisPlacement", "value": "left"}]}, + {"matcher": {"id": "byName", "options": "oldest age (s)"}, "properties": [{"id": "unit", "value": "s"}, {"id": "custom.axisPlacement", "value": "right"}]} + ] + }, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 16} + }, + { + "id": 8, + "title": "Worker saturation", + "description": "busy workers / configured worker capacity. Dimensionless ratio displayed as percent.", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"refId": "A", "expr": "messenger_worker_busy{service_name=\"messenger-worker\"} / clamp_min(messenger_worker_capacity{service_name=\"messenger-worker\"}, 1)", "legendFormat": "{{service_instance_id}}"}], + "fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 16} + }, + { + "id": 9, + "title": "DB pool used / waiting", + "description": "Number of HikariCP connections by state plus pending acquisition requests. Unit: connections/requests (count).", + "type": "timeseries", + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [ + {"refId": "A", "expr": "sum by (service_name, state) (db_client_connections_usage{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} {{state}}"}, + {"refId": "B", "expr": "sum by (service_name) (db_client_connections_pending_requests{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} waiting"} + ], + "fieldConfig": {"defaults": {"unit": "short"}, "overrides": []}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 16} + }, + { + "id": 10, + "title": "Correlated application logs", + "type": "logs", + "datasource": {"type": "loki", "uid": "loki"}, + "targets": [{"refId": "A", "expr": "{service_name=~\"messenger-(api|worker)\"} | json", "queryType": "range"}], + "options": {"showTime": true, "showLabels": false, "wrapLogMessage": true, "prettifyLogMessage": true, "enableLogDetails": true, "sortOrder": "Descending", "dedupStrategy": "none"}, + "gridPos": {"h": 10, "w": 16, "x": 0, "y": 24} + }, + { + "id": 11, + "title": "Recent traces", + "type": "traces", + "datasource": {"type": "tempo", "uid": "tempo"}, + "targets": [{"refId": "A", "queryType": "search", "serviceName": "messenger-api", "limit": 20}], + "gridPos": {"h": 10, "w": 8, "x": 16, "y": 24} + } + ], + "refresh": "10s", + "schemaVersion": 41, + "tags": ["hla", "lab6", "opentelemetry"], + "templating": {"list": []}, + "time": {"from": "now-30m", "to": "now"}, + "timepicker": {}, + "timezone": "browser", + "title": "Messenger observability", + "uid": "messenger-observability", + "version": 3, + "weekStart": "" +} diff --git a/infra/otel/grafana/provisioning/dashboards/dashboards.yaml b/infra/otel/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..ce50d27 --- /dev/null +++ b/infra/otel/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,13 @@ +apiVersion: 1 + +providers: + - name: Messenger Lab 6 + orgId: 1 + folder: HLA Lab 6 + type: file + disableDeletion: true + updateIntervalSeconds: 30 + allowUiUpdates: false + options: + path: /var/lib/grafana/dashboards + foldersFromFilesStructure: false diff --git a/infra/otel/grafana/provisioning/datasources/datasources.yaml b/infra/otel/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..f012407 --- /dev/null +++ b/infra/otel/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,77 @@ +apiVersion: 1 + +deleteDatasources: + - name: Prometheus + orgId: 1 + - name: Loki + orgId: 1 + - name: Tempo + orgId: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:9090 + isDefault: true + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + timeInterval: 10s + exemplarTraceIdDestinations: + - name: trace_id + datasourceUid: tempo + secureJsonData: + tlsCACert: ${SERVICE_CA_PEM} + tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM} + tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM} + + - name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:3100 + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + derivedFields: + - name: TraceID + matcherRegex: '"trace_id":"([a-f0-9]{32})"' + datasourceUid: tempo + url: '$${__value.raw}' + secureJsonData: + tlsCACert: ${SERVICE_CA_PEM} + tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM} + tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM} + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:3200 + editable: false + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + httpMethod: GET + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -1m + spanEndTimeShift: 1m + filterByTraceID: true + filterBySpanID: false + customQuery: true + query: '{$${__tags}} | json | trace_id="$${__trace.traceId}"' + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true + search: + hide: false + secureJsonData: + tlsCACert: ${SERVICE_CA_PEM} + tlsClientCert: ${GRAFANA_CLIENT_CERT_PEM} + tlsClientKey: ${GRAFANA_CLIENT_KEY_PEM} diff --git a/infra/otel/loki.yaml b/infra/otel/loki.yaml new file mode 100644 index 0000000..9a74ac3 --- /dev/null +++ b/infra/otel/loki.yaml @@ -0,0 +1,42 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + http_tls_config: + cert_file: /run/pki/loki/tls.crt + key_file: /run/pki/loki/tls.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/pki/telemetry-client-ca/ca.crt + +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 + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + +analytics: + reporting_enabled: false diff --git a/infra/otel/prometheus-alerts.yaml b/infra/otel/prometheus-alerts.yaml new file mode 100644 index 0000000..47c23ac --- /dev/null +++ b/infra/otel/prometheus-alerts.yaml @@ -0,0 +1,51 @@ +groups: + - name: messenger-slo + rules: + - alert: MessengerApiHighErrorRate + expr: | + ( + (sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!~"/health/.*"}[5m])) or vector(0)) + / + clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*"}[5m])), 0.001) + ) > 0.05 + for: 2m + labels: + severity: warning + slo: api-availability + annotations: + summary: Messenger API 5xx ratio exceeds 5% + description: Five-minute 5xx ratio is above 5% for two minutes. + runbook: infra/otel/runbooks.md#api-high-error-rate + + - alert: AttachmentQueueLagHigh + expr: messenger_queue_oldest_job_age_seconds{service_name="messenger-api"} > 60 + for: 1m + labels: + severity: warning + slo: attachment-time-to-ready + annotations: + summary: Oldest attachment job is over 60 seconds old + description: The durable worker queue has not drained within the SLO threshold. + runbook: infra/otel/runbooks.md#queue-lag + + - alert: AttachmentWorkerSaturated + expr: | + messenger_worker_busy{service_name="messenger-worker"} + / clamp_min(messenger_worker_capacity{service_name="messenger-worker"}, 1) >= 1 + for: 2m + labels: + severity: warning + annotations: + summary: All attachment workers are busy + description: Worker busy/capacity has remained at 100% for two minutes. + runbook: infra/otel/runbooks.md#worker-saturation + + - alert: TelemetryExportFailures + expr: sum(rate(otelcol_exporter_send_failed_spans_total[5m])) + sum(rate(otelcol_exporter_send_failed_log_records_total[5m])) > 0 + for: 1m + labels: + severity: info + annotations: + summary: Collector is dropping traces or logs + description: A telemetry backend is unavailable or rejecting data. + runbook: infra/otel/runbooks.md#telemetry-backend diff --git a/infra/otel/prometheus-web.yaml b/infra/otel/prometheus-web.yaml new file mode 100644 index 0000000..396411e --- /dev/null +++ b/infra/otel/prometheus-web.yaml @@ -0,0 +1,8 @@ +tls_server_config: + cert_file: /run/pki/prometheus/tls.crt + key_file: /run/pki/prometheus/tls.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/pki/telemetry-client-ca/ca.crt + client_allowed_sans: + - spiffe://hla-lab7/grafana + min_version: TLS12 diff --git a/infra/otel/prometheus.yaml b/infra/otel/prometheus.yaml new file mode 100644 index 0000000..554c3b3 --- /dev/null +++ b/infra/otel/prometheus.yaml @@ -0,0 +1,17 @@ +global: + scrape_interval: 10s + evaluation_interval: 10s + +rule_files: + - /etc/prometheus/prometheus-alerts.yaml + +scrape_configs: + - job_name: otel-collector-exported-metrics + scheme: https + tls_config: + ca_file: /run/pki/service-ca/ca.crt + server_name: otel-collector + cert_file: /run/pki/prometheus-client/tls.crt + key_file: /run/pki/prometheus-client/tls.key + static_configs: + - targets: ["otel-collector:8889"] diff --git a/infra/otel/runbooks.md b/infra/otel/runbooks.md new file mode 100644 index 0000000..079db87 --- /dev/null +++ b/infra/otel/runbooks.md @@ -0,0 +1,27 @@ +# Runbooks + +## API high error rate + +1. In Grafana, compare the 5xx ratio with `db_client_*` pool metrics. +2. Open a failed server span in Tempo and inspect child JDBC/Redis/S3 spans. +3. Search Loki by the trace ID. Do not search by a user, chat or message ID. +4. Restore the failing dependency and confirm the alert resolves after the five-minute window. + +## Queue lag + +1. Check `messenger_queue_depth` and `messenger_queue_oldest_job_age_seconds`. +2. Check worker busy/capacity and the rate of `messenger_jobs_processed_total` by outcome. +3. Search worker errors in Loki, then open the linked consumer trace in Tempo. +4. Restore or scale the worker and confirm depth and age return to zero. + +## Worker saturation + +1. Compare busy/capacity with job duration p95 and container CPU/RAM. +2. Inspect slow consumer spans and their S3/JDBC children. +3. Remove the bottleneck before increasing concurrency; memory is explicitly bounded. + +## Telemetry backend + +1. Inspect Collector exporter failure and queue metrics on port 8888 through Prometheus. +2. Restore Loki or Tempo. Collector retries for at most 60 seconds with a 2048-item queue. +3. Confirm the application remained available; telemetry loss is allowed and bounded. diff --git a/infra/otel/tempo.yaml b/infra/otel/tempo.yaml new file mode 100644 index 0000000..5aa061a --- /dev/null +++ b/infra/otel/tempo.yaml @@ -0,0 +1,40 @@ +server: + http_listen_port: 3200 + http_tls_config: + cert_file: /run/pki/tempo/tls.crt + key_file: /run/pki/tempo/tls.key + client_auth_type: RequireAndVerifyClientCert + client_ca_file: /run/pki/telemetry-client-ca/ca.crt + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /run/pki/tempo/tls.crt + key_file: /run/pki/tempo/tls.key + client_ca_file: /run/pki/telemetry-client-ca/ca.crt + +live_store: + max_trace_idle: 10s + max_block_duration: 5m + wal: + path: /var/tempo/live-store/traces + +storage: + trace: + backend: local + local: + path: /var/tempo/blocks + +overrides: + defaults: + compaction: + block_retention: 72h + +usage_report: + reporting_enabled: false diff --git a/infra/postgres/01-roles.sh b/infra/postgres/01-roles.sh new file mode 100644 index 0000000..03c6dd5 --- /dev/null +++ b/infra/postgres/01-roles.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu +psql --set=ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \ + --set=api_password="$DATABASE_API_PASSWORD" \ + --set=worker_password="$DATABASE_WORKER_PASSWORD" \ + --set=migration_password="$DATABASE_MIGRATION_PASSWORD" <<'SQL' +CREATE ROLE messenger_api LOGIN PASSWORD :'api_password'; +CREATE ROLE messenger_worker LOGIN PASSWORD :'worker_password'; +CREATE ROLE messenger_migration LOGIN PASSWORD :'migration_password'; +GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_migration; +GRANT USAGE, CREATE ON SCHEMA public TO messenger_migration; +SQL diff --git a/infra/postgres/entrypoint-tls.sh b/infra/postgres/entrypoint-tls.sh new file mode 100644 index 0000000..cce7c5e --- /dev/null +++ b/infra/postgres/entrypoint-tls.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu +install -d -m 0700 -o postgres -g postgres /var/lib/postgresql/tls +install -m 0600 -o postgres -g postgres /run/pki/postgres/tls.key /var/lib/postgresql/tls/server.key +install -m 0644 -o postgres -g postgres /run/pki/postgres/tls.crt /var/lib/postgresql/tls/server.crt +exec docker-entrypoint.sh postgres \ + -c ssl=on \ + -c ssl_min_protocol_version=TLSv1.2 \ + -c ssl_cert_file=/var/lib/postgresql/tls/server.crt \ + -c ssl_key_file=/var/lib/postgresql/tls/server.key \ + -c hba_file=/etc/postgresql/pg_hba.conf diff --git a/infra/postgres/pg_hba.conf b/infra/postgres/pg_hba.conf new file mode 100644 index 0000000..583e7b2 --- /dev/null +++ b/infra/postgres/pg_hba.conf @@ -0,0 +1,5 @@ +local all all trust +hostnossl all all 0.0.0.0/0 reject +hostnossl all all ::0/0 reject +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::0/0 scram-sha-256 diff --git a/infra/rabbitmq/rabbitmq.conf b/infra/rabbitmq/rabbitmq.conf new file mode 100644 index 0000000..666952e --- /dev/null +++ b/infra/rabbitmq/rabbitmq.conf @@ -0,0 +1,14 @@ +listeners.tcp = none +listeners.ssl.default = 5671 +ssl_options.cacertfile = /run/pki/workload-client-ca/ca.crt +ssl_options.certfile = /run/pki/rabbitmq/tls.crt +ssl_options.keyfile = /run/pki/rabbitmq/tls.key +ssl_options.verify = verify_peer +ssl_options.fail_if_no_peer_cert = true +ssl_options.versions.1 = tlsv1.3 +ssl_options.versions.2 = tlsv1.2 +management.tcp.port = none +management.ssl.port = 15671 +management.ssl.cacertfile = /run/pki/service-ca/ca.crt +management.ssl.certfile = /run/pki/rabbitmq/tls.crt +management.ssl.keyfile = /run/pki/rabbitmq/tls.key diff --git a/scripts/bootstrap-openbao.ps1 b/scripts/bootstrap-openbao.ps1 new file mode 100644 index 0000000..1b81fd0 --- /dev/null +++ b/scripts/bootstrap-openbao.ps1 @@ -0,0 +1,66 @@ +[CmdletBinding()] +param([string]$EnvFile = '.env') + +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) { + throw 'Set BAO_TOKEN to the operator root token only for this bootstrap process.' +} + +$values = @{} +foreach($line in [System.IO.File]::ReadAllLines((Resolve-Path $EnvFile))) { + if($line -match '^(?[A-Z][A-Z0-9_]*)=(?.*)$') { $values[$Matches.name]=$Matches.value } +} +function Require-Value([string]$Name) { + if(-not $values.ContainsKey($Name) -or [string]::IsNullOrWhiteSpace($values[$Name])) { + throw "Missing $Name in $EnvFile" + } + return $values[$Name] +} +function Bao([Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) { + & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao @Arguments + if($LASTEXITCODE -ne 0){ throw "OpenBao command failed: bao $($Arguments -join ' ')" } +} + +& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao secrets enable -path=secret -version=2 kv 2>$null +if($LASTEXITCODE -ne 0) { Bao secrets list | Select-String 'secret/' | Out-Null } +& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao auth enable approle 2>$null +if($LASTEXITCODE -ne 0) { Bao auth list | Select-String 'approle/' | Out-Null } + +Bao policy write messenger-api /openbao/config/api-policy.hcl | Out-Null +Bao policy write messenger-worker /openbao/config/worker-policy.hcl | Out-Null +Bao write auth/approle/role/messenger-api token_policies=messenger-api token_ttl=15m token_max_ttl=1h token_num_uses=0 secret_id_ttl=24h secret_id_num_uses=0 | Out-Null +Bao write auth/approle/role/messenger-worker token_policies=messenger-worker token_ttl=15m token_max_ttl=1h token_num_uses=0 secret_id_ttl=24h secret_id_num_uses=0 | Out-Null + +$api = @{ + database_password = Require-Value DATABASE_API_PASSWORD + redis_password = Require-Value REDIS_API_PASSWORD + rabbitmq_password = Require-Value RABBITMQ_API_PASSWORD + s3_access_key_id = Require-Value S3_ACCESS_KEY_ID + s3_secret_access_key = Require-Value S3_SECRET_ACCESS_KEY +} | ConvertTo-Json -Compress +$worker = @{ + database_password = Require-Value DATABASE_WORKER_PASSWORD + redis_password = Require-Value REDIS_WORKER_PASSWORD + rabbitmq_password = Require-Value RABBITMQ_WORKER_PASSWORD + s3_access_key_id = Require-Value S3_WORKER_ACCESS_KEY_ID + s3_secret_access_key = Require-Value S3_WORKER_SECRET_ACCESS_KEY +} | ConvertTo-Json -Compress +$api | & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao kv put -mount=secret messenger/api - | Out-Null +if($LASTEXITCODE -ne 0){ throw 'Failed to write API secrets' } +$worker | & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao kv put -mount=secret messenger/worker - | Out-Null +if($LASTEXITCODE -ne 0){ throw 'Failed to write worker secrets' } + +foreach($role in 'api','worker') { + $roleName = "messenger-$role" + $dir = Join-Path 'secrets\openbao' $role + New-Item -ItemType Directory -Path $dir -Force | Out-Null + $roleId = (Bao read -field=role_id "auth/approle/role/$roleName/role-id" | Out-String).Trim() + $secretId = (Bao write -field=secret_id -f "auth/approle/role/$roleName/secret-id" | Out-String).Trim() + [System.IO.File]::WriteAllText((Join-Path $dir 'role-id'),$roleId,[System.Text.Encoding]::ASCII) + [System.IO.File]::WriteAllText((Join-Path $dir 'secret-id'),$secretId,[System.Text.Encoding]::ASCII) +} + +& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao audit enable file file_path=/openbao/data/audit.log 2>$null +if($LASTEXITCODE -ne 0) { Bao audit list | Select-String 'file/' | Out-Null } +Write-Host 'OpenBao policies, AppRoles, KV secrets and agent bootstrap files are ready. Secret values were not printed.' diff --git a/scripts/bootstrap-pki.ps1 b/scripts/bootstrap-pki.ps1 new file mode 100644 index 0000000..0f93c09 --- /dev/null +++ b/scripts/bootstrap-pki.ps1 @@ -0,0 +1,104 @@ +[CmdletBinding()] +param([string]$OutputDirectory, [int]$LeafValidityDays = 30) + +$ErrorActionPreference = 'Stop' +if ([string]::IsNullOrWhiteSpace($OutputDirectory)) { + $OutputDirectory = Join-Path $PSScriptRoot '..\secrets\pki' +} +New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null +$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path +$script:Cas = @{} + +function Write-Pem([string]$Path, [string]$Label, [byte[]]$Value) { + $base64 = [Convert]::ToBase64String($Value) + $lines = for($offset=0; $offset -lt $base64.Length; $offset+=64){ + $base64.Substring($offset,[Math]::Min(64,$base64.Length-$offset)) + } + $pem = "-----BEGIN $Label-----`n" + ($lines -join "`n") + "`n-----END $Label-----`n" + [System.IO.File]::WriteAllText($Path, $pem, [System.Text.Encoding]::ASCII) +} + +function Export-PrivateKey($Rsa) { + if ($null -ne $Rsa.PSObject.Methods['ExportPkcs8PrivateKey']) { + return $Rsa.ExportPkcs8PrivateKey() + } + return $Rsa.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob) +} + +function New-Ca([string]$Name) { + $rsa = [System.Security.Cryptography.RSA]::Create(3072) + $request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new( + "CN=HLA Lab 7 $Name", $rsa, + [System.Security.Cryptography.HashAlgorithmName]::SHA256, + [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) + $request.CertificateExtensions.Add( + [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($true,$false,0,$true)) + $request.CertificateExtensions.Add( + [System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new( + [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyCertSign -bor + [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::CrlSign,$true)) + $certificate = $request.CreateSelfSigned([DateTimeOffset]::UtcNow.AddMinutes(-5),[DateTimeOffset]::UtcNow.AddDays(365)) + $dir = Join-Path $OutputDirectory $Name + New-Item -ItemType Directory -Path $dir -Force | Out-Null + Write-Pem (Join-Path $dir 'ca.crt') 'CERTIFICATE' $certificate.Export( + [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) + Write-Pem (Join-Path $dir 'ca.key') 'PRIVATE KEY' (Export-PrivateKey $rsa) + $script:Cas[$Name] = $certificate +} + +function New-Leaf( + [string]$Name, [string]$CaName, [bool]$ServerAuth, + [string[]]$DnsNames, [string[]]$IpAddresses, [string[]]$Uris) { + $rsa = [System.Security.Cryptography.RSA]::Create(3072) + $request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new( + "CN=$Name",$rsa,[System.Security.Cryptography.HashAlgorithmName]::SHA256, + [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) + $request.CertificateExtensions.Add( + [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($false,$false,0,$true)) + $request.CertificateExtensions.Add( + [System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new( + [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DigitalSignature -bor + [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment,$true)) + $eku = [System.Security.Cryptography.OidCollection]::new() + [void]$eku.Add([System.Security.Cryptography.Oid]::new($(if($ServerAuth){'1.3.6.1.5.5.7.3.1'}else{'1.3.6.1.5.5.7.3.2'}))) + $request.CertificateExtensions.Add( + [System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($eku,$false)) + $san = [System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder]::new() + foreach($dns in $DnsNames){ $san.AddDnsName($dns) } + foreach($ip in $IpAddresses){ $san.AddIpAddress([System.Net.IPAddress]::Parse($ip)) } + foreach($uri in $Uris){ $san.AddUri([Uri]::new($uri)) } + $request.CertificateExtensions.Add($san.Build($true)) + $serial = [byte[]]::new(16) + $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create() + $rng.GetBytes($serial) + $rng.Dispose() + $serial[0] = $serial[0] -band 0x7f + $signed = $request.Create($script:Cas[$CaName],[DateTimeOffset]::UtcNow.AddMinutes(-5), + [DateTimeOffset]::UtcNow.AddDays($LeafValidityDays),$serial) + $certificate = $signed + $dir = Join-Path $OutputDirectory $Name + New-Item -ItemType Directory -Path $dir -Force | Out-Null + Write-Pem (Join-Path $dir 'tls.crt') 'CERTIFICATE' $certificate.Export( + [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) + Write-Pem (Join-Path $dir 'tls.key') 'PRIVATE KEY' (Export-PrivateKey $rsa) + Copy-Item (Join-Path $OutputDirectory "$CaName\ca.crt") (Join-Path $dir 'ca.crt') -Force +} + +foreach($name in 'public-ca','service-ca','lb-client-ca','workload-client-ca','telemetry-client-ca'){ New-Ca $name } +New-Leaf 'ingress' 'public-ca' $true @('localhost') @('127.0.0.1') @() +foreach($name in 'api','postgres','redis','rabbitmq','minio','otel-collector','prometheus','loki','tempo'){ + New-Leaf $name 'service-ca' $true @($name) @() @("spiffe://hla-lab7/$name") +} +New-Leaf 'openbao' 'service-ca' $true @('openbao','localhost') @('127.0.0.1') @('spiffe://hla-lab7/openbao') +New-Leaf 'grafana' 'service-ca' $true @('grafana','localhost') @('127.0.0.1') @('spiffe://hla-lab7/grafana') +New-Leaf 'lb' 'lb-client-ca' $false @() @() @('spiffe://hla-lab7/lb') +New-Leaf 'wrong-lb-client' 'lb-client-ca' $false @() @() @('spiffe://hla-lab7/worker') +New-Leaf 'api-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/api') +New-Leaf 'worker-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/worker') +New-Leaf 'migration-client' 'workload-client-ca' $false @() @() @('spiffe://hla-lab7/migration') +New-Leaf 'collector-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/otel-collector') +New-Leaf 'prometheus-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/prometheus') +New-Leaf 'grafana-client' 'telemetry-client-ca' $false @() @() @('spiffe://hla-lab7/grafana') + +Write-Host "Created private PKI in $OutputDirectory" +Write-Host "Public test CA: $(Join-Path $OutputDirectory 'public-ca\ca.crt')" diff --git a/scripts/bootstrap-secrets.ps1 b/scripts/bootstrap-secrets.ps1 new file mode 100644 index 0000000..8b8e177 --- /dev/null +++ b/scripts/bootstrap-secrets.ps1 @@ -0,0 +1,28 @@ +[CmdletBinding()] +param([string]$Destination, [switch]$Force) + +$ErrorActionPreference = 'Stop' +if ([string]::IsNullOrWhiteSpace($Destination)) { + $Destination = Join-Path $PSScriptRoot '..\.env' +} +if ((Test-Path -LiteralPath $Destination) -and -not $Force) { + throw "$Destination already exists; use -Force only for an intentional full credential rotation" +} +$template = Join-Path $PSScriptRoot '..\.env.example' +$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create() +try { + $lines = foreach($line in [System.IO.File]::ReadAllLines($template)) { + if ($line -match '^(?[A-Z][A-Z0-9_]*)=replace-with-') { + $bytes = [byte[]]::new(32) + $rng.GetBytes($bytes) + $secret = [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_') + "$($Matches.name)=$secret" + } else { + $line + } + } +} finally { + $rng.Dispose() +} +[System.IO.File]::WriteAllLines($Destination,$lines,[System.Text.UTF8Encoding]::new($false)) +Write-Host "Created local stand credentials in $Destination; values were not printed." diff --git a/scripts/bootstrap-tls.ps1 b/scripts/bootstrap-tls.ps1 new file mode 100644 index 0000000..2239a43 --- /dev/null +++ b/scripts/bootstrap-tls.ps1 @@ -0,0 +1,40 @@ +[CmdletBinding()] +param( + [string]$OutputDirectory = (Join-Path $PSScriptRoot '..\secrets\tls'), + [int]$ValidityDays = 30 +) + +$ErrorActionPreference = 'Stop' + +if (-not (Get-Command openssl -ErrorAction SilentlyContinue)) { + throw 'openssl is required and was not found in PATH' +} + +New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null +$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path + +$caKey = Join-Path $OutputDirectory 'ca.key' +$caCert = Join-Path $OutputDirectory 'ca.crt' +$serverKey = Join-Path $OutputDirectory 'server.key' +$serverCsr = Join-Path $OutputDirectory 'server.csr' +$serverCert = Join-Path $OutputDirectory 'server.crt' +$extensions = Join-Path $OutputDirectory 'server.ext' + +@' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature,keyEncipherment +extendedKeyUsage=serverAuth +subjectAltName=DNS:localhost,IP:127.0.0.1 +'@ | Set-Content -LiteralPath $extensions -Encoding ascii + +& openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out $caKey +& openssl req -x509 -new -sha256 -key $caKey -days $ValidityDays ` + -subj '/CN=HLA Lab 7 Local CA' -out $caCert +& openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out $serverKey +& openssl req -new -sha256 -key $serverKey -subj '/CN=localhost' -out $serverCsr +& openssl x509 -req -sha256 -in $serverCsr -CA $caCert -CAkey $caKey ` + -CAcreateserial -days $ValidityDays -extfile $extensions -out $serverCert + +Remove-Item -LiteralPath $serverCsr, $extensions, (Join-Path $OutputDirectory 'ca.srl') -Force -ErrorAction SilentlyContinue +Write-Host "Created local TLS material in $OutputDirectory" +Write-Host "Trust this CA only for the lab: $caCert" diff --git a/scripts/bootstrap-tls.sh b/scripts/bootstrap-tls.sh new file mode 100644 index 0000000..1f543cf --- /dev/null +++ b/scripts/bootstrap-tls.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env sh +set -eu + +repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out_dir=${1:-"$repo_dir/secrets/tls"} +days=${TLS_VALIDITY_DAYS:-30} + +command -v openssl >/dev/null 2>&1 || { + echo 'openssl is required and was not found in PATH' >&2 + exit 1 +} + +mkdir -p "$out_dir" +umask 077 + +cat >"$out_dir/server.ext" <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature,keyEncipherment +extendedKeyUsage=serverAuth +subjectAltName=DNS:localhost,IP:127.0.0.1 +EOF + +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$out_dir/ca.key" +openssl req -x509 -new -sha256 -key "$out_dir/ca.key" -days "$days" \ + -subj '/CN=HLA Lab 7 Local CA' -out "$out_dir/ca.crt" +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$out_dir/server.key" +openssl req -new -sha256 -key "$out_dir/server.key" -subj '/CN=localhost' -out "$out_dir/server.csr" +openssl x509 -req -sha256 -in "$out_dir/server.csr" -CA "$out_dir/ca.crt" \ + -CAkey "$out_dir/ca.key" -CAcreateserial -days "$days" \ + -extfile "$out_dir/server.ext" -out "$out_dir/server.crt" + +rm -f "$out_dir/server.csr" "$out_dir/server.ext" "$out_dir/ca.srl" +printf 'Created local TLS material in %s\n' "$out_dir" +printf 'Trust this CA only for the lab: %s/ca.crt\n' "$out_dir" diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 0000000..ddc596a --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,10 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." +if not defined ENV_FILE set "ENV_FILE=.env" + +docker compose --env-file "%ENV_FILE%" stop nginx api redis postgres minio || exit /b 1 +docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio || exit /b 1 +docker compose --env-file "%ENV_FILE%" run --rm minio-init || exit /b 1 +docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api || exit /b 1 +docker compose --env-file "%ENV_FILE%" up -d --no-deps nginx || exit /b 1 diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..d8a5cec --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" +: "${ENV_FILE:=.env}" + +# Preserve named volumes and the network. The migration job is intentionally +# not re-run during a same-version restart. +docker compose --env-file "$ENV_FILE" stop nginx api redis postgres minio +docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio +docker compose --env-file "$ENV_FILE" run --rm minio-init +docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api +docker compose --env-file "$ENV_FILE" up -d --no-deps nginx diff --git a/scripts/rotate-openbao-secret-ids.ps1 b/scripts/rotate-openbao-secret-ids.ps1 new file mode 100644 index 0000000..1c4c00a --- /dev/null +++ b/scripts/rotate-openbao-secret-ids.ps1 @@ -0,0 +1,13 @@ +[CmdletBinding()] +param([string]$EnvFile = '.env') + +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') +if ([string]::IsNullOrWhiteSpace($env:BAO_TOKEN)) { throw 'Set BAO_TOKEN for this operator action.' } +foreach($role in 'api','worker') { + $roleName = "messenger-$role" + $secretId = (& docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$env:BAO_TOKEN" openbao bao write -field=secret_id -f "auth/approle/role/$roleName/secret-id" | Out-String).Trim() + if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($secretId)){ throw "Failed to rotate $roleName SecretID" } + [System.IO.File]::WriteAllText((Join-Path "secrets\openbao\$role" 'secret-id'),$secretId,[System.Text.Encoding]::ASCII) +} +Write-Host 'AppRole SecretIDs rotated without printing their values.' diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 0000000..1137fb8 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,26 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +if "%TARGET_INSTANCE_ID%"=="" exit /b 2 +cd /d "%~dp0\.." +if not defined ENV_FILE set "ENV_FILE=.env" + +set "TARGET_CONTAINER=" +set /a MATCHES=0 +for /f "usebackq delims=" %%C in (`docker compose --env-file "%ENV_FILE%" ps -q api`) do ( + set "CONTAINER_ID=%%C" + set "SHORT_ID=!CONTAINER_ID:~0,12!" + set "HOSTNAME_VALUE=" + for /f "usebackq delims=" %%H in (`docker inspect --format "{{.Config.Hostname}}" %%C`) do set "HOSTNAME_VALUE=%%H" + if "!HOSTNAME_VALUE!"=="%TARGET_INSTANCE_ID%" ( + set "TARGET_CONTAINER=%%C" + set /a MATCHES+=1 + ) else if "!SHORT_ID!"=="%TARGET_INSTANCE_ID%" ( + set "TARGET_CONTAINER=%%C" + set /a MATCHES+=1 + ) +) + +if not "!MATCHES!"=="1" exit /b 2 +docker stop --time 5 "!TARGET_CONTAINER!" >nul +exit /b %ERRORLEVEL% diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..19370e1 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,29 @@ +#!/bin/sh +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" +: "${ENV_FILE:=.env}" + +target="" +matches=0 +for container_id in $(docker compose --env-file "$ENV_FILE" ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id") + short_id=$(printf '%s' "$container_id" | cut -c1-12) + if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$short_id" ]; then + target=$container_id + matches=$((matches + 1)) + fi +done + +if [ "$matches" -ne 1 ]; then + printf '%s\n' "Expected one API replica for X-Instance-Id, found $matches" >&2 + exit 2 +fi + +# Five seconds keeps the operator hook below the test's ten-second budget while +# still delivering SIGTERM and allowing Spring's graceful shutdown phase. +docker stop --time 5 "$target" >/dev/null diff --git a/scripts/test-mtls.ps1 b/scripts/test-mtls.ps1 new file mode 100644 index 0000000..096ad9b --- /dev/null +++ b/scripts/test-mtls.ps1 @@ -0,0 +1,25 @@ +[CmdletBinding()] +param([string]$EnvFile = '.env') + +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') + +function Invoke-Probe([string]$TlsArguments) { + $script = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -connect api:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1" + $output = docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script + return ($output -join "`n") +} + +$noCertificate = Invoke-Probe '' +if ($noCertificate -match 'HTTP/1.1 200') { throw 'mTLS failure: API accepted a client without a certificate' } + +$foreignCa = Invoke-Probe '-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key' +if ($foreignCa -match 'HTTP/1.1 200') { throw 'mTLS failure: API accepted a foreign client CA' } + +$wrongIdentity = Invoke-Probe '-cert /run/pki/wrong-lb-client/tls.crt -key /run/pki/wrong-lb-client/tls.key' +if ($wrongIdentity -notmatch 'HTTP/1.1 403') { throw 'mTLS failure: trusted CA with forbidden SAN was not rejected with 403' } + +$allowed = Invoke-Probe '-cert /run/pki/lb/tls.crt -key /run/pki/lb/tls.key' +if ($allowed -notmatch 'HTTP/1.1 200') { throw 'mTLS failure: allowed LB identity did not reach API health' } + +Write-Host 'PASS: no cert, foreign CA and forbidden SAN rejected; LB identity accepted.' diff --git a/scripts/test-openbao-policies.ps1 b/scripts/test-openbao-policies.ps1 new file mode 100644 index 0000000..0e07dad --- /dev/null +++ b/scripts/test-openbao-policies.ps1 @@ -0,0 +1,30 @@ +[CmdletBinding()] +param([string]$EnvFile = '.env') + +$ErrorActionPreference = 'Stop' +Set-Location (Join-Path $PSScriptRoot '..') + +function Get-AppRoleToken([string]$Role) { + $dir = Join-Path 'secrets\openbao' $Role + $roleId = [System.IO.File]::ReadAllText((Join-Path $dir 'role-id')).Trim() + $secretId = [System.IO.File]::ReadAllText((Join-Path $dir 'secret-id')).Trim() + $body = @{ role_id = $roleId; secret_id = $secretId } | ConvertTo-Json -Compress + $token = ($body | & docker compose --env-file $EnvFile exec -T openbao bao write -field=token auth/approle/login - | Out-String).Trim() + if($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) { throw "AppRole login failed for $Role" } + return $token +} + +function Bao-WithToken([string]$Token,[Parameter(ValueFromRemainingArguments=$true)][string[]]$Arguments) { + & docker compose --env-file $EnvFile exec -T -e "BAO_TOKEN=$Token" openbao bao @Arguments 2>$null | Out-Null + return $LASTEXITCODE +} + +foreach($role in 'api','worker') { + $other = if($role -eq 'api'){'worker'}else{'api'} + $token = Get-AppRoleToken $role + if((Bao-WithToken $token kv get -mount=secret "messenger/$role") -ne 0) { throw "$role cannot read its own KV path" } + if((Bao-WithToken $token kv get -mount=secret "messenger/$other") -eq 0) { throw "$role unexpectedly read the $other KV path" } + if((Bao-WithToken $token policy write forbidden /openbao/config/api-policy.hcl) -eq 0) { throw "$role unexpectedly changed an OpenBao policy" } +} + +Write-Host 'OpenBao policy checks passed: own path allowed; foreign path and policy changes denied.' diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..33a0ca4 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,109 @@ -# Модель угроз — заполнить +# Модель угроз HLA Lab 7 -## Активы и акторы +## Область и допущения -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +Модель относится к локальному учебному стенду из `compose.yaml`: клиент, nginx ingress, две и более реплики API, worker, PostgreSQL, Redis, RabbitMQ, MinIO, OpenTelemetry Collector, Prometheus/Loki/Tempo, Grafana и OpenBao. Хост Docker и рабочее место оператора считаются доверенной административной зоной. Компрометация ядра хоста, Docker daemon или учётной записи оператора находится за границей модели, но последствия ограничиваются раздельными credentials, непривилегированными контейнерами, отсутствием Docker socket и возможностью ротации. -## Границы доверия +Документ различает фактическое состояние и целевой контракт. Контроль с пометкой **GAP** ещё не реализован и не считается доказательством защищённости. Полное описание соединений и отрицательных проверок находится в [`contracts/trust-matrix.md`](../contracts/trust-matrix.md). -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +## Активы + +| Актив | Требование защиты | Источник истины / владелец | +| --- | --- | --- | +| Пароли пользователей | Конфиденциальность; Argon2id hash с уникальной солью и параметрами | PostgreSQL; API | +| Bearer-сессии | Непредсказуемость, ограниченный TTL, отзыв; plaintext выдаётся один раз | SHA-256 token hash в PostgreSQL; API | +| Чаты, сообщения и metadata вложений | Доступ только участникам соответствующего чата; целостность и порядок | PostgreSQL | +| Оригиналы и варианты вложений | Конфиденциальность bucket, целостность объекта, запрет cross-chat доступа | MinIO; API/worker | +| Очередь заданий и lease/outbox | Нельзя подделать задание или подтвердить чужой lease; at-least-once без потери | PostgreSQL + RabbitMQ | +| Service identities и credentials | Минимальные права, раздельность API/worker/operator, отзыв и ротация | OpenBao/локальный bootstrap; оператор | +| CA private keys, leaf keys, root token, unseal shares | Не попадают в Git, image, env/logs/telemetry; доступны только оператору | Вне Git; оператор | +| Telemetry | Не содержит Authorization, tokens, пароли, тела сообщений/файлов; write/read разделены | Collector и telemetry backends | +| Доступность | Деградации не приводят к обходу auth/TLS или повреждению данных | Весь стенд; оператор | + +## Акторы и возможности + +| Актор | Разрешённые действия | Потенциально враждебные возможности | +| --- | --- | --- | +| Участник чата | Работает со своими сессиями и чатами, загружает допустимые изображения | Меняет UUID, заголовки, cursor/idempotency key, MIME/размер файла, повторяет запросы | +| Аутентифицированный посторонний | Создаёт собственные чаты и сообщения | Пытается читать/изменять чужой чат и вложение, прикрепить чужой attachment | +| Внешний клиент без сессии | Регистрация, login и health через HTTPS | MITM, credential stuffing, malformed/oversized requests, недоверенный CA/hostname | +| Скомпрометированный API/worker | Действует с identity и сетевым доступом одного сервиса | Читает чужие secret paths, bucket prefixes, очереди или БД; шлёт ложную telemetry | +| Скомпрометированный внутренний контейнер | Имеет адрес в Docker-сети, но не service credential | Сканирует порты, пытается обойти ingress и подключиться без mTLS | +| Оператор | Init/unseal, bootstrap, выдача/отзыв identities, резервирование и аудит | Ошибка конфигурации или утечка bootstrap material — максимальный риск стенда | + +## Границы доверия и потоки + +```text +Internet/local client + │ HTTPS :8443, public CA + hostname, Bearer + ▼ +nginx ingress (DMZ) + │ target: mTLS, client SAN spiffe://hla-lab7/lb + ▼ +API replicas ── TLS/ACL ── PostgreSQL / Redis / MinIO / RabbitMQ + │ ▲ │ + └──── TLS/mTLS ── Collector │ ▼ + │ └────────────── worker + └── TLS ── Prometheus/Loki/Tempo ── TLS ── Grafana + +API / worker ── TLS + service auth ── OpenBao +Operator ── loopback/protected channel ── admin planes +``` + +1. **Публичная:** клиент → nginx. Единственный публикуемый business endpoint — `127.0.0.1:8443` в локальном профиле. Проверяются CA и SAN `localhost`. +2. **DMZ → application:** nginx → API использует обязательный mTLS, отдельный LB client CA и allowlist URI SAN `spiffe://hla-lab7/lb`; API port не публикуется. +3. **Application → data plane:** PostgreSQL, Redis, MinIO и RabbitMQ принимают TLS; API/worker имеют раздельные DB/cache/broker/S3 identities. Prefix-specific S3 policy остаётся улучшением. +4. **Application → telemetry:** API/worker пишут в Collector по mTLS с раздельными leaf identities; Collector, Prometheus и Grafana также используют отдельные mTLS identities для backend-связей. Redaction processor удаляет известные чувствительные поля. +5. **Secrets control plane:** отдельные API/worker Agents → OpenBao по TLS с разными AppRole и scoped policy; credentials передаются приложениям через разные read-only runtime volumes. +6. **Administrative:** operator → OpenBao/Grafana/MinIO admin. Интерфейсы не публикуются наружу; локальные Grafana/telemetry ports bound к loopback. + +## Инварианты безопасности и угрозы | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | - -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +| MITM подменяет ingress certificate или используется неверный hostname | Basic/Bearer передаются только аутентифицированному ingress | TLS 1.2/1.3, локальный CA, SAN `localhost`, hostname verification, без `-k` | `make test-security CA_FILE=secrets/tls/ca.crt`; пустой/чужой CA и wrong hostname → certificate error | Ручная установка CA — bootstrap trust; компрометация CA требует ротации | +| Внутренний контейнер обращается к API, минуя nginx | Business API доступен только доверенному LB | API TLS `client-auth=need`, отдельный LB CA и точный allowlist SAN `spiffe://hla-lab7/lb`; порт не публикуется | `scripts/test-mtls.ps1`: no cert/foreign CA/wrong SAN rejected; LB accepted | Компрометация LB key требует немедленного отзыва/ротации | +| Пользователь меняет `X-User-Id` или UUID и читает чужой чат/attachment | Identity определяется Bearer; membership проверяется сервером | Stateless auth filter, token hash lookup, repository membership predicates и FK | Bob + Alice UUID → 404/401; forged `X-User-Id` не меняет результат | Ошибки намеренно не различают отсутствие объекта и отсутствие прав | +| Пользователь прикрепляет чужой attachment или читает object key напрямую | Attachment принадлежит тому же чату; bucket private | Membership/ownership/chat validation, private bucket, opaque keys | Загрузить в чат A, попытаться attach/read из B; anonymous `mc ls/cp` → denied | Компрометация S3 credential даёт доступ в пределах его policy | +| Credential stuffing на login истощает CPU Argon2id | Login bounded; ответ не раскрывает существование user | Argon2id, dummy hash; общий Redis fixed-window limit по username/source, fail-closed, 429/Retry-After | Серия неверных login через разные replicas → 429; existing/unknown user имеют одинаковый класс ответа | Fixed window допускает burst на границе окна; source limit видит адрес ingress до завершения trusted-proxy модели | +| Кража БД раскрывает пароль или активный bearer token | В БД нет plaintext password/session token | Argon2id password hash; SHA-256 session token hash; TTL/logout | Проверить `$argon2id$`; plaintext token отсутствует; после logout/expiry token → 401 | Offline guessing зависит от качества пароля и измеренных Argon2 параметров | +| Скомпрометированный worker читает users/sessions или admin bucket/queue | Worker видит только jobs и нужные storage operations | Отдельные DB role, S3 key, RabbitMQ/Redis cert+user+ACL; отдельная OpenBao AppRole читает только worker KV | Worker: `SELECT password_hash`, MinIO admin, запрещённый broker route и API KV → denied | MinIO API/worker пока используют одинаковую bucket policy, хотя keys различаются | +| Поддельный RabbitMQ job или подтверждение чужой работы | Producer/consumer identities и ACL различаются | mTLS `5671`, отдельные cert/users/regex permissions; plaintext listener disabled; DB lease fencing | No cert/foreign CA → TLS отказ; запрещённая broker operation → access refused | Точная проверка URI SAN выполняется ACL user mapping, не самим Rabbit TLS listener | +| Внутренний контейнер шлёт фальшивую telemetry или читает backends | Только заявленные workload identities могут ingest/query | mTLS на workload→Collector, Collector→Loki/Tempo, Prometheus→Collector и Grafana→backends; отдельные certs; redaction | No cert/foreign CA rejected; Prometheus разрешает exact Grafana SAN; canary отсутствует в telemetry | Single-tenant Loki/Tempo не дают fine-grained query ACL сверх mTLS role | +| Authorization/password/body попадает в signals | Telemetry не содержит credentials/payload | OTel capture headers/bodies выключен; Collector удаляет auth, bodies, DB parameters/query | Запрос с уникальным canary; поиск в Loki/Tempo/Prometheus/logs → 0 | Новые instrumentation attributes требуют повторного canary-теста | +| Image bomb или concurrent uploads исчерпывают worker | Файл и суммарная обработка имеют bounds | 10 MiB limit, pixel limit, semaphore, worker memory budget, timeout/resources | Oversized body → 413; >40M pixels → reject/failed; concurrent test остаётся в limit | Decoder CVE остаются supply-chain риском; нужны scan/upgrade | +| Private key/secret попадает в Git, image или app env | Operator secrets не поставляются со skeleton | `.gitignore`, `.dockerignore`, local bootstrap в `secrets/`, OpenBao Agent и отдельные runtime files | Secret scanner, `docker history`, inspect app env не содержат root/unseal/runtime password | Dependency bootstrap passwords пока поступают их контейнерам через Compose env; это остаточный локальный риск | +| OpenBao sealed, приложение использует hardcoded fallback/plaintext | Отказ secret plane не ослабляет auth/TLS | Agent retry, отсутствие app fallback, controlled startup failure без rendered file; TLS не отключается | Seal/stop Bao; новая replica не стартует без файла; после unseal Agent re-auth | Уже запущенное приложение продолжает работать со статическими dependency credentials до restart/их отзыва | ## Lifecycle и инциденты -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +### Bootstrap + +1. Оператор на доверенном хосте создаёт CA/leaf keys и initial OpenBao material. Private keys, root token, unseal shares и SecretID находятся вне Git; `secrets/` имеет минимальные filesystem permissions. +2. OpenBao запускается не в dev-mode с persistent storage. Init выполняется один раз. Unseal shares разделяются между владельцами; root token используется только для bootstrap/recovery. +3. Оператор включает KV v2, создаёт отдельные policies/auth roles `messenger-api` и `messenger-worker`. SecretID имеет TTL 24 h и хранится только в игнорируемом локальном bootstrap mount; постоянного `BAO_TOKEN` в Compose нет. +4. Сервисы получают короткоживущие tokens, читают только свои paths и запускаются после проверки TLS/server identity. Миграции используют отдельную `migration` role. + +Шаги реализованы конфигурацией Compose, policy/bootstrap scripts и Agents. Init/unseal намеренно остаются ручной обязанностью оператора; runtime доказательство выполняется на initialized стенде скриптом `test-openbao-policies.ps1`. + +### Сроки и ротация + +- User session: `SESSION_TTL_SECONDS`, по умолчанию 3600 s; logout немедленно помечает token hash revoked. +- TLS leaf: целевой TTL 30 дней; renewal начинается не позднее 2/3 TTL. CA ротируется overlap-набором trust anchors. +- OpenBao service token: целевой TTL 15 min, renewable до max TTL 1 h, затем повторная service authentication. +- Static service credential на уровне 3: новая KV version, последовательный reload/restart клиентов, проверка новых соединений, отзыв старой версии. + +### Компрометация identity + +1. Изолировать сервис и зафиксировать время/serial/accessor без публикации secret value. +2. Отозвать leaf/OpenBao token и связанные DB/S3/broker credentials; закрыть pooled connections или дождаться измеренного TTL. +3. Выдать новую identity, перезапустить только затронутые replicas, выполнить allow/deny и integrity checks. +4. Проверить audit/telemetry на чужие paths/prefixes; при компрометации CA выполнить staged rollover. + +### Sealed OpenBao и восстановление + +Обычный restart сохраняет storage, но требует operator unseal в принятой ручной модели. Пока sealed, сервисы не получают новые leases, не используют root token и не переходят на `.env` fallback. После unseal agents повторяют auth с backoff, обновляют file-rendered secrets атомарно, приложения пересоздают соединения. RTO и поведение до expiry фиксируются экспериментом. + +### Dependency/image scan + +Для каждого High/Critical finding фиксируются package/version, достижимость кода в данной конфигурации, наличие fix, срок обновления и временный контроль. Одно количество CVE не является доказательством. Неприменимость подтверждается отсутствием component/code path или выключенной feature, а не только закрытым портом. diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d8f971a --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mtusi-messenger' diff --git a/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java b/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java new file mode 100644 index 0000000..4e0eb36 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java @@ -0,0 +1,20 @@ +package com.example.mtusi_messenger; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +public class MtusiMessengerApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run( + MtusiMessengerApplication.class, args); + if (Boolean.parseBoolean(System.getenv("MIGRATE_ONLY"))) { + System.exit(SpringApplication.exit(context)); + } + } + +} diff --git a/src/main/java/com/example/mtusi_messenger/cache/UserCache.java b/src/main/java/com/example/mtusi_messenger/cache/UserCache.java new file mode 100644 index 0000000..04ad803 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/cache/UserCache.java @@ -0,0 +1,83 @@ +package com.example.mtusi_messenger.cache; + +import com.example.mtusi_messenger.model.User; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; + +@Component +public class UserCache { + private static final Logger log = LoggerFactory.getLogger(UserCache.class); + private static final String KEY_PREFIX = "messenger:user:"; + + private final StringRedisTemplate redis; + private final ObjectMapper mapper; + private final Duration ttl; + + public UserCache( + StringRedisTemplate redis, + ObjectMapper mapper, + @Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds + ) { + if (ttlSeconds <= 0) { + throw new IllegalArgumentException("User cache TTL must be positive"); + } + this.redis = redis; + this.mapper = mapper; + this.ttl = Duration.ofSeconds(ttlSeconds); + } + + public Optional find(UUID userId) { + try { + String value = redis.opsForValue().get(key(userId)); + if (value == null) { + return Optional.empty(); + } + User cachedUser = mapper.readValue(value, User.class); + if (cachedUser == null) { + log.warn("Ignoring null Redis user cache entry for {}", userId); + evict(userId); + return Optional.empty(); + } + return Optional.of(cachedUser); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; using PostgreSQL fallback"); + return Optional.empty(); + } catch (JsonProcessingException e) { + log.warn("Ignoring malformed Redis user cache entry for {}", userId); + evict(userId); + return Optional.empty(); + } + } + + public void put(User user) { + try { + redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; user was not cached"); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot serialize user cache entry", e); + } + } + + public void evict(UUID userId) { + try { + redis.delete(key(userId)); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; cache eviction was skipped"); + } + } + + private String key(UUID userId) { + return KEY_PREFIX + userId; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java b/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java new file mode 100644 index 0000000..568a65e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java @@ -0,0 +1,28 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer; + +import tools.jackson.databind.cfg.CoercionAction; +import tools.jackson.databind.cfg.CoercionInputShape; +import tools.jackson.databind.type.LogicalType; + +@Configuration +public class JacksonConfig { + + @Bean + JsonMapperBuilderCustomizer strictStringTypes() { + return builder -> builder.withCoercionConfig( + LogicalType.Textual, + config -> { + config.setCoercion( + CoercionInputShape.Integer, CoercionAction.Fail); + config.setCoercion( + CoercionInputShape.Float, CoercionAction.Fail); + config.setCoercion( + CoercionInputShape.Boolean, CoercionAction.Fail); + } + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java b/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java new file mode 100644 index 0000000..14cc24f --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.config; + + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@SecurityScheme( + name = "basicAuth", + type = SecuritySchemeType.HTTP, + scheme = "basic" +) +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + scheme = "bearer", + bearerFormat = "opaque session token" +) +@Configuration +public class OpenApiConfig { +} diff --git a/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java b/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java new file mode 100644 index 0000000..f9572d1 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java @@ -0,0 +1,22 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordConfig { + @Bean + PasswordEncoder passwordEncoder( + @Value("${messenger.password.argon2.memory-kib:19456}") int memoryKiB, + @Value("${messenger.password.argon2.iterations:2}") int iterations, + @Value("${messenger.password.argon2.parallelism:1}") int parallelism + ) { + if (memoryKiB < 19456 || iterations < 2 || parallelism < 1) { + throw new IllegalArgumentException("Argon2id parameters are below the lab7 baseline"); + } + return new Argon2PasswordEncoder(16, 32, parallelism, memoryKiB, iterations); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java b/src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java new file mode 100644 index 0000000..ec334a9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/RabbitJobConfig.java @@ -0,0 +1,57 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RabbitJobConfig { + @Bean + DirectExchange attachmentExchange(@Value("${messenger.jobs.exchange}") String name) { + return new DirectExchange(name, true, false); + } + + @Bean + Queue attachmentQueue( + @Value("${messenger.jobs.queue}") String name, + @Value("${messenger.jobs.dead-letter-exchange}") String deadLetterExchange, + @Value("${messenger.jobs.dead-letter-routing-key}") String deadLetterRoutingKey) { + return QueueBuilder.durable(name) + .withArgument("x-dead-letter-exchange", deadLetterExchange) + .withArgument("x-dead-letter-routing-key", deadLetterRoutingKey) + .build(); + } + + @Bean + DirectExchange attachmentDeadLetterExchange( + @Value("${messenger.jobs.dead-letter-exchange}") String name) { + return new DirectExchange(name, true, false); + } + + @Bean + Queue attachmentDeadLetterQueue(@Value("${messenger.jobs.dead-letter-queue}") String name) { + return QueueBuilder.durable(name).build(); + } + + @Bean + Binding attachmentBinding( + @Qualifier("attachmentQueue") Queue attachmentQueue, + @Qualifier("attachmentExchange") DirectExchange attachmentExchange, + @Value("${messenger.jobs.routing-key}") String routingKey) { + return BindingBuilder.bind(attachmentQueue).to(attachmentExchange).with(routingKey); + } + + @Bean + Binding attachmentDeadLetterBinding( + @Qualifier("attachmentDeadLetterQueue") Queue queue, + @Qualifier("attachmentDeadLetterExchange") DirectExchange exchange, + @Value("${messenger.jobs.dead-letter-routing-key}") String routingKey) { + return BindingBuilder.bind(queue).to(exchange).with(routingKey); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java new file mode 100644 index 0000000..34720e6 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java @@ -0,0 +1,122 @@ +package com.example.mtusi_messenger.config; + +import com.example.mtusi_messenger.security.ApiAuthenticationFilter; +import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider; +import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint; +import com.example.mtusi_messenger.security.LoginRateLimiter; +import com.example.mtusi_messenger.security.TrustedClientCertificateFilter; +import com.example.mtusi_messenger.service.AuthenticationService; +import com.example.mtusi_messenger.web.ReadinessGuardFilter; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; + +@Configuration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +public class SecurityConfig { + @Bean + AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) { + return new ProviderManager(provider); + } + + @Bean + RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) { + return new RestAuthenticationEntryPoint( + mapper, + "Basic realm=\"messenger\", charset=\"UTF-8\""); + } + + @Bean + RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) { + return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\""); + } + + @Bean + ApiAuthenticationFilter apiAuthenticationFilter( + AuthenticationManager authenticationManager, + AuthenticationService authenticationService, + LoginRateLimiter loginRateLimiter, + @Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint, + @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint + ) { + return new ApiAuthenticationFilter( + authenticationManager, + authenticationService, + loginRateLimiter, + basicAuthenticationEntryPoint, + bearerAuthenticationEntryPoint); + } + + @Bean + FilterRegistrationBean disableServletFilterRegistration( + ApiAuthenticationFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + @Bean + FilterRegistrationBean disableReadinessGuardServletRegistration( + ReadinessGuardFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + @Bean + FilterRegistrationBean disableTrustedClientCertificateServletRegistration( + TrustedClientCertificateFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + @Bean + SecurityFilterChain securityFilterChain( + HttpSecurity http, + ApiAuthenticationFilter apiAuthenticationFilter, + ReadinessGuardFilter readinessGuardFilter, + TrustedClientCertificateFilter trustedClientCertificateFilter, + @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint + ) throws Exception { + http + .csrf(csrf -> csrf.disable()) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .logout(logout -> logout.disable()) + .requestCache(cache -> cache.disable()) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(errors -> errors + .authenticationEntryPoint(bearerAuthenticationEntryPoint)) + .authorizeHttpRequests(authorize -> authorize + .requestMatchers(HttpMethod.GET, "/health/**").permitAll() + .requestMatchers( + "/swagger-ui.html", + "/swagger-ui/**", + "/v3/api-docs/**" + ).permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll() + .anyRequest().authenticated()) + // Refuse business traffic before authentication touches storage. + // Nginx retries this 503 on another peer and passively excludes + // the refusing replica according to max_fails/fail_timeout. + .addFilterBefore(trustedClientCertificateFilter, AnonymousAuthenticationFilter.class) + .addFilterAfter(readinessGuardFilter, TrustedClientCertificateFilter.class) + .addFilterAfter(apiAuthenticationFilter, ReadinessGuardFilter.class); + return http.build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/WebConfig.java b/src/main/java/com/example/mtusi_messenger/config/WebConfig.java new file mode 100644 index 0000000..ac26bb3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/WebConfig.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebConfig { + @Bean + ObjectMapper objectMapper() { + return JsonMapper.builder().findAndAddModules() + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java b/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java new file mode 100644 index 0000000..72350f5 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/AttachmentController.java @@ -0,0 +1,75 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.dto.AttachmentResponse; +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.security.SessionPrincipal; +import com.example.mtusi_messenger.service.AttachmentService; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1") +@SecurityRequirement(name = "bearerAuth") +public class AttachmentController { + private final AttachmentService attachments; + + @PostMapping(value = "/chats/{chatId}/attachments", + consumes = {"image/png", "image/jpeg"}, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity upload( + @AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestParam String filename, + @RequestHeader(HttpHeaders.CONTENT_TYPE) String contentType, + HttpServletRequest request + ) throws IOException { + Attachment attachment = attachments.upload(parse(chatId), principal.user().id(), filename, + contentType, request.getContentLengthLong(), request.getInputStream()); + return ResponseEntity.status(HttpStatus.ACCEPTED).body(AttachmentResponse.from(attachment)); + } + + @GetMapping("/attachments/{attachmentId}") + public AttachmentResponse metadata( + @AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String attachmentId + ) { + return AttachmentResponse.from(attachments.getAccessible(parse(attachmentId), principal.user().id())); + } + + @GetMapping("/attachments/{attachmentId}/content") + public ResponseEntity download( + @AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String attachmentId, + @RequestParam(defaultValue = "original") String variant + ) { + AttachmentService.Download download = attachments.download( + parse(attachmentId), principal.user().id(), variant); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(download.contentType())) + .contentLength(download.bytes().length) + .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline() + .filename(download.filename(), StandardCharsets.UTF_8).build().toString()) + .body(download.bytes()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/ChatController.java b/src/main/java/com/example/mtusi_messenger/controller/ChatController.java new file mode 100644 index 0000000..ff02c9b --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/ChatController.java @@ -0,0 +1,83 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.service.ChatService; +import com.example.mtusi_messenger.security.SessionPrincipal; +import java.util.List; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RestController +@RequestMapping("/api/v1/chats") +@SecurityRequirement(name = "bearerAuth") +@RequiredArgsConstructor +public class ChatController { + + private final ChatService chats; + + @PostMapping + public ResponseEntity create(@AuthenticationPrincipal SessionPrincipal principal, + @Valid @RequestBody CreateChatRequest body + ) { + UUID userId = principal.user().id(); + Chat c = chats.create(body, userId); + return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c)); + } + + @GetMapping + public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal, + @RequestParam(required = false) String limit, + @RequestParam(required = false) String cursor + ) { + UUID userId = principal.user().id(); + int parsedLimit = validateLimit(limit); + validateCursorPresence(cursor); + List page = chats.page(userId, parsedLimit, cursor); + boolean hasNext = page.size() > parsedLimit; + if (hasNext) page = page.subList(0, parsedLimit); + return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null : + chats.nextCursor(userId, page.get(page.size() - 1), hasNext)); + } + + @GetMapping("/{chatId}") + public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId + ) { + UUID userId = principal.user().id(); + return ChatResponse.from(chats.getAccessible(parse(chatId), userId)); + } + + private static int validateLimit(String limit) { + if (limit == null) { + return 50; + } + if (!limit.matches("[0-9]+")) { + throw ApiExceptions.invalid("Invalid limit"); + } + try { + int value = Integer.parseInt(limit); + + if (value < 1 || value > 100) { + throw ApiExceptions.invalid("Invalid limit"); + } + + return value; + } catch (NumberFormatException ex) { + throw ApiExceptions.invalid("Invalid limit"); + } + } + + private static void validateCursorPresence(String c) { + if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/HealthController.java b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java new file mode 100644 index 0000000..e4bfec3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import com.example.mtusi_messenger.dto.HealthResponse; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.service.ReadinessService; + +@RestController +public class HealthController { + private final ReadinessService readiness; + + public HealthController(ReadinessService readiness) { + this.readiness = readiness; + } + + @GetMapping("/health/live") + public ResponseEntity live() { + return ResponseEntity.ok(new HealthResponse("ok")); + } + + @GetMapping("/health/ready") + public ResponseEntity ready() { + // Always probe dependencies, even after a failure, so a restored schema + // can move this process back to ACCEPTING_TRAFFIC without a restart. + if (!readiness.probeDependencies() || !readiness.acceptsBusinessTraffic()) { + throw ApiExceptions.unavailable("Application is not accepting traffic"); + } + return ResponseEntity.ok(new HealthResponse("ok")); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/MessageController.java b/src/main/java/com/example/mtusi_messenger/controller/MessageController.java new file mode 100644 index 0000000..e26c4cb --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/MessageController.java @@ -0,0 +1,79 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.service.MessageService; +import com.example.mtusi_messenger.security.SessionPrincipal; +import java.util.List; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1/chats/{chatId}/messages") +@SecurityRequirement(name = "bearerAuth") +public class MessageController { + private static final String IDEMPOTENCY_KEY_PATTERN = "[A-Za-z0-9._:-]{1,128}"; + private final MessageService messages; + + @PostMapping + public ResponseEntity create(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey, + @Valid @RequestBody CreateMessageRequest body + ) { + if (idempotencyKey == null || !idempotencyKey.matches(IDEMPOTENCY_KEY_PATTERN)) { + throw ApiExceptions.invalid("Invalid or missing Idempotency-Key"); + } + UUID userId = principal.user().id(); + UUID parsedChatId = parse(chatId); + Message m = messages.create(parsedChatId, userId, body, idempotencyKey); + return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m)); + } + + @GetMapping + public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestParam(required = false) String limit, + @RequestParam(required=false) String cursor + ) { + UUID userId = principal.user().id(); + UUID parsedChatId = parse(chatId); + int parsedLimit = validateLimit(limit); + if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + List page = messages.page(parsedChatId, userId, parsedLimit, cursor); + boolean hasNext = page.size() > parsedLimit; if (hasNext) page = page.subList(0, parsedLimit); + return new MessagePageResponse(page.stream().map(MessageResponse::from).toList(), + page.isEmpty() ? null : messages.nextCursor(parsedChatId, page.get(page.size()-1), hasNext)); + } + + private static int validateLimit(String limit) { + if (limit == null) { + return 50; + } + if (!limit.matches("[0-9]+")) { + throw ApiExceptions.invalid("Invalid limit"); + } + try { + int value = Integer.parseInt(limit); + + if (value < 1 || value > 100) { + throw ApiExceptions.invalid("Invalid limit"); + } + + return value; + } catch (NumberFormatException ex) { + throw ApiExceptions.invalid("Invalid limit"); + } + } + +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/SessionController.java b/src/main/java/com/example/mtusi_messenger/controller/SessionController.java new file mode 100644 index 0000000..f79528f --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/SessionController.java @@ -0,0 +1,41 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.dto.SessionResponse; +import com.example.mtusi_messenger.dto.UserResponse; +import com.example.mtusi_messenger.service.AuthenticationService; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.security.SessionPrincipal; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/auth/sessions") +@RequiredArgsConstructor +public class SessionController { + private final AuthenticationService authentication; + + @PostMapping + @SecurityRequirement(name = "basicAuth") + public ResponseEntity create(@AuthenticationPrincipal User user) { + var issued = authentication.issueSession(user); + return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse( + issued.token(), + "Bearer", + issued.expiresAt(), + UserResponse.from(issued.user()))); + } + + @DeleteMapping("/current") + @SecurityRequirement(name = "bearerAuth") + public ResponseEntity revoke(@AuthenticationPrincipal SessionPrincipal principal) { + authentication.revoke(principal); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/UserController.java b/src/main/java/com/example/mtusi_messenger/controller/UserController.java new file mode 100644 index 0000000..0d2d9cf --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/UserController.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.controller; + +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.service.UserService; +import com.example.mtusi_messenger.security.SessionPrincipal; + +@RestController +@RequestMapping("/api/v1/users") +@RequiredArgsConstructor +public class UserController { + + private final UserService users; + + @PostMapping + public ResponseEntity create(@Valid @RequestBody CreateUserRequest request) { + var user = users.create(request); + return ResponseEntity.status(HttpStatus.CREATED).body(UserResponse.from(user)); + } + + @GetMapping("/me") + @SecurityRequirement(name = "bearerAuth") + public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) { + return UserResponse.from(principal.user()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java b/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java new file mode 100644 index 0000000..7d7d2fa --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/AttachmentResponse.java @@ -0,0 +1,36 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Attachment; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record AttachmentResponse(UUID id, + UUID chat_id, + UUID owner_id, + String filename, + String content_type, + long size_bytes, + String sha256, + String status, + List variants, + String error_code, + Instant created_at, + Instant updated_at) { + public static AttachmentResponse from(Attachment attachment) { + return new AttachmentResponse( + attachment.id(), + attachment.chatId(), + attachment.ownerId(), + attachment.filename(), + attachment.contentType(), + attachment.sizeBytes(), + attachment.sha256(), + attachment.status(), + attachment.variants().stream().map(AttachmentVariantResponse::from).toList(), + attachment.errorCode(), + attachment.createdAt(), + attachment.updatedAt()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java b/src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java new file mode 100644 index 0000000..7bbdc3c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/AttachmentVariantResponse.java @@ -0,0 +1,16 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.AttachmentVariant; + +public record AttachmentVariantResponse(String name, + String content_type, + long size_bytes, + int width, + int height, + String sha256) { + public static AttachmentVariantResponse from(AttachmentVariant variant) { + return new AttachmentVariantResponse( + variant.name(), variant.contentType(), variant.sizeBytes(), + variant.width(), variant.height(), variant.sha256()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java new file mode 100644 index 0000000..e1d54bf --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import java.util.List; + +public record ChatPageResponse( + List items, + String next_cursor +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java new file mode 100644 index 0000000..96b2abb --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Chat; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record ChatResponse(UUID id, + String title, + List member_ids, + Instant created_at) { + public static ChatResponse from(Chat c) { + return new ChatResponse( + c.id(), + c.title(), + c.memberIds(), + c.createdAt()); } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java new file mode 100644 index 0000000..3f79234 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.Size; +import java.util.List; +import java.util.UUID; + +public record CreateChatRequest( + @NotUnicodeBlank + @UnicodeSize(min = 1, max = 100) + String title, + + @NotEmpty + @Size(min = 1, max = 100) + List member_ids +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java new file mode 100644 index 0000000..202f911 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java @@ -0,0 +1,31 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +import java.util.HashSet; +import java.util.List; +import java.util.UUID; + +public record CreateMessageRequest( + @NotNull @UnicodeSize(max = 4000) String text, + @Size(max = 10) List attachment_ids +) { + public CreateMessageRequest { + attachment_ids = attachment_ids == null ? List.of() : List.copyOf(attachment_ids); + } + + @AssertTrue(message = "text or attachment_ids must be present") + public boolean isContentPresent() { + return text != null && (!text.isBlank() || !attachment_ids.isEmpty()); + } + + @AssertTrue(message = "attachment_ids must be unique and non-null") + public boolean isAttachmentIdsValid() { + return attachment_ids != null + && attachment_ids.stream().noneMatch(java.util.Objects::isNull) + && new HashSet<>(attachment_ids).size() == attachment_ids.size(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java new file mode 100644 index 0000000..6d6e5a9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java @@ -0,0 +1,20 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; + +public record CreateUserRequest( + @NotBlank + @Pattern(regexp = "[a-z0-9_]{3,32}") + String username, + + @NotUnicodeBlank + @UnicodeSize(min = 1, max = 100) + String display_name, + + @NotUnicodeBlank + @UnicodeSize(min = 12, max = 128) + String password +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java new file mode 100644 index 0000000..4b1a2a9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +public record ErrorResponse(ErrorBody error) { + public record ErrorBody(String code, + String message, + String request_id) + {} +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java b/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java new file mode 100644 index 0000000..9630b10 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java @@ -0,0 +1,3 @@ +package com.example.mtusi_messenger.dto; + +public record HealthResponse(String status) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java new file mode 100644 index 0000000..db72eee --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import java.util.List; + +public record MessagePageResponse( + List items, + String next_cursor +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java new file mode 100644 index 0000000..2f59187 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java @@ -0,0 +1,22 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Message; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record MessageResponse(UUID id, + UUID chat_id, + UUID sender_id, + String text, + Instant created_at, + List attachment_ids) { + public static MessageResponse from(Message m) { + return new MessageResponse(m.id(), + m.chatId(), + m.senderId(), + m.text(), + m.createdAt(), + m.attachmentIds()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java b/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java new file mode 100644 index 0000000..64b54f9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java @@ -0,0 +1,10 @@ +package com.example.mtusi_messenger.dto; + +import java.time.Instant; + +public record SessionResponse( + String token, + String token_type, + Instant expires_at, + UserResponse user +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java b/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java new file mode 100644 index 0000000..e84bcb7 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.User; +import java.time.Instant; +import java.util.UUID; + +public record UserResponse(UUID id, + String username, + String display_name, + Instant created_at) { + public static UserResponse from(User u) { + return new UserResponse( + u.id(), + u.username(), + u.displayName(), + u.createdAt()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/exception/ApiException.java b/src/main/java/com/example/mtusi_messenger/exception/ApiException.java new file mode 100644 index 0000000..2c07f22 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/exception/ApiException.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.exception; + +import org.springframework.http.HttpStatus; + +public class ApiException extends RuntimeException { + private final String code; private final HttpStatus status; private final String authenticate; + public ApiException(String code, HttpStatus status, String message) { this(code, status, message, null); } + public ApiException(String code, HttpStatus status, String message, String authenticate) { + super(message); this.code = code; this.status = status; this.authenticate = authenticate; + } + public String code() { return code; } + public HttpStatus status() { return status; } + public String authenticate() { return authenticate; } +} diff --git a/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java b/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java new file mode 100644 index 0000000..254d671 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java @@ -0,0 +1,17 @@ +package com.example.mtusi_messenger.exception; + +import org.springframework.http.HttpStatus; + +public final class ApiExceptions { + private ApiExceptions() {} + public static ApiException invalid(String m) { return new ApiException("invalid_request", HttpStatus.BAD_REQUEST, m); } + public static ApiException unauthorized(String m) { return unauthorizedBearer(m); } + public static ApiException unauthorizedBasic(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Basic realm=\"messenger\", charset=\"UTF-8\""); } + public static ApiException unauthorizedBearer(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Bearer realm=\"messenger\""); } + public static ApiException notFound(String m) { return new ApiException("not_found", HttpStatus.NOT_FOUND, m); } + public static ApiException conflict(String m) { return new ApiException("conflict", HttpStatus.CONFLICT, m); } + public static ApiException payloadTooLarge(String m) { return new ApiException("payload_too_large", HttpStatus.PAYLOAD_TOO_LARGE, m); } + public static ApiException unsupportedMediaType(String m) { return new ApiException("unsupported_media_type", HttpStatus.UNSUPPORTED_MEDIA_TYPE, m); } + public static ApiException tooManyRequests(String m) { return new ApiException("rate_limited", HttpStatus.TOO_MANY_REQUESTS, m); } + public static ApiException unavailable(String m) { return new ApiException("unavailable", HttpStatus.SERVICE_UNAVAILABLE, m); } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/Attachment.java b/src/main/java/com/example/mtusi_messenger/model/Attachment.java new file mode 100644 index 0000000..acb2515 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Attachment.java @@ -0,0 +1,38 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record Attachment(UUID id, + UUID chatId, + UUID ownerId, + String filename, + String contentType, + long sizeBytes, + String sha256, + String objectKey, + String stagingKey, + String status, + List variants, + String errorCode, + Instant createdAt, + Instant updatedAt) { + public Attachment { + variants = variants == null ? List.of() : List.copyOf(variants); + } + + public Attachment(UUID id, + UUID chatId, + UUID ownerId, + String filename, + String contentType, + long sizeBytes, + String sha256, + String objectKey, + Instant createdAt, + Instant updatedAt) { + this(id, chatId, ownerId, filename, contentType, sizeBytes, sha256, objectKey, + null, "ready", List.of(), null, createdAt, updatedAt); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java b/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java new file mode 100644 index 0000000..a189403 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/AttachmentJob.java @@ -0,0 +1,40 @@ +package com.example.mtusi_messenger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.Instant; +import java.util.UUID; + +public record AttachmentJob( + @JsonProperty("schema_version") int schemaVersion, + @JsonProperty("job_id") UUID jobId, + String type, + @JsonProperty("attachment_id") UUID attachmentId, + @JsonProperty("pipeline_version") int pipelineVersion, + int attempt, + @JsonProperty("created_at") Instant createdAt) { + + public static final int SCHEMA_VERSION = 1; + public static final int MIN_PIPELINE_VERSION = 1; + public static final int CURRENT_PIPELINE_VERSION = 2; + public static final String TYPE = "attachment.process.v1"; + + public AttachmentJob { + if (schemaVersion != SCHEMA_VERSION || !TYPE.equals(type) + || pipelineVersion < MIN_PIPELINE_VERSION + || pipelineVersion > CURRENT_PIPELINE_VERSION || attempt < 1) { + throw new IllegalArgumentException("Unsupported attachment job message"); + } + } + + public static AttachmentJob first( + UUID jobId, UUID attachmentId, int pipelineVersion, Instant createdAt) { + return new AttachmentJob(SCHEMA_VERSION, jobId, TYPE, attachmentId, + pipelineVersion, 1, createdAt); + } + + public AttachmentJob nextAttempt(int nextAttempt) { + return new AttachmentJob(schemaVersion, jobId, type, attachmentId, + pipelineVersion, nextAttempt, createdAt); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java b/src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java new file mode 100644 index 0000000..ff4e809 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/AttachmentVariant.java @@ -0,0 +1,10 @@ +package com.example.mtusi_messenger.model; + +public record AttachmentVariant(String name, + String contentType, + long sizeBytes, + int width, + int height, + String sha256, + String objectKey) { +} diff --git a/src/main/java/com/example/mtusi_messenger/model/Chat.java b/src/main/java/com/example/mtusi_messenger/model/Chat.java new file mode 100644 index 0000000..829d99e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Chat.java @@ -0,0 +1,11 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record Chat(UUID id, String title, List memberIds, Instant createdAt) { + public Chat { + memberIds = List.copyOf(memberIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java b/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java new file mode 100644 index 0000000..424d7a3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java @@ -0,0 +1,3 @@ +package com.example.mtusi_messenger.model; + +public record IdempotentMessage(byte[] requestHash, Message message) {} diff --git a/src/main/java/com/example/mtusi_messenger/model/Message.java b/src/main/java/com/example/mtusi_messenger/model/Message.java new file mode 100644 index 0000000..2539faa --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Message.java @@ -0,0 +1,16 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record Message(UUID id, + UUID chatId, + UUID senderId, + String text, + Instant createdAt, + List attachmentIds) { + public Message { + attachmentIds = attachmentIds == null ? List.of() : List.copyOf(attachmentIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/MessageKey.java b/src/main/java/com/example/mtusi_messenger/model/MessageKey.java new file mode 100644 index 0000000..545fd60 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/MessageKey.java @@ -0,0 +1,35 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record MessageKey(Instant createdAt, UUID id) + implements Comparable { + + private static int compareUuidV7(UUID a, UUID b) { + int result = Long.compareUnsigned( + a.getMostSignificantBits(), + b.getMostSignificantBits() + ); + + if (result != 0) { + return result; + } + + return Long.compareUnsigned( + a.getLeastSignificantBits(), + b.getLeastSignificantBits() + ); + } + + @Override + public int compareTo(MessageKey other) { + int result = createdAt.compareTo(other.createdAt); + + if (result != 0) { + return result; + } + + return compareUuidV7(id, other.id); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/model/Session.java b/src/main/java/com/example/mtusi_messenger/model/Session.java new file mode 100644 index 0000000..27aa2fb --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Session.java @@ -0,0 +1,15 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record Session(UUID id, UUID userId, byte[] tokenHash, Instant createdAt, Instant expiresAt) { + public Session { + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/User.java b/src/main/java/com/example/mtusi_messenger/model/User.java new file mode 100644 index 0000000..1fefb17 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/User.java @@ -0,0 +1,6 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record User(UUID id, String username, String displayName, Instant createdAt) {} diff --git a/src/main/java/com/example/mtusi_messenger/observability/DurableTraceContext.java b/src/main/java/com/example/mtusi_messenger/observability/DurableTraceContext.java new file mode 100644 index 0000000..021a29e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/observability/DurableTraceContext.java @@ -0,0 +1,45 @@ +package com.example.mtusi_messenger.observability; + +import com.example.mtusi_messenger.repository.AttachmentRepository.TraceContext; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.context.propagation.TextMapGetter; +import io.opentelemetry.context.propagation.TextMapPropagator; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class DurableTraceContext { + private static final TextMapGetter> GETTER = new TextMapGetter<>() { + @Override + public Iterable keys(Map carrier) { + return carrier.keySet(); + } + + @Override + public String get(Map carrier, String key) { + return carrier.get(key); + } + }; + + private final TextMapPropagator propagator = GlobalOpenTelemetry.getPropagators() + .getTextMapPropagator(); + + public TraceContext capture() { + Map carrier = new HashMap<>(); + propagator.inject(Context.current(), carrier, Map::put); + return new TraceContext(carrier.get("traceparent"), carrier.get("tracestate")); + } + + public Scope restore(TraceContext traceContext) { + Map carrier = new HashMap<>(); + carrier.put("traceparent", traceContext.traceparent()); + if (traceContext.tracestate() != null && !traceContext.tracestate().isBlank()) { + carrier.put("tracestate", traceContext.tracestate()); + } + return propagator.extract(Context.root(), carrier, GETTER).makeCurrent(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/observability/JobTelemetry.java b/src/main/java/com/example/mtusi_messenger/observability/JobTelemetry.java new file mode 100644 index 0000000..8001cdc --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/observability/JobTelemetry.java @@ -0,0 +1,77 @@ +package com.example.mtusi_messenger.observability; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.atomic.AtomicLong; + +/** Low-cardinality business metrics required by contracts/observability.md. */ +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "worker") +public class JobTelemetry { + private static final AttributeKey JOB_TYPE = AttributeKey.stringKey("job.type"); + private static final AttributeKey OUTCOME = AttributeKey.stringKey("outcome"); + private static final String ATTACHMENT_JOB = "attachment_variant"; + + private final LongCounter processed; + private final DoubleHistogram processingDuration; + private final DoubleHistogram timeToReady; + private final AtomicLong busy = new AtomicLong(); + + public JobTelemetry(@Value("${spring.rabbitmq.listener.simple.concurrency:2}") long capacity) { + Meter meter = GlobalOpenTelemetry.get().meterBuilder("messenger-jobs") + .setInstrumentationVersion("1.0.0") + .build(); + processed = meter.counterBuilder("messenger.jobs.processed") + .setDescription("Completed attachment job attempts") + .build(); + processingDuration = meter.histogramBuilder("messenger.job.processing.duration") + .setDescription("Attachment job attempt duration") + .setUnit("s") + .build(); + timeToReady = meter.histogramBuilder("messenger.attachment.time_to_ready") + .setDescription("Time from durable acceptance to ready state") + .setUnit("s") + .build(); + meter.gaugeBuilder("messenger.worker.busy") + .ofLongs() + .setDescription("Workers currently processing an attachment job") + .buildWithCallback(measurement -> measurement.record(busy.get())); + meter.gaugeBuilder("messenger.worker.capacity") + .ofLongs() + .setDescription("Configured attachment worker capacity") + .buildWithCallback(measurement -> measurement.record(capacity)); + } + + public long started() { + busy.incrementAndGet(); + return System.nanoTime(); + } + + public void finished(long startedNanos, Instant acceptedAt, String outcome) { + busy.updateAndGet(current -> Math.max(0, current - 1)); + Attributes attributes = Attributes.of(JOB_TYPE, ATTACHMENT_JOB, OUTCOME, outcome); + processed.add(1, attributes); + processingDuration.record( + Math.max(0, System.nanoTime() - startedNanos) / 1_000_000_000.0, + attributes); + if ("success".equals(outcome)) { + timeToReady.record( + Math.max(0, Duration.between(acceptedAt, Instant.now()).toMillis()) / 1000.0, + Attributes.of(JOB_TYPE, ATTACHMENT_JOB, OUTCOME, outcome)); + } + } + + public void malformedMessage() { + processed.add(1, Attributes.of(JOB_TYPE, ATTACHMENT_JOB, OUTCOME, "invalid_message")); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/observability/QueueTelemetry.java b/src/main/java/com/example/mtusi_messenger/observability/QueueTelemetry.java new file mode 100644 index 0000000..4aa2f30 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/observability/QueueTelemetry.java @@ -0,0 +1,71 @@ +package com.example.mtusi_messenger.observability; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.Meter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicLong; + +/** Samples the durable job queue without placing job or user identifiers in labels. */ +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class QueueTelemetry { + private static final Logger log = LoggerFactory.getLogger(QueueTelemetry.class); + private static final AttributeKey QUEUE_NAME = AttributeKey.stringKey("messaging.destination.name"); + + private final JdbcTemplate jdbc; + private final AtomicLong depth = new AtomicLong(); + private final AtomicLong oldestAgeSeconds = new AtomicLong(); + private final Attributes queueAttributes; + + public QueueTelemetry( + JdbcTemplate jdbc, + @Value("${messenger.jobs.queue}") String queueName) { + this.jdbc = jdbc; + this.queueAttributes = Attributes.of(QUEUE_NAME, queueName); + Meter meter = GlobalOpenTelemetry.get().meterBuilder("messenger-queue") + .setInstrumentationVersion("1.0.0") + .build(); + meter.gaugeBuilder("messenger.queue.depth") + .ofLongs() + .setDescription("Durable queued or processing attachment jobs") + .buildWithCallback(measurement -> measurement.record(depth.get(), queueAttributes)); + meter.gaugeBuilder("messenger.queue.oldest_job.age") + .ofLongs() + .setDescription("Age of the oldest non-terminal attachment job") + .setUnit("s") + .buildWithCallback(measurement -> measurement.record(oldestAgeSeconds.get(), queueAttributes)); + } + + @Scheduled(fixedDelayString = "${messenger.observability.queue-poll-interval:5s}") + public void sample() { + try { + QueueSnapshot snapshot = jdbc.queryForObject(""" + SELECT count(*) AS depth, + COALESCE(EXTRACT(EPOCH FROM + (clock_timestamp() - min(created_at))), 0)::bigint AS oldest_age + FROM attachment_jobs + WHERE status IN ('queued', 'processing') + """, (rs, row) -> new QueueSnapshot(rs.getLong("depth"), rs.getLong("oldest_age"))); + if (snapshot != null) { + depth.set(snapshot.depth()); + oldestAgeSeconds.set(Math.max(0, snapshot.oldestAgeSeconds())); + } + } catch (RuntimeException error) { + log.atWarn() + .addKeyValue("event", "queue_metrics_sample_failed") + .log("Queue telemetry sample failed: {}", error.getClass().getSimpleName()); + } + } + + private record QueueSnapshot(long depth, long oldestAgeSeconds) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java b/src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java new file mode 100644 index 0000000..ce87b42 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/AttachmentJobPublisher.java @@ -0,0 +1,65 @@ +package com.example.mtusi_messenger.queue; + +import com.example.mtusi_messenger.model.AttachmentJob; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageDeliveryMode; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.time.Duration; + +@Component +public class AttachmentJobPublisher { + private final RabbitTemplate rabbit; + private final ObjectMapper mapper; + private final String exchange; + private final String routingKey; + private final long confirmTimeoutMillis; + + public AttachmentJobPublisher( + RabbitTemplate rabbit, + ObjectMapper mapper, + @Value("${messenger.jobs.exchange}") String exchange, + @Value("${messenger.jobs.routing-key}") String routingKey, + @Value("${messenger.jobs.publish-confirm-timeout:5s}") Duration confirmTimeout) { + this.rabbit = rabbit; + this.mapper = mapper; + this.exchange = exchange; + this.routingKey = routingKey; + this.confirmTimeoutMillis = confirmTimeout.toMillis(); + this.rabbit.setMandatory(true); + } + + public void publish(AttachmentJob job) { + try { + byte[] body = mapper.writeValueAsBytes(job); + MessageProperties properties = new MessageProperties(); + properties.setContentType(MessageProperties.CONTENT_TYPE_JSON); + properties.setContentEncoding("UTF-8"); + properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT); + properties.setMessageId(job.jobId().toString()); + properties.setHeader("schema_version", job.schemaVersion()); + Message message = new Message(body, properties); + + rabbit.invoke(operations -> { + operations.send(exchange, routingKey, message); + operations.waitForConfirmsOrDie(confirmTimeoutMillis); + return null; + }); + } catch (JsonProcessingException error) { + throw new JobPublishException("Cannot encode attachment job", error); + } catch (RuntimeException error) { + throw new JobPublishException("RabbitMQ did not confirm attachment job", error); + } + } + + public static final class JobPublishException extends RuntimeException { + public JobPublishException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java b/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java new file mode 100644 index 0000000..4ddeb98 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/ExpiredLeaseReaper.java @@ -0,0 +1,57 @@ +package com.example.mtusi_messenger.queue; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.Clock; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class ExpiredLeaseReaper { + private static final Logger log = LoggerFactory.getLogger(ExpiredLeaseReaper.class); + private final AttachmentRepository attachments; + private final RetryPolicy retryPolicy; + private final TransactionTemplate transaction; + private final int maxAttempts; + private final Clock clock = Clock.systemUTC(); + + public ExpiredLeaseReaper( + AttachmentRepository attachments, + RetryPolicy retryPolicy, + TransactionTemplate transaction, + @Value("${messenger.jobs.max-attempts:5}") int maxAttempts) { + this.attachments = attachments; + this.retryPolicy = retryPolicy; + this.transaction = transaction; + this.maxAttempts = maxAttempts; + } + + @Scheduled(fixedDelayString = "${messenger.jobs.lease-reaper-interval:5s}") + public void recoverExpired() { + for (var job : attachments.findExpiredJobs(50)) { + try { + transaction.executeWithoutResult(status -> { + if (job.attempt() >= maxAttempts) { + attachments.failExpired(job.jobId(), job.attachmentId(), + job.pipelineVersion(), "retry_exhausted"); + } else { + int nextAttempt = job.attempt() + 1; + attachments.requeueExpired( + job.jobId(), job.attachmentId(), job.pipelineVersion(), + nextAttempt, "processing_timeout", + clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt))); + } + }); + } catch (RuntimeException error) { + log.warn("Expired attachment lease recovery postponed for job {}", job.jobId()); + return; + } + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java b/src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java new file mode 100644 index 0000000..306375e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/RetryPolicy.java @@ -0,0 +1,39 @@ +package com.example.mtusi_messenger.queue; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.util.concurrent.ThreadLocalRandom; + +@Component +public class RetryPolicy { + private final long baseDelayMillis; + private final long maxDelayMillis; + + public RetryPolicy( + @Value("${messenger.jobs.retry-base-delay:1s}") Duration baseDelay, + @Value("${messenger.jobs.retry-max-delay:30s}") Duration maxDelay) { + if (baseDelay.isNegative() || baseDelay.isZero() || maxDelay.compareTo(baseDelay) < 0) { + throw new IllegalArgumentException("Invalid retry delay configuration"); + } + this.baseDelayMillis = baseDelay.toMillis(); + this.maxDelayMillis = maxDelay.toMillis(); + } + + public Duration delayForAttempt(int nextAttempt) { + int exponent = Math.max(0, Math.min(30, nextAttempt - 2)); + long exponential; + try { + exponential = Math.multiplyExact(baseDelayMillis, 1L << exponent); + } catch (ArithmeticException overflow) { + exponential = maxDelayMillis; + } + long ceiling = Math.min(maxDelayMillis, exponential); + long floor = Math.max(1, ceiling / 2); + long jittered = floor == ceiling + ? ceiling + : ThreadLocalRandom.current().nextLong(floor, ceiling + 1); + return Duration.ofMillis(jittered); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java b/src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java new file mode 100644 index 0000000..7b9793b --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/queue/UnpublishedJobRepublisher.java @@ -0,0 +1,47 @@ +package com.example.mtusi_messenger.queue; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.observability.DurableTraceContext; +import io.opentelemetry.context.Scope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class UnpublishedJobRepublisher { + private static final Logger log = LoggerFactory.getLogger(UnpublishedJobRepublisher.class); + private final AttachmentRepository attachments; + private final AttachmentJobPublisher publisher; + private final DurableTraceContext tracing; + + public UnpublishedJobRepublisher(AttachmentRepository attachments, + AttachmentJobPublisher publisher, + DurableTraceContext tracing) { + this.attachments = attachments; + this.publisher = publisher; + this.tracing = tracing; + } + + @Scheduled(fixedDelayString = "${messenger.jobs.republish-interval:5s}") + public void publishPending() { + for (var job : attachments.findUnpublishedJobs(50)) { + try { + var traceContext = attachments.findTraceContext(job.jobId()); + if (traceContext.isPresent()) { + try (Scope ignored = tracing.restore(traceContext.get())) { + publisher.publish(job); + } + } else { + publisher.publish(job); + } + attachments.markPublished(job.jobId()); + } catch (RuntimeException error) { + log.warn("Attachment job publication postponed for job {}", job.jobId()); + return; + } + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java new file mode 100644 index 0000000..c2595f3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/AttachmentRepository.java @@ -0,0 +1,45 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.Set; +import java.time.Duration; +import java.time.Instant; + +public interface AttachmentRepository { + Attachment saveQueued(Attachment attachment, AttachmentJob job); + Optional findById(UUID id); + List findAllByIdsInChat(UUID chatId, List ids); + Set findAllObjectKeys(); + Set findActiveStagingKeys(); + void markPublished(UUID jobId); + boolean markPublishFaultInjected(UUID jobId); + List findUnpublishedJobs(int limit); + Optional findTraceContext(UUID jobId); + int currentAttempt(UUID jobId); + boolean claim(UUID jobId, UUID attachmentId, int pipelineVersion, + int attempt, UUID leaseToken, Duration leaseDuration); + boolean markBeforeEffectFaultInjected(UUID jobId, UUID leaseToken); + boolean markAfterEffectFaultInjected(UUID jobId, UUID leaseToken); + boolean markQueuedForRetry(UUID jobId, UUID attachmentId, int pipelineVersion, UUID leaseToken, + int nextAttempt, String errorCode, Instant nextAttemptAt); + CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion, + List variants, boolean injectCrashAfterCommit); + boolean markFailed(UUID jobId, UUID attachmentId, int pipelineVersion, + UUID leaseToken, String errorCode); + List findExpiredJobs(int limit); + boolean requeueExpired(UUID jobId, UUID attachmentId, int pipelineVersion, int nextAttempt, + String errorCode, Instant nextAttemptAt); + boolean failExpired(UUID jobId, UUID attachmentId, int pipelineVersion, String errorCode); + + record CompletionResult(boolean completed, boolean crashAfterCommit) { + } + + record TraceContext(String traceparent, String tracestate) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java b/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java new file mode 100644 index 0000000..66085e4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Chat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface ChatRepository { + Chat save(Chat chat); + Optional findById(UUID id); + boolean isMember(UUID chatId, UUID userId); + List findAllForUser(UUID userId); + List findPageForUser(UUID userId, UUID afterId, java.time.Instant afterCreatedAt, int limitPlusOne); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java b/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java new file mode 100644 index 0000000..23ea481 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Message; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface MessageRepository { + Message save(Message message); + void lockIdempotencyScope(UUID userId, String method, String path, String key); + void deleteExpiredIdempotency(UUID userId, String method, String path, String key, Instant expiresBefore); + Optional findIdempotent( + UUID userId, String method, String path, String key); + void saveIdempotency(UUID userId, String method, String path, String key, + byte[] requestHash, UUID messageId, Instant createdAt); + List findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java new file mode 100644 index 0000000..d97f66d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresAttachmentRepository.java @@ -0,0 +1,402 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; +import com.example.mtusi_messenger.observability.DurableTraceContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Duration; +import java.time.Instant; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +@Repository +public class PostgresAttachmentRepository implements AttachmentRepository { + private static final String COLUMNS = """ + id, chat_id, owner_id, filename, content_type, size_bytes, + sha256, object_key, staging_key, status, error_code, created_at, updated_at + """; + private final JdbcTemplate jdbc; + private final DurableTraceContext tracing; + + public PostgresAttachmentRepository(JdbcTemplate jdbc, DurableTraceContext tracing) { + this.jdbc = jdbc; + this.tracing = tracing; + } + + @Override + public Attachment saveQueued(Attachment attachment, AttachmentJob job) { + jdbc.update(""" + INSERT INTO attachments + (id, chat_id, owner_id, filename, content_type, size_bytes, + sha256, object_key, staging_key, pipeline_version, + status, error_code, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, ?, ?) + """, attachment.id(), attachment.chatId(), attachment.ownerId(), + attachment.filename(), attachment.contentType(), attachment.sizeBytes(), + attachment.sha256(), attachment.objectKey(), attachment.stagingKey(), + job.pipelineVersion(), + Timestamp.from(attachment.createdAt()), Timestamp.from(attachment.updatedAt())); + TraceContext traceContext = tracing.capture(); + jdbc.update(""" + INSERT INTO attachment_jobs + (id, attachment_id, pipeline_version, attempt, status, published, + trace_parent, trace_state, created_at, updated_at) + VALUES (?, ?, ?, ?, 'queued', false, ?, ?, ?, ?) + """, job.jobId(), job.attachmentId(), job.pipelineVersion(), job.attempt(), + traceContext.traceparent(), traceContext.tracestate(), + Timestamp.from(job.createdAt()), Timestamp.from(job.createdAt())); + return attachment; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE id = ?", + (rs, rowNum) -> map(rs), id).stream().findFirst(); + } + + @Override + public List findAllByIdsInChat(UUID chatId, List ids) { + if (ids.isEmpty()) { + return List.of(); + } + String placeholders = String.join(",", Collections.nCopies(ids.size(), "?")); + Object[] args = new Object[ids.size() + 1]; + args[0] = chatId; + for (int i = 0; i < ids.size(); i++) { + args[i + 1] = ids.get(i); + } + return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE chat_id = ? AND id IN (" + + placeholders + ") AND status <> 'failed'", + (rs, rowNum) -> map(rs), args); + } + + @Override + public Set findAllObjectKeys() { + Set keys = new HashSet<>(jdbc.query( + "SELECT object_key FROM attachments WHERE status = 'ready'", + (rs, rowNum) -> rs.getString("object_key"))); + keys.addAll(jdbc.query("SELECT object_key FROM attachment_variants", + (rs, rowNum) -> rs.getString("object_key"))); + return keys; + } + + @Override + public Set findActiveStagingKeys() { + return new HashSet<>(jdbc.query(""" + SELECT staging_key + FROM attachments + WHERE status IN ('queued', 'processing') AND staging_key IS NOT NULL + """, (rs, rowNum) -> rs.getString("staging_key"))); + } + + @Override + public void markPublished(UUID jobId) { + jdbc.update(""" + UPDATE attachment_jobs + SET published = true, updated_at = clock_timestamp() + WHERE id = ? AND status = 'queued' + """, jobId); + } + + @Override + public boolean markPublishFaultInjected(UUID jobId) { + return jdbc.update(""" + UPDATE attachment_jobs + SET publish_fault_injected = true, updated_at = clock_timestamp() + WHERE id = ? AND publish_fault_injected = false AND status = 'queued' + """, jobId) == 1; + } + + @Override + public List findUnpublishedJobs(int limit) { + return jdbc.query(""" + SELECT id, attachment_id, pipeline_version, attempt, created_at + FROM attachment_jobs + WHERE status = 'queued' AND published = false + AND next_attempt_at <= clock_timestamp() + ORDER BY next_attempt_at, created_at, id + LIMIT ? + """, (rs, rowNum) -> mapJob(rs), limit); + } + + @Override + public Optional findTraceContext(UUID jobId) { + return jdbc.query(""" + SELECT trace_parent, trace_state + FROM attachment_jobs + WHERE id = ? AND trace_parent IS NOT NULL + """, (rs, rowNum) -> new TraceContext( + rs.getString("trace_parent"), rs.getString("trace_state")), jobId) + .stream().findFirst(); + } + + @Override + public int currentAttempt(UUID jobId) { + Integer attempt = jdbc.query("SELECT attempt FROM attachment_jobs WHERE id = ?", + (rs, rowNum) -> rs.getInt("attempt"), jobId).stream().findFirst().orElse(null); + return attempt == null ? 1 : attempt; + } + + @Override + public boolean claim(UUID jobId, UUID attachmentId, int pipelineVersion, int attempt, + UUID leaseToken, Duration leaseDuration) { + int claimed = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'processing', attempt = GREATEST(attempt, ?), + lease_token = ?, + lease_until = clock_timestamp() + (? * interval '1 millisecond'), + updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? + AND pipeline_version = ? + AND (status = 'queued' + OR (status = 'processing' AND lease_until < clock_timestamp())) + AND EXISTS ( + SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ? + AND a.status IN ('queued', 'processing')) + """, attempt, leaseToken, leaseDuration.toMillis(), jobId, attachmentId, + pipelineVersion, attachmentId, pipelineVersion); + if (claimed == 0) { + return false; + } + jdbc.update(""" + UPDATE attachments + SET status = 'processing', error_code = NULL, updated_at = clock_timestamp() + WHERE id = ? AND pipeline_version = ? + AND status IN ('queued', 'processing') + """, attachmentId, pipelineVersion); + return true; + } + + @Override + public boolean markBeforeEffectFaultInjected(UUID jobId, UUID leaseToken) { + return jdbc.update(""" + UPDATE attachment_jobs + SET before_effect_fault_injected = true, updated_at = clock_timestamp() + WHERE id = ? AND status = 'processing' AND lease_token = ? + AND before_effect_fault_injected = false + """, jobId, leaseToken) == 1; + } + + @Override + public boolean markAfterEffectFaultInjected(UUID jobId, UUID leaseToken) { + return jdbc.update(""" + UPDATE attachment_jobs + SET after_effect_fault_injected = true, updated_at = clock_timestamp() + WHERE id = ? AND status = 'processing' AND lease_token = ? + AND after_effect_fault_injected = false + """, jobId, leaseToken) == 1; + } + + @Override + public boolean markQueuedForRetry(UUID jobId, UUID attachmentId, int pipelineVersion, + UUID leaseToken, + int nextAttempt, String errorCode, Instant nextAttemptAt) { + TraceContext traceContext = tracing.capture(); + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'queued', attempt = ?, published = false, + last_error_code = ?, next_attempt_at = ?, + trace_parent = ?, trace_state = ?, + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND pipeline_version = ? AND lease_token = ? + """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), + traceContext.traceparent(), traceContext.tracestate(), + jobId, attachmentId, pipelineVersion, leaseToken); + if (updated == 0) { + return false; + } + jdbc.update(""" + UPDATE attachments + SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() + WHERE id = ? AND pipeline_version = ? + AND status IN ('queued', 'processing') + """, attachmentId, pipelineVersion); + return true; + } + + @Override + public CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion, + List variants, boolean injectCrashAfterCommit) { + boolean triggerCrash = injectCrashAfterCommit && Boolean.TRUE.equals(jdbc.query(""" + SELECT NOT result_fault_injected + FROM attachment_jobs + WHERE id = ? AND attachment_id = ? AND status = 'processing' AND lease_token = ? + FOR UPDATE + """, (rs, rowNum) -> rs.getBoolean(1), jobId, attachmentId, leaseToken) + .stream().findFirst().orElse(false)); + int completed = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'ready', published = true, last_error_code = NULL, + lease_token = NULL, lease_until = NULL, + result_fault_injected = result_fault_injected OR ?, + updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND pipeline_version = ? AND lease_token = ? + AND EXISTS ( + SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ? + AND a.status = 'processing') + """, triggerCrash, jobId, attachmentId, pipelineVersion, leaseToken, + attachmentId, pipelineVersion); + if (completed == 0) { + return new CompletionResult(false, false); + } + for (AttachmentVariant variant : variants) { + jdbc.update(""" + INSERT INTO attachment_variants + (attachment_id, pipeline_version, name, content_type, size_bytes, + width, height, sha256, object_key, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp()) + ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING + """, attachmentId, pipelineVersion, variant.name(), variant.contentType(), + variant.sizeBytes(), variant.width(), variant.height(), variant.sha256(), + variant.objectKey()); + } + jdbc.update(""" + UPDATE attachments + SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() + WHERE id = ? AND pipeline_version = ? AND status = 'processing' + """, attachmentId, pipelineVersion); + return new CompletionResult(true, triggerCrash); + } + + @Override + public boolean markFailed(UUID jobId, UUID attachmentId, int pipelineVersion, + UUID leaseToken, String errorCode) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'failed', published = true, last_error_code = ?, + lease_token = NULL, lease_until = NULL, + updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND pipeline_version = ? AND lease_token = ? + AND EXISTS (SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ?) + """, errorCode, jobId, attachmentId, pipelineVersion, leaseToken, + attachmentId, pipelineVersion); + if (updated == 0) { + return false; + } + jdbc.update(""" + UPDATE attachments + SET status = 'failed', error_code = ?, updated_at = clock_timestamp() + WHERE id = ? AND pipeline_version = ? AND status <> 'ready' + """, errorCode, attachmentId, pipelineVersion); + return true; + } + + @Override + public List findExpiredJobs(int limit) { + return jdbc.query(""" + SELECT id, attachment_id, pipeline_version, attempt, created_at + FROM attachment_jobs + WHERE status = 'processing' AND lease_until < clock_timestamp() + ORDER BY lease_until, id + LIMIT ? + """, (rs, rowNum) -> mapJob(rs), limit); + } + + @Override + public boolean requeueExpired(UUID jobId, UUID attachmentId, int pipelineVersion, + int nextAttempt, + String errorCode, Instant nextAttemptAt) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'queued', attempt = ?, published = false, + last_error_code = ?, next_attempt_at = ?, + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND pipeline_version = ? AND lease_until < clock_timestamp() + AND EXISTS (SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ?) + """, nextAttempt, errorCode, Timestamp.from(nextAttemptAt), jobId, attachmentId, + pipelineVersion, attachmentId, pipelineVersion); + if (updated == 1) { + jdbc.update(""" + UPDATE attachments SET status = 'queued', error_code = NULL, + updated_at = clock_timestamp() + WHERE id = ? AND pipeline_version = ? AND status = 'processing' + """, attachmentId, pipelineVersion); + } + return updated == 1; + } + + @Override + public boolean failExpired(UUID jobId, UUID attachmentId, int pipelineVersion, + String errorCode) { + int updated = jdbc.update(""" + UPDATE attachment_jobs + SET status = 'failed', published = true, last_error_code = ?, + lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() + WHERE id = ? AND attachment_id = ? AND status = 'processing' + AND pipeline_version = ? AND lease_until < clock_timestamp() + AND EXISTS (SELECT 1 FROM attachments a + WHERE a.id = ? AND a.pipeline_version = ?) + """, errorCode, jobId, attachmentId, pipelineVersion, + attachmentId, pipelineVersion); + if (updated == 1) { + jdbc.update(""" + UPDATE attachments SET status = 'failed', error_code = ?, + updated_at = clock_timestamp() + WHERE id = ? AND pipeline_version = ? AND status <> 'ready' + """, errorCode, attachmentId, pipelineVersion); + } + return updated == 1; + } + + private Attachment map(ResultSet rs) throws SQLException { + UUID id = rs.getObject("id", UUID.class); + return new Attachment( + id, + rs.getObject("chat_id", UUID.class), + rs.getObject("owner_id", UUID.class), + rs.getString("filename"), + rs.getString("content_type"), + rs.getLong("size_bytes"), + rs.getString("sha256"), + rs.getString("object_key"), + rs.getString("staging_key"), + rs.getString("status"), + findVariants(id), + rs.getString("error_code"), + rs.getTimestamp("created_at").toInstant(), + rs.getTimestamp("updated_at").toInstant()); + } + + private List findVariants(UUID attachmentId) { + return jdbc.query(""" + SELECT name, content_type, size_bytes, width, height, sha256, object_key + FROM attachment_variants + WHERE attachment_id = ? + AND pipeline_version = ( + SELECT pipeline_version FROM attachments WHERE id = ?) + ORDER BY name + """, (rs, rowNum) -> new AttachmentVariant( + rs.getString("name"), rs.getString("content_type"), rs.getLong("size_bytes"), + rs.getInt("width"), rs.getInt("height"), rs.getString("sha256"), + rs.getString("object_key")), attachmentId, attachmentId); + } + + private static AttachmentJob mapJob(ResultSet rs) throws SQLException { + return new AttachmentJob( + AttachmentJob.SCHEMA_VERSION, + rs.getObject("id", UUID.class), + AttachmentJob.TYPE, + rs.getObject("attachment_id", UUID.class), + rs.getInt("pipeline_version"), + rs.getInt("attempt"), + rs.getTimestamp("created_at").toInstant()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java new file mode 100644 index 0000000..17d825d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java @@ -0,0 +1,106 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Chat; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresChatRepository implements ChatRepository { + private final JdbcTemplate jdbc; + + public PostgresChatRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + @Transactional(timeout = 5) + public Chat save(Chat chat) { + jdbc.update(""" + INSERT INTO chats (id, title, created_at) + VALUES (?, ?, ?) + """, chat.id(), chat.title(), Timestamp.from(chat.createdAt())); + + for (UUID memberId : chat.memberIds()) { + jdbc.update(""" + INSERT INTO chat_members (chat_id, user_id) + VALUES (?, ?) + """, chat.id(), memberId); + } + return chat; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query(""" + SELECT id, title, created_at + FROM chats + WHERE id = ? + """, (rs, rowNum) -> new ChatRow( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getTimestamp("created_at").toInstant()), id) + .stream().findFirst() + .map(this::toChat); + } + + @Override + public boolean isMember(UUID chatId, UUID userId) { + return Boolean.TRUE.equals(jdbc.queryForObject(""" + SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = ? AND user_id = ? + ) + """, Boolean.class, chatId, userId)); + } + + @Override + public List findAllForUser(UUID userId) { + return findPageForUser(userId, null, null, Integer.MAX_VALUE); + } + + @Override + public List findPageForUser(UUID userId, UUID afterId, Instant afterCreatedAt, int limitPlusOne) { + StringBuilder sql = new StringBuilder(""" + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id + WHERE cm.user_id = ? + """); + List parameters = new ArrayList<>(); + parameters.add(userId); + + if (afterCreatedAt != null) { + sql.append(" AND (c.created_at, c.id) > (?, ?) "); + parameters.add(Timestamp.from(afterCreatedAt)); + parameters.add(afterId); + } + sql.append(" ORDER BY c.created_at, c.id LIMIT ? "); + parameters.add(limitPlusOne); + + return jdbc.query(sql.toString(), (rs, rowNum) -> new ChatRow( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getTimestamp("created_at").toInstant()), parameters.toArray()) + .stream().map(this::toChat).toList(); + } + + private Chat toChat(ChatRow row) { + List members = jdbc.queryForList(""" + SELECT user_id + FROM chat_members + WHERE chat_id = ? + ORDER BY joined_at, user_id + """, UUID.class, row.id()); + return new Chat(row.id(), row.title(), members, row.createdAt()); + } + + private record ChatRow(UUID id, String title, Instant createdAt) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java new file mode 100644 index 0000000..f9c6748 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java @@ -0,0 +1,172 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.model.IdempotentMessage; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +@Repository +public class PostgresMessageRepository implements MessageRepository { + private final JdbcTemplate jdbc; + + public PostgresMessageRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public Message save(Message message) { + jdbc.update(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES (?, ?, ?, ?, ?) + """, message.id(), message.chatId(), message.senderId(), message.text(), + Timestamp.from(message.createdAt())); + if (!message.attachmentIds().isEmpty()) { + jdbc.batchUpdate(""" + INSERT INTO message_attachments + (message_id, chat_id, attachment_id, position) + VALUES (?, ?, ?, ?) + """, new BatchPreparedStatementSetter() { + @Override + public void setValues(PreparedStatement statement, int index) throws SQLException { + statement.setObject(1, message.id()); + statement.setObject(2, message.chatId()); + statement.setObject(3, message.attachmentIds().get(index)); + statement.setInt(4, index); + } + + @Override + public int getBatchSize() { + return message.attachmentIds().size(); + } + }); + } + return message; + } + + @Override + public void lockIdempotencyScope(UUID userId, String method, String path, String key) { + String scope = userId + "\n" + method + "\n" + path + "\n" + key; + jdbc.query( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + rs -> { + rs.next(); + return null; + }, + scope); + } + + @Override + public void deleteExpiredIdempotency( + UUID userId, + String method, + String path, + String key, + Instant expiresBefore + ) { + jdbc.update(""" + DELETE FROM message_idempotency + WHERE user_id = ? + AND method = ? + AND request_path = ? + AND idempotency_key = ? + AND created_at < ? + """, userId, method, path, key, Timestamp.from(expiresBefore)); + } + + @Override + public Optional findIdempotent( + UUID userId, + String method, + String path, + String key + ) { + Optional result = jdbc.query(""" + SELECT i.request_hash, + m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM message_idempotency i + JOIN messages m ON m.id = i.message_id + WHERE i.user_id = ? + AND i.method = ? + AND i.request_path = ? + AND i.idempotency_key = ? + """, (rs, rowNum) -> new IdempotentMessage( + rs.getBytes("request_hash"), + new Message( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("sender_id", UUID.class), + rs.getString("text"), + rs.getTimestamp("created_at").toInstant(), + List.of())), + userId, method, path, key).stream().findFirst(); + return result.map(value -> new IdempotentMessage( + value.requestHash(), withAttachments(value.message()))); + } + + @Override + public void saveIdempotency( + UUID userId, + String method, + String path, + String key, + byte[] requestHash, + UUID messageId, + Instant createdAt + ) { + jdbc.update(""" + INSERT INTO message_idempotency + (user_id, method, request_path, idempotency_key, + request_hash, message_id, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + """, userId, method, path, key, requestHash, messageId, + Timestamp.from(createdAt)); + } + + @Override + public List findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne) { + StringBuilder sql = new StringBuilder(""" + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = ? + """); + List parameters = new ArrayList<>(); + parameters.add(chatId); + + if (afterCreatedAt != null) { + sql.append(" AND (created_at, id) > (?, ?) "); + parameters.add(Timestamp.from(afterCreatedAt)); + parameters.add(afterId); + } + sql.append(" ORDER BY created_at, id LIMIT ? "); + parameters.add(limitPlusOne); + + return jdbc.query(sql.toString(), (rs, rowNum) -> new Message( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("sender_id", UUID.class), + rs.getString("text"), + rs.getTimestamp("created_at").toInstant(), + List.of()), parameters.toArray()).stream().map(this::withAttachments).toList(); + } + + private Message withAttachments(Message message) { + List attachmentIds = jdbc.query(""" + SELECT attachment_id + FROM message_attachments + WHERE message_id = ? + ORDER BY position + """, (rs, rowNum) -> rs.getObject("attachment_id", UUID.class), message.id()); + return new Message(message.id(), message.chatId(), message.senderId(), message.text(), + message.createdAt(), attachmentIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java new file mode 100644 index 0000000..c2744a3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java @@ -0,0 +1,75 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Session; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresSessionRepository implements SessionRepository { + private final JdbcTemplate jdbc; + + public PostgresSessionRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public void lockUserSessions(UUID userId) { + jdbc.queryForObject("SELECT id FROM users WHERE id = ? FOR UPDATE", UUID.class, userId); + } + + @Override + public Session save(Session session) { + jdbc.update(""" + INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at) + VALUES (?, ?, ?, ?, ?) + """, session.id(), session.userId(), session.tokenHash(), + Timestamp.from(session.createdAt()), Timestamp.from(session.expiresAt())); + return session; + } + + @Override + public int revokeExcessActive(UUID userId, int maximumActive) { + return jdbc.update(""" + WITH excess AS ( + SELECT id + FROM sessions + WHERE user_id = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + ORDER BY created_at DESC, id DESC + OFFSET ? + ) + UPDATE sessions s + SET revoked_at = CURRENT_TIMESTAMP + FROM excess + WHERE s.id = excess.id + """, userId, maximumActive); + } + + @Override + public Optional findActiveUserId(byte[] tokenHash) { + return jdbc.query(""" + SELECT user_id + FROM sessions + WHERE token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + """, (rs, rowNum) -> rs.getObject("user_id", UUID.class), tokenHash) + .stream().findFirst(); + } + + @Override + public boolean revoke(byte[] tokenHash) { + return jdbc.update(""" + UPDATE sessions + SET revoked_at = CURRENT_TIMESTAMP + WHERE token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + """, tokenHash) == 1; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java new file mode 100644 index 0000000..872e0c4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java @@ -0,0 +1,81 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.User; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresUserRepository implements UserRepository { + private final JdbcTemplate jdbc; + + public PostgresUserRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public User save(User user, String passwordHash) { + jdbc.update(""" + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES (?, ?, ?, ?, ?) + """, user.id(), user.username(), user.displayName(), passwordHash, + Timestamp.from(user.createdAt())); + return user; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query(""" + SELECT id, username, display_name, created_at + FROM users + WHERE id = ? + """, (rs, rowNum) -> new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), id) + .stream().findFirst(); + } + + @Override + public Optional findByUsername(String username) { + return jdbc.query(""" + SELECT id, username, display_name, created_at + FROM users + WHERE username = ? + """, (rs, rowNum) -> new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), username) + .stream().findFirst(); + } + + @Override + public Optional findCredentialsByUsername(String username) { + return jdbc.query(""" + SELECT id, username, display_name, password_hash, created_at + FROM users + WHERE username = ? + """, (rs, rowNum) -> new UserCredentials( + new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), + rs.getString("password_hash")), username) + .stream().findFirst(); + } + + @Override + public boolean replacePasswordHash(UUID userId, String expectedHash, String newHash) { + return jdbc.update(""" + UPDATE users + SET password_hash = ? + WHERE id = ? AND password_hash = ? + """, newHash, userId, expectedHash) == 1; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java b/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java new file mode 100644 index 0000000..bf7c701 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Session; + +import java.util.Optional; +import java.util.UUID; + +public interface SessionRepository { + void lockUserSessions(UUID userId); + Session save(Session session); + int revokeExcessActive(UUID userId, int maximumActive); + Optional findActiveUserId(byte[] tokenHash); + boolean revoke(byte[] tokenHash); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java b/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java new file mode 100644 index 0000000..09fb9e9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java @@ -0,0 +1,15 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.User; +import java.util.Optional; +import java.util.UUID; + +public interface UserRepository { + User save(User user, String passwordHash); + Optional findById(UUID id); + Optional findByUsername(String username); + Optional findCredentialsByUsername(String username); + boolean replacePasswordHash(UUID userId, String expectedHash, String newHash); + + record UserCredentials(User user, String passwordHash) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java b/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java new file mode 100644 index 0000000..efae50d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java @@ -0,0 +1,135 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.service.AuthenticationService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Enumeration; +import java.util.List; + +public class ApiAuthenticationFilter extends OncePerRequestFilter { + private static final String AUTHORIZATION = "Authorization"; + private static final String SESSION_PATH = "/api/v1/auth/sessions"; + + private final AuthenticationManager authenticationManager; + private final AuthenticationService sessions; + private final LoginRateLimiter loginRateLimiter; + private final RestAuthenticationEntryPoint basicEntryPoint; + private final RestAuthenticationEntryPoint bearerEntryPoint; + + public ApiAuthenticationFilter( + AuthenticationManager authenticationManager, + AuthenticationService sessions, + LoginRateLimiter loginRateLimiter, + RestAuthenticationEntryPoint basicEntryPoint, + RestAuthenticationEntryPoint bearerEntryPoint + ) { + this.authenticationManager = authenticationManager; + this.sessions = sessions; + this.loginRateLimiter = loginRateLimiter; + this.basicEntryPoint = basicEntryPoint; + this.bearerEntryPoint = bearerEntryPoint; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + boolean basicLogin = HttpMethod.POST.matches(request.getMethod()) + && SESSION_PATH.equals(request.getRequestURI()); + if (isPublicRequest(request) && !basicLogin) { + filterChain.doFilter(request, response); + return; + } + + try { + Authentication authentication = basicLogin + ? authenticateBasic(request) + : authenticateBearer(request); + var context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + filterChain.doFilter(request, response); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + (basicLogin ? basicEntryPoint : bearerEntryPoint) + .commence(request, response, e); + } finally { + SecurityContextHolder.clearContext(); + } + } + + private Authentication authenticateBasic(HttpServletRequest request) { + String header = singleAuthorizationHeader(request); + if (!header.startsWith("Basic ") || header.length() == 6) { + throw new BadCredentialsException("Invalid Basic credentials"); + } + try { + byte[] decoded = Base64.getDecoder().decode(header.substring(6)); + String credentials = new String(decoded, StandardCharsets.UTF_8); + int separator = credentials.indexOf(':'); + if (separator <= 0) { + throw new BadCredentialsException("Invalid Basic credentials"); + } + String username = credentials.substring(0, separator); + loginRateLimiter.check(username, request.getRemoteAddr()); + return authenticationManager.authenticate( + UsernamePasswordAuthenticationToken.unauthenticated( + username, + credentials.substring(separator + 1))); + } catch (IllegalArgumentException e) { + throw new BadCredentialsException("Invalid Basic credentials", e); + } + } + + private Authentication authenticateBearer(HttpServletRequest request) { + String header = singleAuthorizationHeader(request); + if (!header.startsWith("Bearer ") || header.length() == 7) { + throw new BadCredentialsException("Invalid Bearer token"); + } + String token = header.substring(7); + if (!token.matches("[A-Za-z0-9_-]{43}")) { + throw new BadCredentialsException("Invalid Bearer token"); + } + SessionPrincipal principal = sessions.authenticateBearer(token); + return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of()); + } + + private String singleAuthorizationHeader(HttpServletRequest request) { + Enumeration values = request.getHeaders(AUTHORIZATION); + if (values == null || !values.hasMoreElements()) { + throw new BadCredentialsException("Authentication required"); + } + String value = values.nextElement(); + if (values.hasMoreElements()) { + throw new BadCredentialsException("Multiple Authorization headers"); + } + return value; + } + + private boolean isPublicRequest(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/health/") + || path.equals("/swagger-ui.html") + || path.startsWith("/swagger-ui/") + || path.equals("/v3/api-docs") + || path.startsWith("/v3/api-docs/") + || (HttpMethod.POST.matches(request.getMethod()) + && "/api/v1/users".equals(path)); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java b/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java new file mode 100644 index 0000000..a97e84f --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java @@ -0,0 +1,75 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.repository.UserRepository; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; +import org.springframework.dao.DataAccessException; + +import java.util.List; + +@Component +public class DatabaseAuthenticationProvider implements AuthenticationProvider { + private final UserRepository users; + private final PasswordEncoder passwordEncoder; + private final String dummyPasswordHash; + + public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) { + this.users = users; + this.passwordEncoder = passwordEncoder; + this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing"); + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String username = authentication.getName(); + String password = String.valueOf(authentication.getCredentials()); + final java.util.Optional stored; + try { + stored = users.findCredentialsByUsername(username); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash) + .filter(hash -> hash.startsWith("$argon2")) + .orElse(dummyPasswordHash); + + boolean matches; + try { + matches = passwordEncoder.matches(password, passwordHash); + } catch (IllegalArgumentException e) { + matches = false; + } + + if (stored.isEmpty() || !matches) { + throw new BadCredentialsException("Invalid credentials"); + } + + UserRepository.UserCredentials credentials = stored.get(); + if (passwordEncoder.upgradeEncoding(credentials.passwordHash())) { + try { + users.replacePasswordHash( + credentials.user().id(), + credentials.passwordHash(), + passwordEncoder.encode(password)); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Password hash upgrade failed", e); + } + } + + return UsernamePasswordAuthenticationToken.authenticated( + credentials.user(), + null, + List.of()); + } + + @Override + public boolean supports(Class authentication) { + return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/LoginRateLimitException.java b/src/main/java/com/example/mtusi_messenger/security/LoginRateLimitException.java new file mode 100644 index 0000000..19bac29 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/LoginRateLimitException.java @@ -0,0 +1,16 @@ +package com.example.mtusi_messenger.security; + +import org.springframework.security.core.AuthenticationException; + +public final class LoginRateLimitException extends AuthenticationException { + private final long retryAfterSeconds; + + public LoginRateLimitException(long retryAfterSeconds) { + super("Login rate limit exceeded"); + this.retryAfterSeconds = Math.max(1, retryAfterSeconds); + } + + public long retryAfterSeconds() { + return retryAfterSeconds; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/LoginRateLimiter.java b/src/main/java/com/example/mtusi_messenger/security/LoginRateLimiter.java new file mode 100644 index 0000000..3e69743 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/LoginRateLimiter.java @@ -0,0 +1,87 @@ +package com.example.mtusi_messenger.security; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.stereotype.Component; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; + +@Component +public class LoginRateLimiter { + private static final DefaultRedisScript SCRIPT = new DefaultRedisScript<>(""" + local user_count = redis.call('INCR', KEYS[1]) + if user_count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[3]) end + local source_count = redis.call('INCR', KEYS[2]) + if source_count == 1 then redis.call('EXPIRE', KEYS[2], ARGV[3]) end + if user_count > tonumber(ARGV[1]) or source_count > tonumber(ARGV[2]) then + local user_ttl = redis.call('TTL', KEYS[1]) + local source_ttl = redis.call('TTL', KEYS[2]) + return math.max(1, user_ttl, source_ttl) + end + return 0 + """, Long.class); + + private final StringRedisTemplate redis; + private final int attemptsPerUsername; + private final int attemptsPerSource; + private final int windowSeconds; + + public LoginRateLimiter( + StringRedisTemplate redis, + @Value("${messenger.login-rate-limit.attempts-per-username:5}") int attemptsPerUsername, + @Value("${messenger.login-rate-limit.attempts-per-source:100}") int attemptsPerSource, + @Value("${messenger.login-rate-limit.window-seconds:60}") int windowSeconds + ) { + if (attemptsPerUsername < 1 || attemptsPerSource < attemptsPerUsername + || windowSeconds < 1 || windowSeconds > 3600) { + throw new IllegalArgumentException("Invalid login rate limit configuration"); + } + this.redis = redis; + this.attemptsPerUsername = attemptsPerUsername; + this.attemptsPerSource = attemptsPerSource; + this.windowSeconds = windowSeconds; + } + + public void check(String username, String sourceAddress) { + String normalized = username.toLowerCase(Locale.ROOT); + List keys = List.of( + "messenger:login:user:" + digest(normalized), + "messenger:login:source:" + digest(sourceAddress)); + try { + Long retryAfter = redis.execute( + SCRIPT, + keys, + Integer.toString(attemptsPerUsername), + Integer.toString(attemptsPerSource), + Integer.toString(windowSeconds)); + if (retryAfter == null) { + throw new AuthenticationServiceException("Login rate limiter returned no result"); + } + if (retryAfter > 0) { + throw new LoginRateLimitException(retryAfter); + } + } catch (LoginRateLimitException e) { + throw e; + } catch (DataAccessException e) { + // Fail closed: a Redis outage must not remove the expensive-login guard. + throw new AuthenticationServiceException("Login rate limiter is unavailable", e); + } + } + + private static String digest(String value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java b/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000..c40c77e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,53 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.web.RequestIdFilter; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import java.io.IOException; + +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ObjectMapper mapper; + private final String challenge; + + public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) { + this.mapper = mapper; + this.challenge = challenge; + } + + @Override + public void commence( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException exception + ) throws IOException { + String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); + boolean unavailable = exception instanceof AuthenticationServiceException; + boolean rateLimited = exception instanceof LoginRateLimitException; + response.setStatus(rateLimited + ? 429 + : unavailable + ? HttpServletResponse.SC_SERVICE_UNAVAILABLE + : HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + if (rateLimited) { + response.setHeader("Retry-After", Long.toString( + ((LoginRateLimitException) exception).retryAfterSeconds())); + } else if (!unavailable) { + response.setHeader("WWW-Authenticate", challenge); + } + mapper.writeValue(response.getOutputStream(), new ErrorResponse( + new ErrorResponse.ErrorBody( + rateLimited ? "rate_limited" : unavailable ? "unavailable" : "unauthorized", + rateLimited ? "Too many login attempts" + : unavailable ? "Authentication service temporarily unavailable" : "Authentication required", + requestId))); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java b/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java new file mode 100644 index 0000000..03c3951 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.model.User; + +public record SessionPrincipal(User user, byte[] tokenHash) { + public SessionPrincipal { + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java b/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java new file mode 100644 index 0000000..9925f6f --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java @@ -0,0 +1,54 @@ +package com.example.mtusi_messenger.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.List; + +@Component +public class TrustedClientCertificateFilter extends OncePerRequestFilter { + private final String allowedUri; + + public TrustedClientCertificateFilter( + @Value("${messenger.mtls.allowed-client-uri:}") String allowedUri) { + this.allowedUri = allowedUri; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return allowedUri.isBlank(); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + X509Certificate[] certificates = (X509Certificate[]) request.getAttribute( + "jakarta.servlet.request.X509Certificate"); + if (certificates == null || certificates.length == 0 || !hasAllowedUri(certificates[0])) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Client certificate identity is not allowed"); + return; + } + chain.doFilter(request, response); + } + + private boolean hasAllowedUri(X509Certificate certificate) { + try { + Collection> names = certificate.getSubjectAlternativeNames(); + if (names == null) return false; + return names.stream().anyMatch(name -> name.size() >= 2 + && Integer.valueOf(6).equals(name.get(0)) + && allowedUri.equals(name.get(1))); + } catch (CertificateParsingException e) { + return false; + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java new file mode 100644 index 0000000..415abb0 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentReconciler.java @@ -0,0 +1,106 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.Set; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class AttachmentReconciler { + private static final Logger log = LoggerFactory.getLogger(AttachmentReconciler.class); + private static final String PREFIX = "attachments/"; + private final AttachmentRepository attachments; + private final ObjectStorage storage; + private final Duration gracePeriod; + private final boolean dryRun; + private final Clock clock; + + @Autowired + public AttachmentReconciler( + AttachmentRepository attachments, + ObjectStorage storage, + @Value("${messenger.attachments.cleanup-grace-seconds:3600}") long graceSeconds, + @Value("${messenger.attachments.cleanup-dry-run:false}") boolean dryRun + ) { + this(attachments, storage, Duration.ofSeconds(graceSeconds), dryRun, Clock.systemUTC()); + } + + AttachmentReconciler(AttachmentRepository attachments, + ObjectStorage storage, + Duration gracePeriod, + boolean dryRun, + Clock clock) { + if (gracePeriod.isNegative() || gracePeriod.isZero()) { + throw new IllegalArgumentException("Attachment cleanup grace period must be positive"); + } + this.attachments = attachments; + this.storage = storage; + this.gracePeriod = gracePeriod; + this.dryRun = dryRun; + this.clock = clock; + } + + @Scheduled( + fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}", + initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}") + public void scheduledReconcile() { + try { + Report report = reconcile(); + if (report.orphanObjects() > 0 || report.missingObjects() > 0) { + log.warn("Attachment reconciliation: {} orphan, {} deleted, {} missing, dryRun={}", + report.orphanObjects(), report.deletedObjects(), report.missingObjects(), dryRun); + } + } catch (RuntimeException error) { + log.warn("Attachment reconciliation postponed: {}", error.getMessage()); + } + } + + public Report reconcile() { + Set databaseKeys = attachments.findAllObjectKeys(); + var storedObjects = storage.list(PREFIX); + Set storageKeys = new HashSet<>(); + Instant deleteBefore = clock.instant().minus(gracePeriod); + int orphans = 0; + int deleted = 0; + + for (ObjectStorage.StoredObject object : storedObjects) { + storageKeys.add(object.objectKey()); + if (!databaseKeys.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) { + orphans++; + if (!dryRun) { + storage.delete(object.objectKey()); + deleted++; + } + } + } + + int missing = 0; + for (String databaseKey : databaseKeys) { + if (!storageKeys.contains(databaseKey)) { + missing++; + log.error("Attachment metadata references missing object {}", databaseKey); + } + } + return new Report(databaseKeys.size(), storedObjects.size(), orphans, deleted, missing, dryRun); + } + + public record Report(int metadataObjects, + int storageObjects, + int orphanObjects, + int deletedObjects, + int missingObjects, + boolean dryRun) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java new file mode 100644 index 0000000..cff2617 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AttachmentService.java @@ -0,0 +1,295 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; +import com.example.mtusi_messenger.queue.AttachmentJobPublisher; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.example.mtusi_messenger.storage.ObjectStorageException; +import com.github.f4b6a3.uuid.UuidCreator; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +@Service +public class AttachmentService { + private static final List ALLOWED_TYPES = List.of("image/png", "image/jpeg"); + private final AttachmentRepository attachments; + private final ChatService chats; + private final ObjectStorage storage; + private final AttachmentJobPublisher publisher; + private final TransactionTemplate transaction; + private final long maxUploadBytes; + private final long maxImagePixels; + private final Semaphore uploadPermits; + private final long uploadPermitWaitMillis; + private final boolean injectCrashAfterOutboxCommit; + private final int pipelineVersion; + + public AttachmentService( + AttachmentRepository attachments, + ChatService chats, + ObjectStorage storage, + AttachmentJobPublisher publisher, + TransactionTemplate transaction, + @Value("${messenger.attachments.max-upload-bytes:10485760}") long maxUploadBytes, + @Value("${messenger.attachments.max-image-pixels:40000000}") long maxImagePixels, + @Value("${messenger.attachments.max-concurrent-uploads:3}") int maxConcurrentUploads, + @Value("${messenger.attachments.upload-permit-wait-millis:10000}") long uploadPermitWaitMillis, + @Value("${messenger.jobs.fault-crash-after-outbox-commit:false}") boolean injectCrashAfterOutboxCommit, + @Value("${messenger.jobs.pipeline-version:2}") int pipelineVersion + ) { + this.attachments = attachments; + this.chats = chats; + this.storage = storage; + this.publisher = publisher; + this.transaction = transaction; + this.maxUploadBytes = maxUploadBytes; + this.maxImagePixels = maxImagePixels; + if (maxConcurrentUploads < 1 || uploadPermitWaitMillis < 1) { + throw new IllegalArgumentException("Upload concurrency limits must be positive"); + } + this.uploadPermits = new Semaphore(maxConcurrentUploads, true); + this.uploadPermitWaitMillis = uploadPermitWaitMillis; + this.injectCrashAfterOutboxCommit = injectCrashAfterOutboxCommit; + if (pipelineVersion < AttachmentJob.MIN_PIPELINE_VERSION + || pipelineVersion > AttachmentJob.CURRENT_PIPELINE_VERSION) { + throw new IllegalArgumentException("Unsupported attachment pipeline version"); + } + this.pipelineVersion = pipelineVersion; + } + + public Attachment upload(UUID chatId, + UUID ownerId, + String filename, + String declaredContentType, + long declaredLength, + InputStream input) { + chats.getAccessible(chatId, ownerId); + String safeFilename = validateFilename(filename); + String contentType = normalizeContentType(declaredContentType); + if (declaredLength > maxUploadBytes) { + throw ApiExceptions.payloadTooLarge("Attachment exceeds 10 MiB"); + } + + try { + try { + if (!uploadPermits.tryAcquire(uploadPermitWaitMillis, TimeUnit.MILLISECONDS)) { + throw ApiExceptions.tooManyRequests("Upload capacity is temporarily exhausted"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw ApiExceptions.unavailable("Upload was interrupted"); + } + try { + return storeValidated(chatId, ownerId, safeFilename, contentType, input); + } finally { + uploadPermits.release(); + } + } catch (com.example.mtusi_messenger.exception.ApiException error) { + throw error; + } + } + + private Attachment storeValidated(UUID chatId, + UUID ownerId, + String safeFilename, + String contentType, + InputStream input) { + byte[] bytes = readBounded(input); + if (bytes.length == 0) { + throw ApiExceptions.unsupportedMediaType("Image is empty"); + } + validateImage(bytes, contentType); + + UUID id = UuidCreator.getTimeOrderedEpochPlus1(); + String objectKey = "attachments/" + id + "/original"; + String stagingKey = "staging/" + id + "/original"; + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + AttachmentJob job = AttachmentJob.first(UUID.randomUUID(), id, pipelineVersion, now); + Attachment attachment = new Attachment(id, chatId, ownerId, safeFilename, contentType, + bytes.length, sha256(bytes), objectKey, stagingKey, "queued", List.of(), + null, now, now); + + storage.put(stagingKey, bytes, contentType); + try { + Attachment saved = transaction.execute(status -> attachments.saveQueued(attachment, job)); + if (injectCrashAfterOutboxCommit && attachments.markPublishFaultInjected(job.jobId())) { + // Opt-in fault injection for the exact DB COMMIT -> broker publish window. + // The persisted outbox row remains unpublished and is recovered after restart. + Runtime.getRuntime().halt(87); + } + try { + publisher.publish(job); + attachments.markPublished(job.jobId()); + return saved; + } catch (RuntimeException publishFailure) { + // The database job and staging object are intentionally retained. + // The scheduled republisher closes the DB-commit -> broker window. + throw ApiExceptions.unavailable("Attachment was staged; queue publication is pending"); + } + } catch (RuntimeException databaseFailure) { + if (databaseFailure instanceof com.example.mtusi_messenger.exception.ApiException) { + throw databaseFailure; + } + try { + storage.delete(stagingKey); + } catch (RuntimeException cleanupFailure) { + databaseFailure.addSuppressed(cleanupFailure); + } + throw databaseFailure; + } + } + + public Attachment getAccessible(UUID attachmentId, UUID userId) { + Attachment attachment = attachments.findById(attachmentId) + .orElseThrow(() -> ApiExceptions.notFound("Attachment not found")); + chats.getAccessible(attachment.chatId(), userId); + return attachment; + } + + public Download download(UUID attachmentId, UUID userId) { + return download(attachmentId, userId, "original"); + } + + public Download download(UUID attachmentId, UUID userId, String variantName) { + Attachment attachment = getAccessible(attachmentId, userId); + if (!"ready".equals(attachment.status())) { + throw ApiExceptions.conflict("Attachment content is not ready"); + } + if ("original".equals(variantName)) { + return new Download(attachment, attachment.contentType(), attachment.filename(), + storage.get(attachment.objectKey())); + } + if (!List.of("thumbnail", "crop", "optimized").contains(variantName)) { + throw ApiExceptions.invalid("Unsupported attachment variant"); + } + AttachmentVariant variant = attachment.variants().stream() + .filter(candidate -> candidate.name().equals(variantName)) + .findFirst() + .orElseThrow(() -> ApiExceptions.notFound("Attachment variant not found")); + String extension = "image/webp".equals(variant.contentType()) ? ".webp" : ".jpg"; + return new Download(attachment, variant.contentType(), variantName + extension, + storage.get(variant.objectKey())); + } + + public void validateForMessage(UUID chatId, List attachmentIds) { + if (attachmentIds.isEmpty()) { + return; + } + if (attachments.findAllByIdsInChat(chatId, attachmentIds).size() != attachmentIds.size()) { + throw ApiExceptions.notFound("Attachment not found"); + } + } + + private byte[] readBounded(InputStream input) { + try { + ByteArrayOutputStream output = new ByteArrayOutputStream( + (int) Math.min(maxUploadBytes, 1024 * 1024)); + byte[] chunk = new byte[8192]; + long total = 0; + int read; + while ((read = input.read(chunk)) != -1) { + total += read; + if (total > maxUploadBytes) { + throw ApiExceptions.payloadTooLarge("Attachment exceeds 10 MiB"); + } + output.write(chunk, 0, read); + } + return output.toByteArray(); + } catch (IOException error) { + throw ApiExceptions.invalid("Cannot read request body"); + } + } + + private void validateImage(byte[] bytes, String declaredContentType) { + ImageIO.setUseCache(false); + try (var imageInput = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) { + if (imageInput == null) { + throw ApiExceptions.unsupportedMediaType("Invalid image"); + } + Iterator readers = ImageIO.getImageReaders(imageInput); + if (!readers.hasNext()) { + throw ApiExceptions.unsupportedMediaType("Invalid PNG/JPEG image"); + } + ImageReader reader = readers.next(); + try { + reader.setInput(imageInput, true, true); + String actualType = switch (reader.getFormatName().toLowerCase(Locale.ROOT)) { + case "png" -> "image/png"; + case "jpeg", "jpg" -> "image/jpeg"; + default -> throw ApiExceptions.unsupportedMediaType("Only PNG and JPEG are supported"); + }; + if (!actualType.equals(declaredContentType)) { + throw ApiExceptions.unsupportedMediaType("Content-Type does not match image bytes"); + } + int width = reader.getWidth(0); + int height = reader.getHeight(0); + if (width <= 0 || height <= 0) { + throw ApiExceptions.unsupportedMediaType("Invalid image dimensions"); + } + if ((long) width * height > maxImagePixels) { + throw ApiExceptions.payloadTooLarge("Image exceeds 40 million pixels"); + } + if (reader.read(0) == null) { + throw ApiExceptions.unsupportedMediaType("Image cannot be decoded"); + } + } finally { + reader.dispose(); + } + } catch (com.example.mtusi_messenger.exception.ApiException error) { + throw error; + } catch (IOException | RuntimeException error) { + throw ApiExceptions.unsupportedMediaType("Corrupted PNG/JPEG image"); + } + } + + private static String validateFilename(String filename) { + if (filename == null || filename.isBlank() || filename.length() > 255 + || filename.equals(".") || filename.equals("..") + || filename.indexOf('/') >= 0 || filename.indexOf('\\') >= 0 + || filename.codePoints().anyMatch(Character::isISOControl)) { + throw ApiExceptions.invalid("Invalid filename"); + } + return filename; + } + + private static String normalizeContentType(String contentType) { + String normalized = contentType == null ? "" : contentType.split(";", 2)[0].trim().toLowerCase(Locale.ROOT); + if (!ALLOWED_TYPES.contains(normalized)) { + throw ApiExceptions.unsupportedMediaType("Only image/png and image/jpeg are supported"); + } + return normalized; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + public record Download(Attachment attachment, String contentType, String filename, byte[] bytes) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java b/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java new file mode 100644 index 0000000..5d7498a --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java @@ -0,0 +1,114 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.cache.UserCache; +import com.example.mtusi_messenger.model.Session; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.SessionRepository; +import com.example.mtusi_messenger.repository.UserRepository; +import com.example.mtusi_messenger.security.SessionPrincipal; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.UUID; + +@Service +public class AuthenticationService { + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + private final UserRepository users; + private final SessionRepository sessions; + private final UserCache userCache; + private final long ttlSeconds; + private final int maximumActiveSessions; + + public AuthenticationService( + UserRepository users, + SessionRepository sessions, + UserCache userCache, + @Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds, + @Value("${messenger.session.maximum-active:3}") int maximumActiveSessions + ) { + if (ttlSeconds < 300 || ttlSeconds > 86400) { + throw new IllegalArgumentException("Session TTL must be between 5 minutes and 24 hours"); + } + if (maximumActiveSessions < 1 || maximumActiveSessions > 20) { + throw new IllegalArgumentException("Maximum active sessions must be between 1 and 20"); + } + this.users = users; + this.sessions = sessions; + this.userCache = userCache; + this.ttlSeconds = ttlSeconds; + this.maximumActiveSessions = maximumActiveSessions; + } + + @Transactional + public IssuedSession issueSession(User user) { + String token = newToken(); + Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Instant expiresAt = createdAt.plusSeconds(ttlSeconds); + sessions.lockUserSessions(user.id()); + sessions.save(new Session( + UUID.randomUUID(), + user.id(), + hashToken(token), + createdAt, + expiresAt)); + sessions.revokeExcessActive(user.id(), maximumActiveSessions); + return new IssuedSession(token, expiresAt, user); + } + + public SessionPrincipal authenticateBearer(String token) { + byte[] tokenHash = hashToken(token); + try { + UUID userId = sessions.findActiveUserId(tokenHash) + .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); + User user = userCache.find(userId).orElseGet(() -> { + User loaded = users.findById(userId) + .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); + userCache.put(loaded); + return loaded; + }); + return new SessionPrincipal(user, tokenHash); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + } + + public void revoke(SessionPrincipal principal) { + try { + if (!sessions.revoke(principal.tokenHash())) { + throw new BadCredentialsException("Invalid or expired session"); + } + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + } + + private String newToken() { + byte[] bytes = new byte[32]; + SECURE_RANDOM.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private byte[] hashToken(String token) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + public record IssuedSession(String token, Instant expiresAt, User user) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/service/ChatService.java b/src/main/java/com/example/mtusi_messenger/service/ChatService.java new file mode 100644 index 0000000..38eeff2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/ChatService.java @@ -0,0 +1,38 @@ +package com.example.mtusi_messenger.service; + +import org.springframework.stereotype.Service; +import com.example.mtusi_messenger.dto.CreateChatRequest; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.repository.ChatRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; + +@Service +public class ChatService { + private final ChatRepository chats; private final UserService users; private final CursorService cursors; + public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; } + public Chat create(CreateChatRequest r, UUID caller) { + Set ids = new LinkedHashSet<>(r.member_ids()); + if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids"); + for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids"); + return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids), + Instant.now().truncatedTo(ChronoUnit.MICROS))); + } + public Chat getAccessible(UUID chatId, UUID userId) { + users.get(userId); + if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found"); + return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found")); + } + public List page(UUID userId, int limit, String cursor) { + CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId); + return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1); + } + public String nextCursor(UUID userId, + Chat last, + boolean hasNext + ) { + return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/CursorService.java b/src/main/java/com/example/mtusi_messenger/service/CursorService.java new file mode 100644 index 0000000..87cd7ff --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/CursorService.java @@ -0,0 +1,40 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.stereotype.Service; +import com.example.mtusi_messenger.exception.ApiExceptions; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +@Service +public class CursorService { + private final ObjectMapper mapper; + public CursorService(ObjectMapper mapper) { this.mapper = mapper; } + + public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) { + try { + byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id)); + return Base64.getUrlEncoder().withoutPadding().encodeToString(json); + } catch (Exception e) { throw new IllegalStateException(e); } + } + public Cursor decode(String raw, String resource, UUID resourceId) { + if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + try { + CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class); + if (p.v != 1 + || !resource.equals(p.resource) + || !Objects.equals(resourceId, p.resourceId) + || p.createdAt() == null + || p.createdAt().isBlank() + || p.id() == null + ) throw ApiExceptions.invalid("Invalid cursor"); + return new Cursor(Instant.parse(p.createdAt), p.id); + } catch (ApiException e) { throw e; } + catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); } + } + public record Cursor(Instant createdAt, UUID id) {} + private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {} + private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/MessageService.java b/src/main/java/com/example/mtusi_messenger/service/MessageService.java new file mode 100644 index 0000000..c164553 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/MessageService.java @@ -0,0 +1,102 @@ +package com.example.mtusi_messenger.service; + +import com.github.f4b6a3.uuid.UuidCreator; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.IdempotentMessage; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.example.mtusi_messenger.dto.CreateMessageRequest; +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.repository.MessageRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +@Service +public class MessageService { + private static final String METHOD = "POST"; + private final MessageRepository messages; + private final ChatService chats; + private final CursorService cursors; + private final AttachmentService attachments; + private final Duration idempotencyTtl; + + public MessageService( + MessageRepository messages, + ChatService chats, + CursorService cursors, + AttachmentService attachments, + @Value("${messenger.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds + ) { + if (idempotencyTtlSeconds < 86400) { + throw new IllegalArgumentException("Idempotency TTL must be at least 24 hours"); + } + this.messages = messages; + this.chats = chats; + this.cursors = cursors; + this.attachments = attachments; + this.idempotencyTtl = Duration.ofSeconds(idempotencyTtlSeconds); + } + + @Transactional + public Message create(UUID chatId, UUID senderId, CreateMessageRequest r, String idempotencyKey) { + chats.getAccessible(chatId, senderId); + attachments.validateForMessage(chatId, r.attachment_ids()); + String path = "/api/v1/chats/" + chatId + "/messages"; + byte[] requestHash = hash(r.text(), r.attachment_ids()); + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + + // The transaction-scoped PostgreSQL advisory lock serializes the same + // idempotency scope across every API replica. A hash collision only + // causes harmless extra serialization; the full scope is still checked. + messages.lockIdempotencyScope(senderId, METHOD, path, idempotencyKey); + messages.deleteExpiredIdempotency( + senderId, METHOD, path, idempotencyKey, now.minus(idempotencyTtl)); + + var existing = messages.findIdempotent(senderId, METHOD, path, idempotencyKey); + if (existing.isPresent()) { + IdempotentMessage value = existing.get(); + if (!Arrays.equals(value.requestHash(), requestHash)) { + throw ApiExceptions.conflict("Idempotency-Key was already used with another request body"); + } + return value.message(); + } + + Message message = messages.save(new Message( + UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, r.text(), now, + r.attachment_ids())); + messages.saveIdempotency( + senderId, METHOD, path, idempotencyKey, requestHash, message.id(), now); + return message; + } + + private static byte[] hash(String text, List attachmentIds) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] textBytes = text.getBytes(StandardCharsets.UTF_8); + digest.update(java.nio.ByteBuffer.allocate(Integer.BYTES).putInt(textBytes.length).array()); + digest.update(textBytes); + for (UUID id : attachmentIds) { + digest.update(java.nio.ByteBuffer.allocate(16) + .putLong(id.getMostSignificantBits()) + .putLong(id.getLeastSignificantBits()).array()); + } + return digest.digest(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + public List page(UUID chatId, UUID userId, int limit, String cursor) { + chats.getAccessible(chatId, userId); + CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId); + return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1); + } + public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java new file mode 100644 index 0000000..3b14c4b --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/ReadinessService.java @@ -0,0 +1,85 @@ +package com.example.mtusi_messenger.service; + +import org.springframework.boot.availability.ApplicationAvailability; +import org.springframework.boot.availability.AvailabilityChangeEvent; +import org.springframework.boot.availability.ReadinessState; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.concurrent.atomic.AtomicBoolean; + +@Service +public class ReadinessService { + private final JdbcTemplate jdbc; + private final StringRedisTemplate redis; + private final ApplicationAvailability availability; + private final ApplicationEventPublisher events; + private final AtomicBoolean dependencyUnavailable = new AtomicBoolean(false); + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + + public ReadinessService( + JdbcTemplate jdbc, + StringRedisTemplate redis, + ApplicationAvailability availability, + ApplicationEventPublisher events + ) { + this.jdbc = jdbc; + this.redis = redis; + this.availability = availability; + this.events = events; + } + + public boolean probeDependencies() { + try { + // Redis is an optional cache. Ping only warms the lazy connection; + // its failure must not make the authoritative API unavailable. + redis.execute((RedisCallback) connection -> connection.ping()); + } catch (DataAccessException ignored) { + // PostgreSQL remains the source of truth. + } + + try { + // The schema-level probe proves that both the shared idempotency + // schema (lab3) and the attachment schema (lab4/lab5) completed + // before this replica is allowed to serve business traffic. + jdbc.queryForObject(""" + SELECT (SELECT count(*) FROM message_idempotency) + + (SELECT count(*) FROM attachments) + """, Long.class); + markDependenciesAvailable(); + return true; + } catch (DataAccessException e) { + markDependenciesUnavailable(); + return false; + } + } + + public boolean acceptsBusinessTraffic() { + return !shuttingDown.get() + && !dependencyUnavailable.get() + && availability.getReadinessState() == ReadinessState.ACCEPTING_TRAFFIC; + } + + @EventListener(ContextClosedEvent.class) + void onContextClosed() { + shuttingDown.set(true); + } + + private void markDependenciesUnavailable() { + dependencyUnavailable.set(true); + AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC); + } + + private void markDependenciesAvailable() { + boolean recovered = dependencyUnavailable.getAndSet(false); + if (recovered && !shuttingDown.get()) { + AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java b/src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java new file mode 100644 index 0000000..f347f89 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/StagingCleaner.java @@ -0,0 +1,65 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.Clock; +import java.time.Duration; +import java.util.Set; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) +public class StagingCleaner { + private static final Logger log = LoggerFactory.getLogger(StagingCleaner.class); + private static final String PREFIX = "staging/"; + private final AttachmentRepository attachments; + private final ObjectStorage storage; + private final Duration retention; + private final Clock clock; + + @Autowired + public StagingCleaner( + AttachmentRepository attachments, + ObjectStorage storage, + @Value("${messenger.attachments.staging-retention-seconds:86400}") long retentionSeconds) { + this(attachments, storage, Duration.ofSeconds(retentionSeconds), Clock.systemUTC()); + } + + StagingCleaner( + AttachmentRepository attachments, + ObjectStorage storage, + Duration retention, + Clock clock) { + if (retention.isZero() || retention.isNegative()) { + throw new IllegalArgumentException("Staging retention must be positive"); + } + this.attachments = attachments; + this.storage = storage; + this.retention = retention; + this.clock = clock; + } + + @Scheduled( + fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}", + initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}") + public void cleanup() { + try { + Set active = attachments.findActiveStagingKeys(); + var deleteBefore = clock.instant().minus(retention); + for (ObjectStorage.StoredObject object : storage.list(PREFIX)) { + if (!active.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) { + storage.delete(object.objectKey()); + } + } + } catch (RuntimeException error) { + log.warn("Staging cleanup postponed: {}", error.getMessage()); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/UserService.java b/src/main/java/com/example/mtusi_messenger/service/UserService.java new file mode 100644 index 0000000..c8bed8b --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/UserService.java @@ -0,0 +1,34 @@ +package com.example.mtusi_messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.security.crypto.password.PasswordEncoder; +import com.example.mtusi_messenger.dto.CreateUserRequest; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.UserRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class UserService { + private final UserRepository users; + private final PasswordEncoder passwordEncoder; + + public User create(CreateUserRequest r) { + String username = r.username(); String display = r.display_name(); + if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken"); + String passwordHash = passwordEncoder.encode(r.password()); + try { + return users.save(new User(UUID.randomUUID(), username, display, + Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash); + } catch (DuplicateKeyException e) { + throw ApiExceptions.conflict("Username is already taken"); + } + } + public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); } + public boolean exists(UUID id) { return users.findById(id).isPresent(); } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java b/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java new file mode 100644 index 0000000..ea292fe --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java @@ -0,0 +1,27 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiExceptions; + +import java.util.UUID; +import java.util.regex.Pattern; + +public final class UuidValidator { + + private static final Pattern UUID_PATTERN = Pattern.compile( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + ); + + private UuidValidator() {} + + public static UUID parse(String value) { + if (value == null || !UUID_PATTERN.matcher(value).matches()) { + throw ApiExceptions.invalid("Invalid UUID"); + } + + try { + return UUID.fromString(value); + } catch (IllegalArgumentException e) { + throw ApiExceptions.invalid("Invalid UUID"); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java b/src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java new file mode 100644 index 0000000..b50f4b4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/storage/MinioObjectStorage.java @@ -0,0 +1,92 @@ +package com.example.mtusi_messenger.storage; + +import io.minio.GetObjectArgs; +import io.minio.MinioClient; +import io.minio.ListObjectsArgs; +import io.minio.PutObjectArgs; +import io.minio.RemoveObjectArgs; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import okhttp3.OkHttpClient; + +import java.io.ByteArrayInputStream; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +@Component +public class MinioObjectStorage implements ObjectStorage { + private final MinioClient client; + private final String bucket; + + public MinioObjectStorage( + @Value("${messenger.s3.endpoint}") String endpoint, + @Value("${messenger.s3.access-key}") String accessKey, + @Value("${messenger.s3.secret-key}") String secretKey, + @Value("${messenger.s3.bucket}") String bucket, + @Value("${messenger.s3.region:us-east-1}") String region + ) { + OkHttpClient httpClient = new OkHttpClient.Builder() + .connectTimeout(Duration.ofSeconds(2)) + .readTimeout(Duration.ofSeconds(10)) + .writeTimeout(Duration.ofSeconds(10)) + .callTimeout(Duration.ofSeconds(15)) + .build(); + this.client = MinioClient.builder() + .endpoint(endpoint) + .credentials(accessKey, secretKey) + .region(region) + .httpClient(httpClient) + .build(); + this.bucket = bucket; + } + + @Override + public void put(String objectKey, byte[] bytes, String contentType) { + try (var stream = new ByteArrayInputStream(bytes)) { + client.putObject(PutObjectArgs.builder() + .bucket(bucket) + .object(objectKey) + .contentType(contentType) + .stream(stream, bytes.length, -1) + .build()); + } catch (Exception error) { + throw new ObjectStorageException("Cannot write attachment object", error); + } + } + + @Override + public byte[] get(String objectKey) { + try (var stream = client.getObject(GetObjectArgs.builder() + .bucket(bucket).object(objectKey).build())) { + return stream.readAllBytes(); + } catch (Exception error) { + throw new ObjectStorageException("Cannot read attachment object", error); + } + } + + @Override + public void delete(String objectKey) { + try { + client.removeObject(RemoveObjectArgs.builder() + .bucket(bucket).object(objectKey).build()); + } catch (Exception error) { + throw new ObjectStorageException("Cannot remove attachment object", error); + } + } + + @Override + public List list(String prefix) { + try { + List objects = new ArrayList<>(); + for (var result : client.listObjects(ListObjectsArgs.builder() + .bucket(bucket).prefix(prefix).recursive(true).build())) { + var item = result.get(); + objects.add(new StoredObject(item.objectName(), item.lastModified().toInstant(), item.size())); + } + return List.copyOf(objects); + } catch (Exception error) { + throw new ObjectStorageException("Cannot list attachment objects", error); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java new file mode 100644 index 0000000..bb521dd --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorage.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.storage; + +import java.time.Instant; +import java.util.List; + +public interface ObjectStorage { + void put(String objectKey, byte[] bytes, String contentType); + byte[] get(String objectKey); + void delete(String objectKey); + List list(String prefix); + + record StoredObject(String objectKey, Instant lastModified, long sizeBytes) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java new file mode 100644 index 0000000..6173a46 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/storage/ObjectStorageException.java @@ -0,0 +1,7 @@ +package com.example.mtusi_messenger.storage; + +public class ObjectStorageException extends RuntimeException { + public ObjectStorageException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java b/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java new file mode 100644 index 0000000..d9209c3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java @@ -0,0 +1,56 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.dao.DataAccessException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.exception.ApiException; +import com.example.mtusi_messenger.storage.ObjectStorageException; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(ApiException.class) + ResponseEntity api(ApiException e, HttpServletRequest req) { + var body = body(e.code(), e.getMessage(), req); + var builder = ResponseEntity.status(e.status()); + if (e.status() == HttpStatus.UNAUTHORIZED && e.authenticate() != null) { + builder.header("WWW-Authenticate", e.authenticate()); + } + if (e.status() == HttpStatus.TOO_MANY_REQUESTS) { + builder.header("Retry-After", "1"); + } + return builder.body(body); + } + @ExceptionHandler({MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class}) + ResponseEntity bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); } + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + ResponseEntity unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); } + @ExceptionHandler(DataAccessException.class) + ResponseEntity unavailable(DataAccessException e, HttpServletRequest req) { + return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req)); + } + @ExceptionHandler(ObjectStorageException.class) + ResponseEntity storageUnavailable(ObjectStorageException e, HttpServletRequest req) { + return ResponseEntity.status(503).body(body("unavailable", "Object storage temporarily unavailable", req)); + } + @ExceptionHandler(Exception.class) + ResponseEntity internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); } + private ErrorResponse body( + String code, + String message, + HttpServletRequest req + ) { + String id = (String) req.getAttribute(RequestIdFilter.ATTRIBUTE); + + return new ErrorResponse( + new ErrorResponse.ErrorBody(code, message, id) + ); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java b/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java new file mode 100644 index 0000000..9c56a39 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java @@ -0,0 +1,47 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class InstanceIdFilter extends OncePerRequestFilter { + public static final String HEADER = "X-Instance-Id"; + private final String instanceId; + + public InstanceIdFilter() { + String configured = System.getenv("INSTANCE_ID"); + this.instanceId = configured == null || configured.isBlank() + ? localHostOrRandom() + : configured; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + response.setHeader(HEADER, instanceId); + filterChain.doFilter(request, response); + } + + private static String localHostOrRandom() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + return "api-" + UUID.randomUUID(); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java b/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java new file mode 100644 index 0000000..a4213fc --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = UnicodeBlankValidator.class) +@Target({ FIELD, PARAMETER, RECORD_COMPONENT, ANNOTATION_TYPE }) +@Retention(RUNTIME) +public @interface NotUnicodeBlank { + String message() default "must not be blank"; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java b/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java new file mode 100644 index 0000000..c69594e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/ReadinessGuardFilter.java @@ -0,0 +1,56 @@ +package com.example.mtusi_messenger.web; + +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.service.ReadinessService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +public class ReadinessGuardFilter extends OncePerRequestFilter { + private final ReadinessService readiness; + private final ObjectMapper mapper; + + public ReadinessGuardFilter(ReadinessService readiness, ObjectMapper mapper) { + this.readiness = readiness; + this.mapper = mapper; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/health/") + || path.equals("/swagger-ui.html") + || path.startsWith("/swagger-ui/") + || path.startsWith("/v3/api-docs/") + || path.equals("/v3/api-docs"); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + if (readiness.acceptsBusinessTraffic()) { + filterChain.doFilter(request, response); + return; + } + + response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); + mapper.writeValue(response.getOutputStream(), new ErrorResponse( + new ErrorResponse.ErrorBody( + "unavailable", + "Application is not ready to serve business traffic", + requestId))); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java b/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java new file mode 100644 index 0000000..eef205a --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java @@ -0,0 +1,56 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.web.servlet.HandlerMapping; +import org.springframework.web.filter.OncePerRequestFilter; +import java.io.IOException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RequestIdFilter extends OncePerRequestFilter { + + private static final Logger log = LoggerFactory.getLogger(RequestIdFilter.class); + + public static final String HEADER = "X-Request-Id"; + public static final String ATTRIBUTE = "request_id"; + + @Override + protected void doFilterInternal( + HttpServletRequest req, + HttpServletResponse res, + FilterChain chain + ) throws ServletException, IOException { + + String id = UUID.randomUUID().toString(); + + req.setAttribute(ATTRIBUTE, id); + res.setHeader(HEADER, id); + + try { + MDC.put(ATTRIBUTE, id); + chain.doFilter(req, res); + } finally { + Object routeAttribute = req.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); + String route = routeAttribute == null ? null : routeAttribute.toString(); + if (route != null && !route.startsWith("/health/")) { + log.atInfo() + .addKeyValue("event", "http_request_completed") + .addKeyValue("http.request.method", req.getMethod()) + .addKeyValue("http.route", route) + .addKeyValue("http.response.status_code", res.getStatus()) + .log("HTTP request completed"); + } + MDC.remove(ATTRIBUTE); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java new file mode 100644 index 0000000..5989361 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java @@ -0,0 +1,23 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class UnicodeBlankValidator + implements ConstraintValidator { + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context) { + + if (value == null || value.isEmpty()) { + return false; + } + + return value.codePoints().anyMatch(codePoint -> + !Character.isWhitespace(codePoint) + && !Character.isSpaceChar(codePoint) + ); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java new file mode 100644 index 0000000..dde7ca9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java @@ -0,0 +1,35 @@ +package com.example.mtusi_messenger.web; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = UnicodeSizeValidator.class) +@Target({ + FIELD, + METHOD, + PARAMETER, + ANNOTATION_TYPE +}) +@Retention(RUNTIME) +public @interface UnicodeSize { + + String message() default "size must be between {min} and {max} Unicode code points"; + + int min() default 0; + + int max() default Integer.MAX_VALUE; + + Class[] groups() default {}; + + Class[] payload() default {}; +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java new file mode 100644 index 0000000..f978d54 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class UnicodeSizeValidator + implements ConstraintValidator { + + private int min; + private int max; + + @Override + public void initialize(UnicodeSize annotation) { + this.min = annotation.min(); + this.max = annotation.max(); + } + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context + ) { + if (value == null) { + return true; + } + + int codePointCount = value.codePointCount(0, value.length()); + + return codePointCount >= min + && codePointCount <= max; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java new file mode 100644 index 0000000..e3d42d8 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/worker/AttachmentWorker.java @@ -0,0 +1,315 @@ +package com.example.mtusi_messenger.worker; + +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.AttachmentJob; +import com.example.mtusi_messenger.model.AttachmentVariant; +import com.example.mtusi_messenger.observability.JobTelemetry; +import com.example.mtusi_messenger.queue.RetryPolicy; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.example.mtusi_messenger.storage.ObjectStorageException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rabbitmq.client.Channel; +import jakarta.annotation.PreDestroy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionTemplate; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +@Component +@ConditionalOnProperty(name = "messenger.role", havingValue = "worker") +public class AttachmentWorker { + private static final Logger log = LoggerFactory.getLogger(AttachmentWorker.class); + private final ObjectMapper mapper; + private final AttachmentRepository attachments; + private final ObjectStorage storage; + private final ImageVariantProcessor images; + private final RetryPolicy retryPolicy; + private final TransactionTemplate transaction; + private final JobTelemetry telemetry; + private final int maxAttempts; + private final Duration jobTimeout; + private final Duration leaseDuration; + private final boolean injectCrashBeforeSideEffect; + private final boolean injectCrashAfterSideEffect; + private final boolean injectCrashAfterResultCommit; + private final ExecutorService processingPool; + private final Clock clock = Clock.systemUTC(); + + public AttachmentWorker( + ObjectMapper mapper, + AttachmentRepository attachments, + ObjectStorage storage, + ImageVariantProcessor images, + RetryPolicy retryPolicy, + TransactionTemplate transaction, + JobTelemetry telemetry, + @Value("${messenger.jobs.max-attempts:5}") int maxAttempts, + @Value("${messenger.jobs.timeout:60s}") Duration jobTimeout, + @Value("${messenger.jobs.lease-duration:90s}") Duration leaseDuration, + @Value("${messenger.jobs.fault-crash-before-side-effect:false}") boolean injectCrashBeforeSideEffect, + @Value("${messenger.jobs.fault-crash-after-side-effect:false}") boolean injectCrashAfterSideEffect, + @Value("${messenger.jobs.fault-crash-after-result-commit:false}") boolean injectCrashAfterResultCommit, + @Value("${spring.rabbitmq.listener.simple.concurrency:2}") int concurrency) { + if (maxAttempts < 1 || jobTimeout.isZero() || jobTimeout.isNegative() + || leaseDuration.compareTo(jobTimeout) <= 0 || concurrency < 1) { + throw new IllegalArgumentException("Invalid attachment worker limits"); + } + this.mapper = mapper; + this.attachments = attachments; + this.storage = storage; + this.images = images; + this.retryPolicy = retryPolicy; + this.transaction = transaction; + this.telemetry = telemetry; + this.maxAttempts = maxAttempts; + this.jobTimeout = jobTimeout; + this.leaseDuration = leaseDuration; + this.injectCrashBeforeSideEffect = injectCrashBeforeSideEffect; + this.injectCrashAfterSideEffect = injectCrashAfterSideEffect; + this.injectCrashAfterResultCommit = injectCrashAfterResultCommit; + this.processingPool = Executors.newFixedThreadPool(concurrency, + Thread.ofPlatform().name("attachment-image-", 0).factory()); + } + + @RabbitListener(queues = "${messenger.jobs.queue}") + public void consume(Message message, Channel channel) throws IOException { + long deliveryTag = message.getMessageProperties().getDeliveryTag(); + AttachmentJob job; + try { + job = mapper.readValue(message.getBody(), AttachmentJob.class); + } catch (RuntimeException | IOException invalidMessage) { + telemetry.malformedMessage(); + log.atError() + .addKeyValue("event", "attachment_job_rejected") + .addKeyValue("outcome", "invalid_message") + .log("Rejecting malformed attachment job message"); + channel.basicReject(deliveryTag, false); + return; + } + + Attachment attachment = attachments.findById(job.attachmentId()).orElse(null); + if (attachment == null || "ready".equals(attachment.status()) || "failed".equals(attachment.status())) { + channel.basicAck(deliveryTag, false); + return; + } + + int attempt = Math.max(job.attempt(), attachments.currentAttempt(job.jobId())); + UUID leaseToken = UUID.randomUUID(); + boolean claimed = Boolean.TRUE.equals(transaction.execute(status -> + attachments.claim(job.jobId(), job.attachmentId(), job.pipelineVersion(), + attempt, leaseToken, leaseDuration))); + if (!claimed) { + // A live worker owns the lease, or a terminal state won the race. + // If the owner died, the DB lease reaper will create a new outbox delivery. + channel.basicAck(deliveryTag, false); + return; + } + + long startedNanos = telemetry.started(); + String outcome = "error"; + Future future = processingPool.submit(() -> process(job, leaseToken)); + try { + ProcessOutcome processOutcome = future.get(jobTimeout.toMillis(), TimeUnit.MILLISECONDS); + if (processOutcome.crashAfterCommit()) { + log.atError().addKeyValue("event", "fault_after_result_commit") + .log("Fault injection: halting worker after durable result and before consumer ack"); + Runtime.getRuntime().halt(86); + } + channel.basicAck(deliveryTag, false); + outcome = "success"; + log.atInfo() + .addKeyValue("event", "attachment_job_completed") + .addKeyValue("job.type", AttachmentJob.TYPE) + .addKeyValue("outcome", outcome) + .log("Attachment job completed"); + } catch (TimeoutException timeout) { + future.cancel(true); + retryOrFail(job, leaseToken, attempt, "processing_timeout", deliveryTag, channel); + outcome = attempt >= maxAttempts ? "failed" : "retry"; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + channel.basicNack(deliveryTag, false, true); + outcome = "interrupted"; + } catch (ExecutionException execution) { + Throwable cause = execution.getCause(); + if (cause instanceof ImageVariantProcessor.ProcessingException imageFailure + && imageFailure.permanent()) { + failPermanent(job, leaseToken, imageFailure.errorCode(), deliveryTag, channel); + outcome = "failed"; + } else { + String code = cause instanceof ImageVariantProcessor.ProcessingException imageFailure + ? imageFailure.errorCode() : "processing_failed"; + retryOrFail(job, leaseToken, attempt, code, deliveryTag, channel); + outcome = attempt >= maxAttempts ? "failed" : "retry"; + } + } finally { + telemetry.finished(startedNanos, job.createdAt(), outcome); + } + } + + private ProcessOutcome process(AttachmentJob job, UUID leaseToken) { + if (injectCrashBeforeSideEffect + && attachments.markBeforeEffectFaultInjected(job.jobId(), leaseToken)) { + log.atError().addKeyValue("event", "fault_before_side_effect") + .log("Fault injection: halting worker before object-storage side effect"); + Runtime.getRuntime().halt(84); + } + Attachment attachment = attachments.findById(job.attachmentId()) + .orElseThrow(() -> new ImageVariantProcessor.ProcessingException( + "attachment_missing", true, "Attachment metadata is missing", null)); + byte[] original = loadOriginal(attachment); + if (original.length != attachment.sizeBytes() || !sha256(original).equals(attachment.sha256())) { + throw new ImageVariantProcessor.ProcessingException( + "invalid_image", true, "Staging checksum mismatch", null); + } + + storage.put(attachment.objectKey(), original, attachment.contentType()); + List generated = + images.createVariants(original, job.pipelineVersion()); + List variants = new ArrayList<>(generated.size()); + for (ImageVariantProcessor.GeneratedVariant item : generated) { + String objectKey = "attachments/" + attachment.id() + "/" + + item.name() + "-v" + job.pipelineVersion() + "." + item.extension(); + storage.put(objectKey, item.bytes(), item.contentType()); + variants.add(new AttachmentVariant( + item.name(), item.contentType(), item.bytes().length, + item.width(), item.height(), sha256(item.bytes()), objectKey)); + } + + if (injectCrashAfterSideEffect + && attachments.markAfterEffectFaultInjected(job.jobId(), leaseToken)) { + log.atError().addKeyValue("event", "fault_after_side_effect") + .log("Fault injection: halting worker after object-storage side effect before result commit"); + Runtime.getRuntime().halt(85); + } + + AttachmentRepository.CompletionResult completion = transaction.execute(status -> + attachments.markReady(job.jobId(), job.attachmentId(), leaseToken, + job.pipelineVersion(), variants, injectCrashAfterResultCommit)); + if (completion == null || !completion.completed()) { + return new ProcessOutcome(false); + } + try { + storage.delete(attachment.stagingKey()); + } catch (RuntimeException cleanupFailure) { + log.atWarn().addKeyValue("event", "staging_cleanup_postponed") + .log("Staging cleanup postponed after attachment processing"); + } + return new ProcessOutcome(completion.crashAfterCommit()); + } + + private byte[] loadOriginal(Attachment attachment) { + try { + return storage.get(attachment.stagingKey()); + } catch (ObjectStorageException missingStaging) { + try { + // A pipeline promotion reuses the immutable final original after + // the previous version safely removed its staging object. + return storage.get(attachment.objectKey()); + } catch (ObjectStorageException missingOriginal) { + missingOriginal.addSuppressed(missingStaging); + throw missingOriginal; + } + } + } + + private void failPermanent( + AttachmentJob job, UUID leaseToken, String errorCode, + long deliveryTag, Channel channel) throws IOException { + boolean failed = Boolean.TRUE.equals(transaction.execute(status -> + attachments.markFailed(job.jobId(), job.attachmentId(), job.pipelineVersion(), + leaseToken, errorCode))); + if (failed) { + channel.basicReject(deliveryTag, false); + } else { + channel.basicAck(deliveryTag, false); + } + } + + private void retryOrFail( + AttachmentJob job, UUID leaseToken, int attempt, String errorCode, + long deliveryTag, Channel channel) throws IOException { + try { + if (attempt >= maxAttempts) { + boolean failed = Boolean.TRUE.equals(transaction.execute(status -> + attachments.markFailed(job.jobId(), job.attachmentId(), + job.pipelineVersion(), leaseToken, "retry_exhausted"))); + if (failed) { + log.atError() + .addKeyValue("event", "attachment_job_retry_exhausted") + .addKeyValue("job.type", AttachmentJob.TYPE) + .addKeyValue("outcome", "failed") + .addKeyValue("attempt", attempt) + .addKeyValue("error.code", errorCode) + .log("Attachment job exhausted retry attempts"); + channel.basicReject(deliveryTag, false); + } else { + channel.basicAck(deliveryTag, false); + } + return; + } + + int nextAttempt = attempt + 1; + boolean queued = Boolean.TRUE.equals(transaction.execute(status -> + attachments.markQueuedForRetry( + job.jobId(), job.attachmentId(), job.pipelineVersion(), + leaseToken, nextAttempt, errorCode, + clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt))))); + // The DB outbox is now the durable retry carrier; the current broker + // delivery can be acknowledged without a DB/broker dual write. + channel.basicAck(deliveryTag, false); + if (queued) { + log.atWarn() + .addKeyValue("event", "attachment_job_retry_scheduled") + .addKeyValue("job.type", AttachmentJob.TYPE) + .addKeyValue("outcome", "retry") + .addKeyValue("attempt", nextAttempt) + .addKeyValue("error.code", errorCode) + .log("Attachment job scheduled for retry"); + } else { + log.atInfo().addKeyValue("event", "attachment_job_retry_skipped") + .log("Retry skipped because job lost its lease or became terminal"); + } + } catch (RuntimeException databaseFailure) { + channel.basicNack(deliveryTag, false, true); + } + } + + @PreDestroy + void shutdownPool() { + processingPool.shutdownNow(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record ProcessOutcome(boolean crashAfterCommit) { + } +} diff --git a/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java b/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java new file mode 100644 index 0000000..f7e9faf --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/worker/ImageVariantProcessor.java @@ -0,0 +1,270 @@ +package com.example.mtusi_messenger.worker; + +import net.coobird.thumbnailator.Thumbnails; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.ImageWriteParam; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +@Component +public class ImageVariantProcessor { + private static final long MEBIBYTE = 1024L * 1024L; + private static final long OUTPUT_ALLOWANCE_BYTES = 64L * MEBIBYTE; + private final long maxPixels; + private final long memoryBudgetBytes; + private final Semaphore memoryPermits; + private final Duration memoryWait; + + public ImageVariantProcessor( + @Value("${messenger.jobs.worker-max-pixels:40000000}") long maxPixels, + @Value("${messenger.jobs.worker-memory-budget-bytes:536870912}") long memoryBudgetBytes, + @Value("${messenger.jobs.memory-wait:2s}") Duration memoryWait) { + if (maxPixels < 1 || memoryBudgetBytes < MEBIBYTE || memoryWait.isNegative()) { + throw new IllegalArgumentException("Invalid worker image resource limits"); + } + this.maxPixels = maxPixels; + this.memoryBudgetBytes = memoryBudgetBytes; + this.memoryPermits = new Semaphore((int) Math.min(Integer.MAX_VALUE, + Math.max(1, memoryBudgetBytes / MEBIBYTE)), true); + this.memoryWait = memoryWait; + } + + public List createVariants(byte[] original, int pipelineVersion) { + PipelineProfile profile = PipelineProfile.forVersion(pipelineVersion); + ImageInfo info = inspect(original); + long estimatedBytes; + try { + estimatedBytes = Math.addExact(Math.multiplyExact(info.pixels(), 12L), + OUTPUT_ALLOWANCE_BYTES); + } catch (ArithmeticException overflow) { + throw permanent("image_too_large", "Image memory estimate overflow", overflow); + } + if (estimatedBytes > memoryBudgetBytes) { + throw permanent("image_too_large", "Image exceeds worker memory budget", null); + } + int permits = (int) Math.max(1, (estimatedBytes + MEBIBYTE - 1) / MEBIBYTE); + boolean acquired; + try { + acquired = memoryPermits.tryAcquire(permits, memoryWait.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw temporary("worker_interrupted", "Interrupted while waiting for memory budget", interrupted); + } + if (!acquired) { + throw temporary("worker_capacity", "Worker memory budget is currently exhausted", null); + } + + try { + return transform(original, profile); + } finally { + memoryPermits.release(permits); + } + } + + private ImageInfo inspect(byte[] bytes) { + ImageIO.setUseCache(false); + try (var input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) { + if (input == null) { + throw permanent("invalid_image", "Image input is invalid", null); + } + Iterator readers = ImageIO.getImageReaders(input); + if (!readers.hasNext()) { + throw permanent("invalid_image", "Unsupported image encoding", null); + } + ImageReader reader = readers.next(); + try { + reader.setInput(input, true, true); + int width = reader.getWidth(0); + int height = reader.getHeight(0); + long pixels = Math.multiplyExact((long) width, height); + if (width < 1 || height < 1 || pixels > maxPixels) { + throw permanent("image_too_large", "Image exceeds worker pixel limit", null); + } + return new ImageInfo(width, height, pixels); + } finally { + reader.dispose(); + } + } catch (ProcessingException error) { + throw error; + } catch (IOException | RuntimeException error) { + throw permanent("invalid_image", "Image header cannot be read", error); + } + } + + private List transform(byte[] original, PipelineProfile profile) { + try { + BufferedImage oriented = Thumbnails.of(new ByteArrayInputStream(original)) + .useExifOrientation(true) + .scale(1.0) + .asBufferedImage(); + if (oriented == null || oriented.getWidth() < 1 || oriented.getHeight() < 1) { + throw permanent("invalid_image", "Image cannot be decoded", null); + } + try { + List variants = new ArrayList<>(3); + BufferedImage thumbnail = fit(oriented, 256, BufferedImage.TYPE_INT_RGB, true); + variants.add(encode("thumbnail", "image/jpeg", "jpg", thumbnail, "jpeg", + profile.thumbnailQuality())); + thumbnail.flush(); + + BufferedImage crop = cropSquare(oriented, 128); + variants.add(encode("crop", "image/jpeg", "jpg", crop, "jpeg", + profile.cropQuality())); + crop.flush(); + + int webpType = oriented.getColorModel().hasAlpha() + ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; + BufferedImage optimized = fit(oriented, 1280, webpType, !oriented.getColorModel().hasAlpha()); + variants.add(encode("optimized", "image/webp", "webp", optimized, "webp", + profile.webpQuality())); + optimized.flush(); + return List.copyOf(variants); + } finally { + oriented.flush(); + } + } catch (ProcessingException error) { + throw error; + } catch (IOException | RuntimeException error) { + throw permanent("invalid_image", "Image cannot be transformed", error); + } + } + + private static BufferedImage fit(BufferedImage source, int maxSide, int type, boolean whiteBackground) { + double scale = Math.min(1.0, Math.min( + (double) maxSide / source.getWidth(), + (double) maxSide / source.getHeight())); + int width = Math.max(1, (int) Math.floor(source.getWidth() * scale)); + int height = Math.max(1, (int) Math.floor(source.getHeight() * scale)); + BufferedImage target = new BufferedImage(width, height, type); + Graphics2D graphics = qualityGraphics(target, whiteBackground); + try { + graphics.drawImage(source, 0, 0, width, height, null); + } finally { + graphics.dispose(); + } + return target; + } + + private static BufferedImage cropSquare(BufferedImage source, int side) { + int sourceSide = Math.min(source.getWidth(), source.getHeight()); + int x = (source.getWidth() - sourceSide) / 2; + int y = (source.getHeight() - sourceSide) / 2; + BufferedImage target = new BufferedImage(side, side, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = qualityGraphics(target, true); + try { + graphics.drawImage(source, 0, 0, side, side, + x, y, x + sourceSide, y + sourceSide, null); + } finally { + graphics.dispose(); + } + return target; + } + + private static Graphics2D qualityGraphics(BufferedImage target, boolean whiteBackground) { + Graphics2D graphics = target.createGraphics(); + if (whiteBackground) { + graphics.setColor(Color.WHITE); + graphics.fillRect(0, 0, target.getWidth(), target.getHeight()); + } + graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BICUBIC); + graphics.setRenderingHint(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_QUALITY); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + return graphics; + } + + private static GeneratedVariant encode( + String name, String contentType, String extension, + BufferedImage image, String format, float quality) throws IOException { + Iterator writers = ImageIO.getImageWritersByFormatName(format); + if (!writers.hasNext()) { + throw new IOException(format + " writer is unavailable"); + } + var writer = writers.next(); + try (var output = new ByteArrayOutputStream(); + var imageOutput = ImageIO.createImageOutputStream(output)) { + writer.setOutput(imageOutput); + ImageWriteParam parameters = writer.getDefaultWriteParam(); + if (parameters.canWriteCompressed()) { + parameters.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + String[] compressionTypes = parameters.getCompressionTypes(); + if (compressionTypes != null && compressionTypes.length > 0) { + parameters.setCompressionType(compressionTypes[0]); + } + parameters.setCompressionQuality(quality); + } + // Source metadata is intentionally omitted for every generated variant. + writer.write(null, new IIOImage(image, null, null), parameters); + imageOutput.flush(); + return new GeneratedVariant(name, contentType, extension, output.toByteArray(), + image.getWidth(), image.getHeight()); + } finally { + writer.dispose(); + } + } + + private static ProcessingException permanent(String code, String message, Throwable cause) { + return new ProcessingException(code, true, message, cause); + } + + private static ProcessingException temporary(String code, String message, Throwable cause) { + return new ProcessingException(code, false, message, cause); + } + + private record ImageInfo(int width, int height, long pixels) { + } + + private record PipelineProfile( + int version, float thumbnailQuality, float cropQuality, float webpQuality) { + private static PipelineProfile forVersion(int version) { + return switch (version) { + case 1 -> new PipelineProfile(1, 0.85f, 0.88f, 0.82f); + case 2 -> new PipelineProfile(2, 0.87f, 0.90f, 0.84f); + default -> throw permanent( + "unsupported_pipeline", "Unsupported pipeline version " + version, null); + }; + } + } + + public record GeneratedVariant(String name, String contentType, String extension, + byte[] bytes, int width, int height) { + } + + public static final class ProcessingException extends RuntimeException { + private final String errorCode; + private final boolean permanent; + + public ProcessingException( + String errorCode, boolean permanent, String message, Throwable cause) { + super(message, cause); + this.errorCode = errorCode; + this.permanent = permanent; + } + + public String errorCode() { + return errorCode; + } + + public boolean permanent() { + return permanent; + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..6553b6a --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,174 @@ +spring: + application: + name: mtusi-messenger + + ssl: + bundle: + pem: + redis: + keystore: + certificate: ${CLIENT_TLS_CERTIFICATE:} + private-key: ${CLIENT_TLS_PRIVATE_KEY:} + truststore: + certificate: ${SERVICE_TLS_CA:} + rabbitmq: + keystore: + certificate: ${CLIENT_TLS_CERTIFICATE:} + private-key: ${CLIENT_TLS_PRIVATE_KEY:} + truststore: + certificate: ${SERVICE_TLS_CA:} + + datasource: + url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/messenger} + username: ${DATABASE_USER:messenger} + password: ${DATABASE_PASSWORD:messenger} + hikari: + maximum-pool-size: ${DATABASE_POOL_SIZE:10} + minimum-idle: ${DATABASE_MIN_IDLE:2} + connection-timeout: 5000 + validation-timeout: 2000 + idle-timeout: 600000 + max-lifetime: 1800000 + + data: + redis: + host: ${REDIS_HOST:localhost} + port: ${REDIS_PORT:6379} + connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s} + timeout: ${REDIS_COMMAND_TIMEOUT:500ms} + username: ${REDIS_USER:messenger-api} + password: ${REDIS_PASSWORD:} + ssl: + enabled: ${REDIS_SSL_ENABLED:false} + bundle: ${REDIS_SSL_BUNDLE:redis} + lettuce: + pool: + max-active: ${REDIS_POOL_MAX_ACTIVE:8} + max-idle: ${REDIS_POOL_MAX_IDLE:8} + min-idle: ${REDIS_POOL_MIN_IDLE:0} + max-wait: ${REDIS_POOL_MAX_WAIT:500ms} + + rabbitmq: + host: ${RABBITMQ_HOST:localhost} + port: ${RABBITMQ_PORT:5672} + username: ${RABBITMQ_USER:messenger} + password: ${RABBITMQ_PASSWORD:messenger} + virtual-host: ${RABBITMQ_VHOST:/} + connection-timeout: ${RABBITMQ_CONNECTION_TIMEOUT:5s} + publisher-confirm-type: correlated + publisher-returns: true + ssl: + enabled: ${RABBITMQ_SSL_ENABLED:false} + bundle: ${RABBITMQ_SSL_BUNDLE:rabbitmq} + validate-server-certificate: true + verify-hostname: true + listener: + simple: + acknowledge-mode: manual + default-requeue-rejected: false + prefetch: ${WORKER_PREFETCH:1} + concurrency: ${WORKER_CONCURRENCY:2} + max-concurrency: ${WORKER_CONCURRENCY:2} + + jdbc: + template: + query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5} + + transaction: + default-timeout: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:5} + + flyway: + # API replicas never race one another for migrations. Compose runs the + # same image once as the dedicated migrate service with this overridden. + enabled: ${FLYWAY_ENABLED:false} + locations: classpath:db/migration + + jackson: + deserialization: + fail-on-unknown-properties: true + + lifecycle: + timeout-per-shutdown-phase: 10s + +server: + address: ${APP_HOST:0.0.0.0} + port: ${APP_PORT:8080} + shutdown: graceful + ssl: + enabled: ${SERVER_SSL_ENABLED:false} + certificate: ${SERVER_SSL_CERTIFICATE:} + certificate-private-key: ${SERVER_SSL_PRIVATE_KEY:} + trust-certificate: ${SERVER_SSL_TRUST_CERTIFICATE:} + client-auth: ${SERVER_SSL_CLIENT_AUTH:none} + enabled-protocols: TLSv1.3,TLSv1.2 + +# Spring Boot writes one JSON object per line. The OTel agent injects trace_id +# and span_id into MDC and exports the same records through OTLP. Request and +# message bodies, credentials and signed URLs are never configured for capture. +logging: + structured: + format: + console: logstash + +messenger: + role: ${MESSENGER_ROLE:api} + mtls: + allowed-client-uri: ${MTLS_ALLOWED_CLIENT_URI:} + storage: postgres + password: + argon2: + memory-kib: ${ARGON2_MEMORY_KIB:19456} + iterations: ${ARGON2_ITERATIONS:2} + parallelism: ${ARGON2_PARALLELISM:1} + session: + ttl-seconds: ${SESSION_TTL_SECONDS:3600} + maximum-active: ${SESSION_MAXIMUM_ACTIVE:3} + login-rate-limit: + attempts-per-username: ${LOGIN_ATTEMPTS_PER_USERNAME:5} + attempts-per-source: ${LOGIN_ATTEMPTS_PER_SOURCE:100} + window-seconds: ${LOGIN_RATE_WINDOW_SECONDS:60} + cache: + user-ttl-seconds: ${USER_CACHE_TTL_SECONDS:300} + idempotency: + ttl-seconds: ${IDEMPOTENCY_TTL_SECONDS:86400} + s3: + endpoint: ${S3_ENDPOINT:http://localhost:9000} + region: ${S3_REGION:us-east-1} + bucket: ${S3_BUCKET:messenger-attachments} + access-key: ${S3_ACCESS_KEY_ID:messenger-api} + secret-key: ${S3_SECRET_ACCESS_KEY:messenger-api-local-only} + attachments: + max-upload-bytes: ${MAX_UPLOAD_BYTES:10485760} + max-image-pixels: ${MAX_IMAGE_PIXELS:40000000} + max-concurrent-uploads: ${MAX_CONCURRENT_UPLOADS:3} + upload-permit-wait-millis: ${UPLOAD_PERMIT_WAIT_MILLIS:10000} + staging-retention-seconds: ${STAGING_RETENTION_SECONDS:86400} + cleanup-grace-seconds: ${ATTACHMENT_CLEANUP_GRACE_SECONDS:3600} + cleanup-dry-run: ${ATTACHMENT_CLEANUP_DRY_RUN:false} + reconcile-interval-millis: ${ATTACHMENT_RECONCILE_INTERVAL_MILLIS:600000} + reconcile-initial-delay-millis: ${ATTACHMENT_RECONCILE_INITIAL_DELAY_MILLIS:60000} + jobs: + pipeline-version: ${ATTACHMENT_PIPELINE_VERSION:2} + exchange: ${ATTACHMENT_JOB_EXCHANGE:attachments.v1} + queue: ${ATTACHMENT_JOB_QUEUE:attachments.process.level4.v1} + routing-key: ${ATTACHMENT_JOB_ROUTING_KEY:attachment.process.v1} + dead-letter-exchange: ${ATTACHMENT_DLQ_EXCHANGE:attachments.dlx.v1} + dead-letter-queue: ${ATTACHMENT_DLQ_QUEUE:attachments.failed.v1} + dead-letter-routing-key: ${ATTACHMENT_DLQ_ROUTING_KEY:attachment.failed.v1} + max-attempts: ${JOB_MAX_ATTEMPTS:5} + retry-base-delay: ${JOB_RETRY_BASE_DELAY:1s} + retry-max-delay: ${JOB_RETRY_MAX_DELAY:30s} + timeout: ${JOB_TIMEOUT:60s} + lease-duration: ${JOB_LEASE_DURATION:90s} + lease-reaper-interval: ${JOB_LEASE_REAPER_INTERVAL:5s} + worker-max-pixels: ${WORKER_MAX_IMAGE_PIXELS:40000000} + worker-memory-budget-bytes: ${WORKER_MEMORY_BUDGET_BYTES:536870912} + memory-wait: ${WORKER_MEMORY_WAIT:2s} + publish-confirm-timeout: ${JOB_PUBLISH_CONFIRM_TIMEOUT:5s} + republish-interval: ${JOB_REPUBLISH_INTERVAL:5s} + fault-crash-after-outbox-commit: ${FAULT_CRASH_AFTER_OUTBOX_COMMIT:false} + fault-crash-before-side-effect: ${FAULT_CRASH_BEFORE_SIDE_EFFECT:false} + fault-crash-after-side-effect: ${FAULT_CRASH_AFTER_SIDE_EFFECT:false} + fault-crash-after-result-commit: ${FAULT_CRASH_AFTER_RESULT_COMMIT:false} + observability: + queue-poll-interval: ${OBSERVABILITY_QUEUE_POLL_INTERVAL:5s} diff --git a/src/main/resources/db/migration/V1__create_messenger_schema.sql b/src/main/resources/db/migration/V1__create_messenger_schema.sql new file mode 100644 index 0000000..06885a1 --- /dev/null +++ b/src/main/resources/db/migration/V1__create_messenger_schema.sql @@ -0,0 +1,60 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL, + display_name text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT users_username_uk UNIQUE (username), + CONSTRAINT users_username_format_chk + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length_chk + CHECK (char_length(display_name) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chats_title_length_chk + CHECK (char_length(title) BETWEEN 1 AND 100) +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL, + user_id uuid NOT NULL, + joined_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chat_members_pk PRIMARY KEY (chat_id, user_id), + CONSTRAINT chat_members_chat_fk + FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE, + CONSTRAINT chat_members_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT +); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT messages_text_length_chk + CHECK (char_length(text) BETWEEN 1 AND 4000), + CONSTRAINT messages_sender_membership_fk + FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members(chat_id, user_id) + ON DELETE RESTRICT +); + +CREATE INDEX chat_members_user_chat_idx + ON chat_members (user_id, chat_id); + +CREATE INDEX chats_created_id_idx + ON chats (created_at, id); + +CREATE INDEX messages_chat_created_id_idx + ON messages (chat_id, created_at, id); + +CREATE INDEX messages_sender_created_idx + ON messages (sender_id, created_at); diff --git a/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql b/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql new file mode 100644 index 0000000..d5d7427 --- /dev/null +++ b/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql @@ -0,0 +1,28 @@ +ALTER TABLE users + ADD COLUMN password_hash text; + +ALTER TABLE users + ALTER COLUMN password_hash SET NOT NULL; + +CREATE TABLE sessions ( + id uuid PRIMARY KEY, + user_id uuid NOT NULL, + token_hash bytea NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + + CONSTRAINT sessions_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT sessions_token_hash_uk UNIQUE (token_hash), + CONSTRAINT sessions_token_hash_length_chk + CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_chk + CHECK (expires_at > created_at), + CONSTRAINT sessions_revocation_chk + CHECK (revoked_at IS NULL OR revoked_at >= created_at) +); + +CREATE INDEX sessions_active_expiry_idx + ON sessions (expires_at) + WHERE revoked_at IS NULL; diff --git a/src/main/resources/db/migration/V3__add_message_idempotency.sql b/src/main/resources/db/migration/V3__add_message_idempotency.sql new file mode 100644 index 0000000..dfa127c --- /dev/null +++ b/src/main/resources/db/migration/V3__add_message_idempotency.sql @@ -0,0 +1,25 @@ +CREATE TABLE message_idempotency ( + user_id uuid NOT NULL, + method varchar(8) NOT NULL, + request_path text NOT NULL, + idempotency_key varchar(128) NOT NULL, + request_hash bytea NOT NULL, + message_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT message_idempotency_pk + PRIMARY KEY (user_id, method, request_path, idempotency_key), + CONSTRAINT message_idempotency_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT message_idempotency_message_fk + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE, + CONSTRAINT message_idempotency_method_chk + CHECK (method = 'POST'), + CONSTRAINT message_idempotency_key_format_chk + CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT message_idempotency_hash_length_chk + CHECK (octet_length(request_hash) = 32) +); + +CREATE INDEX message_idempotency_created_idx + ON message_idempotency (created_at); diff --git a/src/main/resources/db/migration/V4__add_attachments.sql b/src/main/resources/db/migration/V4__add_attachments.sql new file mode 100644 index 0000000..ca018eb --- /dev/null +++ b/src/main/resources/db/migration/V4__add_attachments.sql @@ -0,0 +1,53 @@ +ALTER TABLE messages DROP CONSTRAINT messages_text_length_chk; +ALTER TABLE messages ADD CONSTRAINT messages_text_length_chk + CHECK (char_length(text) BETWEEN 0 AND 4000); +ALTER TABLE messages ADD CONSTRAINT messages_id_chat_uk UNIQUE (id, chat_id); + +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + owner_id uuid NOT NULL, + filename varchar(255) NOT NULL, + content_type varchar(32) NOT NULL, + size_bytes bigint NOT NULL, + sha256 char(64) NOT NULL, + object_key text NOT NULL, + status varchar(16) NOT NULL DEFAULT 'ready', + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + + CONSTRAINT attachments_id_chat_uk UNIQUE (id, chat_id), + CONSTRAINT attachments_object_key_uk UNIQUE (object_key), + CONSTRAINT attachments_owner_membership_fk + FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members(chat_id, user_id) ON DELETE RESTRICT, + CONSTRAINT attachments_content_type_chk + CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size_chk + CHECK (size_bytes BETWEEN 1 AND 10485760), + CONSTRAINT attachments_sha256_chk + CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_status_chk CHECK (status = 'ready'), + CONSTRAINT attachments_filename_chk + CHECK (char_length(filename) BETWEEN 1 AND 255) +); + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL, + chat_id uuid NOT NULL, + attachment_id uuid NOT NULL, + position smallint NOT NULL, + + CONSTRAINT message_attachments_pk PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_position_uk UNIQUE (message_id, position), + CONSTRAINT message_attachments_message_fk + FOREIGN KEY (message_id, chat_id) + REFERENCES messages(id, chat_id) ON DELETE CASCADE, + CONSTRAINT message_attachments_attachment_fk + FOREIGN KEY (attachment_id, chat_id) + REFERENCES attachments(id, chat_id) ON DELETE RESTRICT, + CONSTRAINT message_attachments_position_chk CHECK (position BETWEEN 0 AND 9) +); + +CREATE INDEX attachments_chat_created_idx ON attachments (chat_id, created_at, id); +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); diff --git a/src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql b/src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql new file mode 100644 index 0000000..46525a6 --- /dev/null +++ b/src/main/resources/db/migration/V5__add_attachment_processing_jobs.sql @@ -0,0 +1,57 @@ +ALTER TABLE attachments DROP CONSTRAINT attachments_status_chk; +ALTER TABLE attachments + ADD COLUMN staging_key text, + ADD COLUMN error_code varchar(64), + ADD CONSTRAINT attachments_status_chk + CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + ADD CONSTRAINT attachments_error_state_chk + CHECK ((status = 'failed' AND error_code IS NOT NULL) + OR (status <> 'failed' AND error_code IS NULL)); + +CREATE UNIQUE INDEX attachments_staging_key_uk + ON attachments (staging_key) WHERE staging_key IS NOT NULL; + +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version integer NOT NULL, + name varchar(32) NOT NULL, + content_type varchar(32) NOT NULL, + size_bytes bigint NOT NULL, + width integer NOT NULL, + height integer NOT NULL, + sha256 char(64) NOT NULL, + object_key text NOT NULL, + created_at timestamptz NOT NULL, + + CONSTRAINT attachment_variants_pk + PRIMARY KEY (attachment_id, pipeline_version, name), + CONSTRAINT attachment_variants_object_key_uk UNIQUE (object_key), + CONSTRAINT attachment_variants_name_chk + CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_content_type_chk + CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT attachment_variants_size_chk CHECK (size_bytes > 0), + CONSTRAINT attachment_variants_dimensions_chk CHECK (width > 0 AND height > 0), + CONSTRAINT attachment_variants_sha256_chk CHECK (sha256 ~ '^[a-f0-9]{64}$') +); + +CREATE TABLE attachment_jobs ( + id uuid PRIMARY KEY, + attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version integer NOT NULL DEFAULT 1, + attempt integer NOT NULL DEFAULT 1, + status varchar(16) NOT NULL DEFAULT 'queued', + published boolean NOT NULL DEFAULT false, + last_error_code varchar(64), + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + + CONSTRAINT attachment_jobs_pipeline_chk CHECK (pipeline_version > 0), + CONSTRAINT attachment_jobs_attempt_chk CHECK (attempt > 0), + CONSTRAINT attachment_jobs_status_chk + CHECK (status IN ('queued', 'processing', 'ready', 'failed')) +); + +CREATE INDEX attachment_jobs_publish_idx + ON attachment_jobs (published, status, created_at) + WHERE published = false AND status = 'queued'; diff --git a/src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql b/src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql new file mode 100644 index 0000000..1a8539c --- /dev/null +++ b/src/main/resources/db/migration/V6__add_job_leases_replay_and_fault_injection.sql @@ -0,0 +1,41 @@ +ALTER TABLE attachment_jobs + ADD COLUMN next_attempt_at timestamptz, + ADD COLUMN lease_token uuid, + ADD COLUMN lease_until timestamptz, + ADD COLUMN publish_fault_injected boolean NOT NULL DEFAULT false, + ADD COLUMN result_fault_injected boolean NOT NULL DEFAULT false; + +UPDATE attachment_jobs SET next_attempt_at = created_at WHERE next_attempt_at IS NULL; +UPDATE attachment_jobs +SET status = 'queued', published = false, last_error_code = 'lease_migration_recovery' +WHERE status = 'processing'; +UPDATE attachments SET status = 'queued', error_code = NULL WHERE status = 'processing'; +ALTER TABLE attachment_jobs ALTER COLUMN next_attempt_at SET NOT NULL; +ALTER TABLE attachment_jobs ALTER COLUMN next_attempt_at SET DEFAULT clock_timestamp(); + +ALTER TABLE attachment_jobs + ADD CONSTRAINT attachment_jobs_lease_chk CHECK ( + (status = 'processing' AND lease_token IS NOT NULL AND lease_until IS NOT NULL) + OR (status <> 'processing' AND lease_token IS NULL AND lease_until IS NULL) + ); + +DROP INDEX attachment_jobs_publish_idx; +CREATE INDEX attachment_jobs_publish_idx + ON attachment_jobs (next_attempt_at, created_at, id) + WHERE published = false AND status = 'queued'; +CREATE INDEX attachment_jobs_expired_lease_idx + ON attachment_jobs (lease_until) + WHERE status = 'processing'; + +CREATE TABLE attachment_job_replays ( + id bigserial PRIMARY KEY, + job_id uuid NOT NULL REFERENCES attachment_jobs(id) ON DELETE RESTRICT, + requested_by varchar(128) NOT NULL, + previous_attempt integer NOT NULL, + requested_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachment_job_replays_actor_chk + CHECK (char_length(requested_by) BETWEEN 1 AND 128) +); + +CREATE INDEX attachment_job_replays_job_idx + ON attachment_job_replays (job_id, requested_at); diff --git a/src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql b/src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql new file mode 100644 index 0000000..dd50c74 --- /dev/null +++ b/src/main/resources/db/migration/V7__versioned_pipeline_and_fault_points.sql @@ -0,0 +1,33 @@ +ALTER TABLE attachments + ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1, + ADD CONSTRAINT attachments_pipeline_version_chk CHECK (pipeline_version > 0); + +ALTER TABLE attachment_jobs + DROP CONSTRAINT attachment_jobs_attachment_id_key, + DROP CONSTRAINT attachment_jobs_status_chk, + ADD COLUMN before_effect_fault_injected boolean NOT NULL DEFAULT false, + ADD COLUMN after_effect_fault_injected boolean NOT NULL DEFAULT false, + ADD CONSTRAINT attachment_jobs_status_chk + CHECK (status IN ('queued', 'processing', 'ready', 'failed', 'superseded')); + +CREATE UNIQUE INDEX attachment_jobs_attachment_pipeline_uk + ON attachment_jobs (attachment_id, pipeline_version); + +CREATE TABLE attachment_pipeline_promotions ( + id bigserial PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE RESTRICT, + from_version integer NOT NULL, + to_version integer NOT NULL, + job_id uuid NOT NULL REFERENCES attachment_jobs(id) ON DELETE RESTRICT, + requested_by varchar(128) NOT NULL, + requested_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachment_pipeline_promotions_versions_chk + CHECK (from_version > 0 AND to_version > from_version), + CONSTRAINT attachment_pipeline_promotions_actor_chk + CHECK (char_length(requested_by) BETWEEN 1 AND 128), + CONSTRAINT attachment_pipeline_promotions_target_uk + UNIQUE (attachment_id, to_version) +); + +CREATE INDEX attachment_pipeline_promotions_attachment_idx + ON attachment_pipeline_promotions (attachment_id, requested_at); diff --git a/src/main/resources/db/migration/V8__persist_job_trace_context.sql b/src/main/resources/db/migration/V8__persist_job_trace_context.sql new file mode 100644 index 0000000..1e7c6f8 --- /dev/null +++ b/src/main/resources/db/migration/V8__persist_job_trace_context.sql @@ -0,0 +1,12 @@ +ALTER TABLE attachment_jobs + ADD COLUMN trace_parent varchar(55), + ADD COLUMN trace_state text, + ADD CONSTRAINT attachment_jobs_trace_parent_chk CHECK ( + trace_parent IS NULL + OR trace_parent ~ '^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$' + ); + +COMMENT ON COLUMN attachment_jobs.trace_parent IS + 'W3C traceparent used only to continue a durable retry trace'; +COMMENT ON COLUMN attachment_jobs.trace_state IS + 'W3C tracestate used only to continue a durable retry trace'; diff --git a/src/main/resources/db/migration/V9__least_privilege_runtime_roles.sql b/src/main/resources/db/migration/V9__least_privilege_runtime_roles.sql new file mode 100644 index 0000000..225e443 --- /dev/null +++ b/src/main/resources/db/migration/V9__least_privilege_runtime_roles.sql @@ -0,0 +1,9 @@ +GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker; +GRANT SELECT, INSERT, UPDATE, DELETE ON users, sessions, chats, chat_members, + messages, message_idempotency, attachments, message_attachments, + attachment_variants, attachment_jobs, attachment_job_replays, + attachment_pipeline_promotions TO messenger_api; +GRANT SELECT, INSERT, UPDATE, DELETE ON attachments, attachment_variants, + attachment_jobs, attachment_job_replays, attachment_pipeline_promotions TO messenger_worker; +REVOKE ALL ON users, sessions, chats, chat_members, messages, message_idempotency + FROM messenger_worker; diff --git a/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java b/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java new file mode 100644 index 0000000..6a71efe --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java @@ -0,0 +1,368 @@ +package com.example.mtusi_messenger; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +class MtusiMessengerApplicationTests { + + private static final String USERS_URL = "/api/v1/users"; + private static final String CHATS_URL = "/api/v1/chats"; + private static final String SESSIONS_URL = "/api/v1/auth/sessions"; + private static final String TEST_PASSWORD = "correct horse battery staple"; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + private User alice; + private User bob; + private User eve; + + @BeforeEach + void setUp() throws Exception { + String suffix = UUID.randomUUID() + .toString() + .replace("-", "") + .substring(0, 12); + + alice = registerUser("alice_" + suffix, "Alice"); + bob = registerUser("bob_" + suffix, "Bob"); + eve = registerUser("eve_" + suffix, "Eve"); + } + + @Test + void shouldReturn400WhenJsonIsMalformed() throws Exception { + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content("{ \"username\": ")) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn400WhenPasswordContainsOnlyWhitespace() throws Exception { + String requestBody = objectMapper.writeValueAsString( + Map.of( + "username", "blank_password_" + UUID.randomUUID().toString().substring(0, 8), + "display_name", "Blank password probe", + "password", " " + ) + ); + + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldNotAllowNonMemberToReadChatMessages() throws Exception { + String chatId = createChat(alice, bob); + + mockMvc.perform(get(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(eve)) + .param("limit", "10")) + .andExpect(status().isNotFound()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("not_found")); + } + + @Test + void shouldNotAllowNonMemberToSendMessage() throws Exception { + String chatId = createChat(alice, bob); + + String requestBody = """ + { + "text": "Hello from Eve" + } + """; + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(eve)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isNotFound()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("not_found")); + } + + @Test + void shouldReturn400WhenMessageTextIsEmpty() throws Exception { + String chatId = createChat(alice, bob); + + String requestBody = """ + { + "text": "" + } + """; + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn400WhenMessageTextIsMissing() throws Exception { + String chatId = createChat(alice, bob); + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn409WhenUsernameAlreadyExists() throws Exception { + String requestBody = """ + { + "username": "%s", + "display_name": "Another Alice", + "password": "correct horse battery staple" + } + """.formatted(alice.username()); + + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isConflict()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("conflict")); + } + + @Test + void shouldReturnAllMessagesAcrossMultiplePagesWithoutDuplicates() + throws Exception { + + String chatId = createChat(alice, bob); + + int messageCount = 5; + int pageSize = 2; + int expectedPageCount = 3; + + List expectedTexts = new ArrayList<>(); + + for (int i = 1; i <= messageCount; i++) { + String text = "Message " + i; + sendMessage(chatId, alice, text); + expectedTexts.add(text); + } + + List actualIds = new ArrayList<>(); + List actualTexts = new ArrayList<>(); + + String cursor = null; + int pageCount = 0; + + while (true) { + var request = get(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .param("limit", String.valueOf(pageSize)); + + if (cursor != null) { + request.param("cursor", cursor); + } + + MvcResult result = mockMvc.perform(request) + .andExpect(status().isOk()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.items").isArray()) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + JsonNode items = response.get("items"); + + assertNotNull(items); + assertTrue(items.size() <= pageSize); + + for (JsonNode item : items) { + actualIds.add(item.get("id").asText()); + actualTexts.add(item.get("text").asText()); + } + + pageCount++; + + JsonNode nextCursor = response.get("next_cursor"); + + if (nextCursor.isNull()) { + break; + } + + cursor = nextCursor.asText(); + + assertFalse(cursor.isBlank(), + "next_cursor must not be blank when more pages exist"); + + assertTrue(pageCount <= messageCount, + "Pagination did not terminate"); + } + + assertEquals(expectedPageCount, pageCount); + + assertEquals(messageCount, actualIds.size()); + assertEquals(messageCount, actualTexts.size()); + + assertEquals(actualIds.size(), new HashSet<>(actualIds).size()); + + assertEquals(expectedTexts, actualTexts); + } + + @Test + void shouldIgnoreXUserIdForProtectedEndpoints() throws Exception { + mockMvc.perform(get(USERS_URL + "/me") + .header("X-User-Id", alice.id())) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\"")); + } + + @Test + void shouldRevokeCurrentSession() throws Exception { + mockMvc.perform(delete(SESSIONS_URL + "/current") + .header("Authorization", bearer(alice))) + .andExpect(status().isNoContent()); + + mockMvc.perform(get(USERS_URL + "/me") + .header("Authorization", bearer(alice))) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\"")); + } + + @Test + void shouldRejectWrongPasswordWithBasicChallenge() throws Exception { + String basic = Base64.getEncoder().encodeToString( + (alice.username() + ":definitely-wrong-password") + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + mockMvc.perform(post(SESSIONS_URL) + .header("Authorization", "Basic " + basic)) + .andExpect(status().isUnauthorized()) + .andExpect(header().string( + "WWW-Authenticate", + "Basic realm=\"messenger\", charset=\"UTF-8\"")); + } + + private User registerUser(String username, String displayName) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + Map.of( + "username", username, + "display_name", displayName, + "password", TEST_PASSWORD + ) + ); + + MvcResult result = mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + String basic = Base64.getEncoder().encodeToString( + (username + ":" + TEST_PASSWORD).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + MvcResult loginResult = mockMvc.perform(post(SESSIONS_URL) + .header("Authorization", "Basic " + basic)) + .andExpect(status().isCreated()) + .andReturn(); + JsonNode session = objectMapper.readTree(loginResult.getResponse().getContentAsString()); + + return new User( + response.get("id").asText(), + response.get("username").asText(), + session.get("token").asText() + ); + } + + private String createChat(User owner, User member) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + java.util.Map.of( + "title", "Test chat " + UUID.randomUUID(), + "member_ids", List.of(owner.id(), member.id()) + ) + ); + + MvcResult result = mockMvc.perform(post(CHATS_URL) + .header("Authorization", bearer(owner)) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + return response.get("id").asText(); + } + + private void sendMessage(String chatId, User sender, String text) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + java.util.Map.of("text", text) + ); + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(sender)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")); + } + + private static String bearer(User user) { + return "Bearer " + user.token(); + } + + private record User(String id, String username, String token) { + } +} diff --git a/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java b/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java new file mode 100644 index 0000000..fdc0534 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java @@ -0,0 +1,31 @@ +package com.example.mtusi_messenger.cache; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class UserCacheTest { + + @Test + void shouldEvictJsonNullAndReturnCacheMiss() { + UUID userId = UUID.randomUUID(); + String key = "messenger:user:" + userId; + StringRedisTemplate redis = mock(StringRedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations values = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(values); + when(values.get(key)).thenReturn("null"); + UserCache cache = new UserCache(redis, new ObjectMapper(), 300); + + assertTrue(cache.find(userId).isEmpty()); + verify(redis).delete(key); + } +} diff --git a/src/test/java/com/example/mtusi_messenger/config/PasswordConfigTest.java b/src/test/java/com/example/mtusi_messenger/config/PasswordConfigTest.java new file mode 100644 index 0000000..f1436f5 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/config/PasswordConfigTest.java @@ -0,0 +1,30 @@ +package com.example.mtusi_messenger.config; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PasswordConfigTest { + @Test + void usesArgon2idWithTheDocumentedBaseline() { + var encoder = new PasswordConfig().passwordEncoder(19456, 2, 1); + String encoded = encoder.encode("correct horse battery staple"); + + assertTrue(encoded.startsWith("$argon2id$v=19$m=19456,t=2,p=1$")); + assertTrue(encoder.matches("correct horse battery staple", encoded)); + assertFalse(encoder.matches("wrong password", encoded)); + } + + @Test + void requestsUpgradeForWeakerArgon2idHash() { + var baseline = new PasswordConfig().passwordEncoder(19456, 2, 1); + var weak = new PasswordConfig().passwordEncoder(19456, 2, 1); + // A hash with one iteration is created directly to model a legacy row; + // PasswordConfig itself deliberately refuses such a weak runtime setup. + var legacy = new org.springframework.security.crypto.argon2.Argon2PasswordEncoder( + 16, 32, 1, 19456, 1); + assertTrue(baseline.upgradeEncoding(legacy.encode("legacy password"))); + assertFalse(baseline.upgradeEncoding(weak.encode("current password"))); + } +} diff --git a/src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java b/src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java new file mode 100644 index 0000000..5ca590d --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/queue/RetryPolicyTest.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.queue; + +import org.junit.jupiter.api.Test; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RetryPolicyTest { + @Test + void appliesExponentialBackoffWithBoundedJitter() { + RetryPolicy policy = new RetryPolicy(Duration.ofSeconds(1), Duration.ofSeconds(30)); + + for (int attempt = 2; attempt <= 8; attempt++) { + long ceiling = Math.min(30_000L, 1_000L << (attempt - 2)); + long delay = policy.delayForAttempt(attempt).toMillis(); + assertTrue(delay >= Math.max(1, ceiling / 2)); + assertTrue(delay <= ceiling); + } + } +} diff --git a/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java b/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java new file mode 100644 index 0000000..95114fb --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java @@ -0,0 +1,41 @@ +package com.example.mtusi_messenger.security; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.security.cert.X509Certificate; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class TrustedClientCertificateFilterTest { + private final TrustedClientCertificateFilter filter = + new TrustedClientCertificateFilter("spiffe://hla-lab7/lb"); + + @Test + void rejectsWrongUriEvenWhenTlsAlreadyTrustedTheCertificate() throws Exception { + MockHttpServletResponse response = invoke("spiffe://hla-lab7/worker"); + assertEquals(403, response.getStatus()); + } + + @Test + void acceptsExactLoadBalancerUri() throws Exception { + MockHttpServletResponse response = invoke("spiffe://hla-lab7/lb"); + assertEquals(200, response.getStatus()); + } + + private MockHttpServletResponse invoke(String uri) throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, uri))); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/health/ready"); + request.setAttribute("jakarta.servlet.request.X509Certificate", + new X509Certificate[]{certificate}); + MockHttpServletResponse response = new MockHttpServletResponse(); + filter.doFilter(request, response, new MockFilterChain()); + return response; + } +} diff --git a/src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java b/src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java new file mode 100644 index 0000000..49573d2 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/AttachmentReconcilerTest.java @@ -0,0 +1,75 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AttachmentReconcilerTest { + private static final Instant NOW = Instant.parse("2026-11-11T12:00:00Z"); + + @Test + void deletesOnlyOrphansOlderThanGracePeriodAndReportsMissingObjects() { + AttachmentRepository repository = mock(AttachmentRepository.class); + when(repository.findAllObjectKeys()).thenReturn(Set.of( + "attachments/present/original", "attachments/missing/original")); + FakeStorage storage = new FakeStorage(List.of( + object("attachments/present/original", NOW.minusSeconds(7200)), + object("attachments/old-orphan/original", NOW.minusSeconds(7200)), + object("attachments/fresh-orphan/original", NOW.minusSeconds(30)))); + AttachmentReconciler reconciler = new AttachmentReconciler(repository, storage, + Duration.ofHours(1), false, Clock.fixed(NOW, ZoneOffset.UTC)); + + AttachmentReconciler.Report report = reconciler.reconcile(); + + assertEquals(List.of("attachments/old-orphan/original"), storage.deleted); + assertEquals(1, report.orphanObjects()); + assertEquals(1, report.deletedObjects()); + assertEquals(1, report.missingObjects()); + } + + @Test + void dryRunNeverDeletesOldOrphan() { + AttachmentRepository repository = mock(AttachmentRepository.class); + when(repository.findAllObjectKeys()).thenReturn(Set.of()); + FakeStorage storage = new FakeStorage(List.of( + object("attachments/old-orphan/original", NOW.minusSeconds(7200)))); + AttachmentReconciler reconciler = new AttachmentReconciler(repository, storage, + Duration.ofHours(1), true, Clock.fixed(NOW, ZoneOffset.UTC)); + + AttachmentReconciler.Report report = reconciler.reconcile(); + + assertEquals(List.of(), storage.deleted); + assertEquals(1, report.orphanObjects()); + assertEquals(0, report.deletedObjects()); + } + + private static ObjectStorage.StoredObject object(String key, Instant modified) { + return new ObjectStorage.StoredObject(key, modified, 100); + } + + private static final class FakeStorage implements ObjectStorage { + private final List objects; + private final List deleted = new ArrayList<>(); + + private FakeStorage(List objects) { + this.objects = objects; + } + + @Override public void put(String objectKey, byte[] bytes, String contentType) { } + @Override public byte[] get(String objectKey) { return new byte[0]; } + @Override public void delete(String objectKey) { deleted.add(objectKey); } + @Override public List list(String prefix) { return objects; } + } +} diff --git a/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java new file mode 100644 index 0000000..5df23c6 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/AttachmentServiceTest.java @@ -0,0 +1,201 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiException; +import com.example.mtusi_messenger.model.Attachment; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.queue.AttachmentJobPublisher; +import com.example.mtusi_messenger.storage.ObjectStorage; +import com.example.mtusi_messenger.storage.ObjectStorageException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; + +import java.io.ByteArrayInputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class AttachmentServiceTest { + private final UUID chatId = UUID.randomUUID(); + private final UUID ownerId = UUID.randomUUID(); + private AttachmentRepository repository; + private ChatService chats; + private InMemoryStorage storage; + private AttachmentJobPublisher publisher; + private AttachmentService service; + private byte[] png; + + @BeforeEach + void setUp() throws Exception { + repository = mock(AttachmentRepository.class); + chats = mock(ChatService.class); + storage = new InMemoryStorage(); + publisher = mock(AttachmentJobPublisher.class); + TransactionTemplate transaction = mock(TransactionTemplate.class); + when(transaction.execute(any())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(mock(TransactionStatus.class)); + }); + when(chats.getAccessible(chatId, ownerId)).thenReturn( + new Chat(chatId, "test", List.of(ownerId), Instant.now())); + when(repository.saveQueued(any(), any())).thenAnswer(invocation -> invocation.getArgument(0)); + service = new AttachmentService(repository, chats, storage, publisher, transaction, + 10_485_760, 40_000_000, 3, 10_000, false, 2); + png = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png")); + } + + @Test + void stagesValidPngAndPublishesDurableJob() { + Attachment attachment = service.upload(chatId, ownerId, "photo.png", "image/png", + png.length, new ByteArrayInputStream(png)); + + assertEquals("photo.png", attachment.filename()); + assertEquals("image/png", attachment.contentType()); + assertEquals(png.length, attachment.sizeBytes()); + assertTrue(attachment.objectKey().matches("attachments/[0-9a-f-]+/original")); + assertTrue(attachment.stagingKey().matches("staging/[0-9a-f-]+/original")); + assertEquals("queued", attachment.status()); + assertFalse(attachment.objectKey().contains("photo.png")); + assertArrayEquals(png, storage.objects.get(attachment.stagingKey())); + assertFalse(storage.objects.containsKey(attachment.objectKey())); + verify(repository).saveQueued(eq(attachment), argThat(job -> job.pipelineVersion() == 2)); + verify(publisher).publish(any()); + } + + @Test + void rejectsMimeSpoofingBeforeS3Write() { + ApiException error = assertThrows(ApiException.class, () -> service.upload( + chatId, ownerId, "photo.jpg", "image/jpeg", png.length, + new ByteArrayInputStream(png))); + + assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.status()); + assertTrue(storage.objects.isEmpty()); + } + + @Test + void rejectsOversizedBodyBeforeReadingIt() { + ApiException error = assertThrows(ApiException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", 10_485_761, + new ByteArrayInputStream(png))); + + assertEquals(HttpStatus.PAYLOAD_TOO_LARGE, error.status()); + assertTrue(storage.objects.isEmpty()); + } + + @Test + void rejectsAttachmentFromAnotherChat() { + UUID attachmentId = UUID.randomUUID(); + when(repository.findAllByIdsInChat(chatId, List.of(attachmentId))).thenReturn(List.of()); + + ApiException error = assertThrows(ApiException.class, + () -> service.validateForMessage(chatId, List.of(attachmentId))); + + assertEquals(HttpStatus.NOT_FOUND, error.status()); + } + + @Test + void surfacesS3OutageWithoutWritingMetadata() { + storage.failure = true; + + assertThrows(ObjectStorageException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", png.length, + new ByteArrayInputStream(png))); + verify(repository, never()).saveQueued(any(), any()); + } + + @Test + void interruptedRequestDoesNotCreateS3Object() { + java.io.InputStream source = new java.io.InputStream() { + private int position; + + @Override + public int read() throws IOException { + if (position >= 16_384) { + throw new IOException("client disconnected"); + } + return png[position++]; + } + }; + + ApiException error = assertThrows(ApiException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", -1, source)); + + assertEquals(HttpStatus.BAD_REQUEST, error.status()); + assertTrue(storage.objects.isEmpty()); + verify(repository, never()).saveQueued(any(), any()); + } + + @Test + void databaseFailureCompensatesAlreadyWrittenS3Object() { + when(repository.saveQueued(any(), any())).thenThrow(new IllegalStateException("database commit failed")); + + assertThrows(IllegalStateException.class, () -> service.upload( + chatId, ownerId, "photo.png", "image/png", png.length, + new ByteArrayInputStream(png))); + + assertTrue(storage.objects.isEmpty(), "compensating delete must remove the orphan"); + } + + @Test + void downloadsOnlyAfterChatAuthorization() { + Attachment attachment = new Attachment(UUID.randomUUID(), chatId, ownerId, "photo.png", + "image/png", png.length, "a".repeat(64), "attachments/key/original", + Instant.now(), Instant.now()); + when(repository.findById(attachment.id())).thenReturn(Optional.of(attachment)); + storage.objects.put(attachment.objectKey(), png); + + AttachmentService.Download download = service.download(attachment.id(), ownerId); + + verify(chats).getAccessible(chatId, ownerId); + assertArrayEquals(png, download.bytes()); + } + + private static final class InMemoryStorage implements ObjectStorage { + private final Map objects = new HashMap<>(); + private boolean failure; + + @Override + public void put(String objectKey, byte[] bytes, String contentType) { + if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest()); + objects.put(objectKey, bytes.clone()); + } + + @Override + public byte[] get(String objectKey) { + if (failure) throw new ObjectStorageException("S3 unavailable", new IOExceptionForTest()); + return objects.get(objectKey).clone(); + } + + @Override + public void delete(String objectKey) { + objects.remove(objectKey); + } + + @Override + public List list(String prefix) { + return objects.entrySet().stream() + .filter(entry -> entry.getKey().startsWith(prefix)) + .map(entry -> new StoredObject(entry.getKey(), Instant.now(), entry.getValue().length)) + .toList(); + } + } + + private static final class IOExceptionForTest extends RuntimeException { + } + +} diff --git a/src/test/java/com/example/mtusi_messenger/service/AuthenticationServiceTest.java b/src/test/java/com/example/mtusi_messenger/service/AuthenticationServiceTest.java new file mode 100644 index 0000000..70b56fa --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/AuthenticationServiceTest.java @@ -0,0 +1,39 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.cache.UserCache; +import com.example.mtusi_messenger.model.Session; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.SessionRepository; +import com.example.mtusi_messenger.repository.UserRepository; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AuthenticationServiceTest { + @Test + void serializesIssuanceAndRevokesSessionsBeyondConfiguredMaximum() { + UserRepository users = mock(UserRepository.class); + SessionRepository sessions = mock(SessionRepository.class); + UserCache cache = mock(UserCache.class); + User user = new User(UUID.randomUUID(), "alice", "Alice", Instant.now()); + when(sessions.save(any(Session.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + AuthenticationService service = new AuthenticationService(users, sessions, cache, 3600, 3); + AuthenticationService.IssuedSession issued = service.issueSession(user); + + var order = inOrder(sessions); + order.verify(sessions).lockUserSessions(user.id()); + order.verify(sessions).save(any(Session.class)); + order.verify(sessions).revokeExcessActive(user.id(), 3); + assertEquals(43, issued.token().length()); + assertTrue(issued.expiresAt().isAfter(Instant.now().plusSeconds(3500))); + } +} diff --git a/src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java b/src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java new file mode 100644 index 0000000..03c90ef --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/service/StagingCleanerTest.java @@ -0,0 +1,55 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.repository.AttachmentRepository; +import com.example.mtusi_messenger.storage.ObjectStorage; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class StagingCleanerTest { + private static final Instant NOW = Instant.parse("2026-11-18T12:00:00Z"); + + @Test + void keepsActiveAndFreshStagingButDeletesExpiredUnreferencedObject() { + AttachmentRepository repository = mock(AttachmentRepository.class); + when(repository.findActiveStagingKeys()).thenReturn(Set.of("staging/active/original")); + FakeStorage storage = new FakeStorage(List.of( + object("staging/active/original", NOW.minusSeconds(172800)), + object("staging/failed/original", NOW.minusSeconds(172800)), + object("staging/fresh/original", NOW.minusSeconds(60)))); + StagingCleaner cleaner = new StagingCleaner(repository, storage, Duration.ofDays(1), + Clock.fixed(NOW, ZoneOffset.UTC)); + + cleaner.cleanup(); + + assertEquals(List.of("staging/failed/original"), storage.deleted); + } + + private static ObjectStorage.StoredObject object(String key, Instant modified) { + return new ObjectStorage.StoredObject(key, modified, 100); + } + + private static final class FakeStorage implements ObjectStorage { + private final List objects; + private final List deleted = new ArrayList<>(); + + private FakeStorage(List objects) { + this.objects = objects; + } + + @Override public void put(String objectKey, byte[] bytes, String contentType) { } + @Override public byte[] get(String objectKey) { return new byte[0]; } + @Override public void delete(String objectKey) { deleted.add(objectKey); } + @Override public List list(String prefix) { return objects; } + } +} diff --git a/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java b/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java new file mode 100644 index 0000000..a8374d1 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/web/ReadinessGuardFilterTest.java @@ -0,0 +1,62 @@ +package com.example.mtusi_messenger.web; + +import com.example.mtusi_messenger.service.ReadinessService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ReadinessGuardFilterTest { + private final ReadinessService readiness = mock(ReadinessService.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final ReadinessGuardFilter filter = new ReadinessGuardFilter(readiness, mapper); + + @Test + void refusingReplicaRejectsBusinessTrafficBeforeItReachesTheChain() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(false); + var request = new MockHttpServletRequest("GET", "/api/v1/users/me"); + request.setAttribute(RequestIdFilter.ATTRIBUTE, "request-1"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertEquals(503, response.getStatus()); + assertNull(chain.getRequest()); + JsonNode body = mapper.readTree(response.getContentAsByteArray()); + assertEquals("unavailable", body.at("/error/code").asText()); + assertEquals("request-1", body.at("/error/request_id").asText()); + } + + @Test + void readyReplicaPassesBusinessTrafficToTheChain() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(true); + var request = new MockHttpServletRequest("GET", "/api/v1/users/me"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertSame(request, chain.getRequest()); + } + + @Test + void healthProbeIsNeverBlockedByTheBusinessGuard() throws Exception { + when(readiness.acceptsBusinessTraffic()).thenReturn(false); + var request = new MockHttpServletRequest("GET", "/health/ready"); + var response = new MockHttpServletResponse(); + var chain = new MockFilterChain(); + + filter.doFilter(request, response, chain); + + assertSame(request, chain.getRequest()); + } +} diff --git a/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java new file mode 100644 index 0000000..9601467 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/worker/ImageVariantProcessorTest.java @@ -0,0 +1,94 @@ +package com.example.mtusi_messenger.worker; + +import org.junit.jupiter.api.Test; + +import javax.imageio.ImageIO; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Map; +import java.util.Arrays; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ImageVariantProcessorTest { + private final byte[] original; + + ImageVariantProcessorTest() throws Exception { + original = Files.readAllBytes(Path.of("tests", "fixtures", "sample.png")); + } + + @Test + void createsThumbnailCropAndOptimizedWebp() throws Exception { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1)); + + Map variants = processor + .createVariants(original, 2).stream() + .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, + Function.identity())); + + assertEquals(3, variants.size()); + assertImage(variants.get("thumbnail"), "image/jpeg", 256, 160); + assertImage(variants.get("crop"), "image/jpeg", 128, 128); + assertImage(variants.get("optimized"), "image/webp", 320, 200); + byte[] webp = variants.get("optimized").bytes(); + assertEquals("RIFF", new String(webp, 0, 4, StandardCharsets.US_ASCII)); + assertEquals("WEBP", new String(webp, 8, 4, StandardCharsets.US_ASCII)); + } + + @Test + void rejectsImageWhoseEstimateExceedsWorkerMemoryBudget() { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 1L * 1024 * 1024, Duration.ofSeconds(1)); + + var error = assertThrows(ImageVariantProcessor.ProcessingException.class, + () -> processor.createVariants(original, 2)); + + assertTrue(error.permanent()); + assertEquals("image_too_large", error.errorCode()); + } + + @Test + void versionsProduceSeparateDeterministicProfiles() { + ImageVariantProcessor processor = new ImageVariantProcessor( + 40_000_000, 512L * 1024 * 1024, Duration.ofSeconds(1)); + + Map version1 = processor + .createVariants(original, 1).stream() + .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, + Function.identity())); + Map version2 = processor + .createVariants(original, 2).stream() + .collect(Collectors.toMap(ImageVariantProcessor.GeneratedVariant::name, + Function.identity())); + + assertFalse(Arrays.equals(version1.get("optimized").bytes(), + version2.get("optimized").bytes())); + assertTrue(Arrays.equals(version2.get("optimized").bytes(), + processor.createVariants(original, 2).stream() + .filter(item -> item.name().equals("optimized")) + .findFirst().orElseThrow().bytes())); + } + + private static void assertImage( + ImageVariantProcessor.GeneratedVariant variant, + String contentType, int width, int height) throws Exception { + assertNotNull(variant); + assertEquals(contentType, variant.contentType()); + assertEquals(width, variant.width()); + assertEquals(height, variant.height()); + var decoded = ImageIO.read(new ByteArrayInputStream(variant.bytes())); + assertNotNull(decoded); + assertEquals(width, decoded.getWidth()); + assertEquals(height, decoded.getHeight()); + } +} diff --git a/tests/README.md b/tests/README.md index 0dfa3f8..c061bba 100644 --- a/tests/README.md +++ b/tests/README.md @@ -50,7 +50,7 @@ make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt ``` -Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. +Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. `test-security` сначала проверяет доверенное соединение и отказ пустого trust store, затем выполняет негативные проверки user/chat/attachment ACL, запрет cross-chat attachment, 10 MiB upload limit, максимум трёх активных сессий и общий Redis-backed login limit с `429 Retry-After`. Network timeout не засчитывается как правильный TLS-отказ. **Внутреннее mTLS и OpenBao policy проверяют отдельные тесты** по trust matrix. Клиентский сертификат внешнему REST-клиенту не требуется: mTLS находится на внутренних связях. ## Что ещё остаётся доказать diff --git a/tests/security.py b/tests/security.py index 233e896..aea1b74 100644 --- a/tests/security.py +++ b/tests/security.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -"""Public lab7 external TLS check. Internal mTLS/policies require student tests.""" +"""Lab7 external TLS, login/session limits and user/attachment ACL checks.""" +import base64 import ssl import urllib.error import urllib.request -from client import Client, LAB, NoRedirect, arguments, check, run +from client import Client, LAB, NoRedirect, ROOT, arguments, check, run def main(): @@ -24,7 +25,58 @@ def main(): check(isinstance(exc.reason,ssl.SSLCertVerificationError),'negative probe failed for a non-certificate reason') rejected = True check(rejected,'server unexpectedly passed validation with an empty trust store') - print('PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.') + + alice,bob,eve,chat = c.bootstrap() + chat_path = '/api/v1/chats/'+chat['id'] + + # Bearer identity wins over attacker-controlled compatibility headers. + forged = c.call('GET','/api/v1/users/me',actor=eve, + headers={'X-User-Id':alice['id']},schema='User')['json'] + check(forged['id']==eve['id'],'X-User-Id overrode Bearer identity') + c.call('GET',chat_path,404,actor=eve) + c.call('GET',chat_path+'/messages',404,actor=eve) + c.call('POST',chat_path+'/messages',404,actor=eve, + headers={'Idempotency-Key':'acl-outsider-message'},body={'text':'forbidden'}) + + attachment,_ = c.attachment(alice,chat) + for suffix in ('','/content'): + c.call('GET','/api/v1/attachments/'+attachment['id']+suffix,404,actor=eve) + sample = (ROOT / 'tests/fixtures/sample.png').read_bytes() + c.call('POST',chat_path+'/attachments?filename=forbidden.png',404,actor=eve, + raw=sample,headers={'Content-Type':'image/png'}) + + second_chat = c.call('POST','/api/v1/chats',201,actor=alice, + body={'title':'Изолированный чат','member_ids':[alice['id'],bob['id']]}, + schema='Chat')['json'] + c.call('POST','/api/v1/chats/'+second_chat['id']+'/messages',404,actor=alice, + headers={'Idempotency-Key':'cross-chat-attachment'}, + body={'text':'','attachment_ids':[attachment['id']]}) + + # The declared request size is rejected before image decoding/storage. + c.call('POST',chat_path+'/attachments?filename=oversized.png',413,actor=alice, + raw=b'x'*(10*1024*1024+1),headers={'Content-Type':'image/png'}) + + # At most three active sessions are retained. Five logins fit under the + # default per-username login window and must revoke the oldest token. + credential = base64.b64encode((alice['registration']['username']+':' + +alice['registration']['password']).encode()).decode() + for _ in range(4): + c.call('POST','/api/v1/auth/sessions',201, + headers={'Authorization':'Basic '+credential},schema='Session') + c.call('GET','/api/v1/users/me',401,actor=alice) + + limited = c.user('rate_limit') + bad = base64.b64encode((limited['registration']['username']+':wrong-password').encode()).decode() + for _ in range(4): + c.call('POST','/api/v1/auth/sessions',401, + headers={'Authorization':'Basic '+bad}) + blocked = c.call('POST','/api/v1/auth/sessions',429, + headers={'Authorization':'Basic '+bad}) + check(blocked['json']['error']['code']=='rate_limited','wrong rate-limit error code') + retry_after = blocked['headers'].get('Retry-After','') + check(retry_after.isdigit() and int(retry_after)>=1,'missing positive Retry-After') + + print('PASS: trusted HTTPS, ACL/attachment isolation, session cap, upload and login limits.') if __name__=='__main__': run(main)