1 Commits
Author SHA1 Message Date
Vladislav Kunetskiy 3d216fbd50 База lab7: контракт 1.7.0 и реализация lab1–lab6
Перенесены cmd/internal/config, compose.yaml, Dockerfile, скрипты, student-tests и evidence из mtusi-messenger (master, lab6). Skeleton lab7 (openapi/infrastructure 1.7.0, trust-matrix.md, security/THREAT_MODEL.md, infra/openbao, tests/security.py) сохранён; make test-security добавлен в Makefile.
2026-11-09 13:03:49 +03:00
185 changed files with 3159 additions and 216868 deletions
+134 -43
View File
@@ -1,66 +1,145 @@
# Local synthetic stand. Copy to .env; this file contains NO credential values. # Copy to .env for your LOCAL synthetic test environment; never commit .env.
# make prepare generates role keys/backend secrets; operator root/unseal state # Values below are the variables this implementation actually reads
# stays outside the checkout under ~/.local/share/mtusi-lab7/<project> (0700). # (viper: section.name -> SECTION_NAME, see internal/config/config.go).
COMPOSE_PROJECT_NAME=mtusi-messenger-lab6 #
LAB7_SECRETS_DIR=secrets/lab7 # Mapping to the logical names suggested by the skeleton:
BASE_URL=https://localhost:8443 # APP_HOST / APP_PORT -> SERVER_HOST / SERVER_PORT
CA_FILE=secrets/lab7/pki/operator/current/ca.crt # SESSION_STORE=postgres -> server-side sessions live in PostgreSQL (SESSION_TTL_SECONDS)
PUBLIC_PORT=8443 # DATABASE_URL_FILE -> unused: POSTGRES_* below pass no secret files
S3_PORT=8333 # CACHE_URL_FILE -> unused: REDIS_* below pass no secret files
BAO_PORT=8200 # API_REPLICAS -> number of API replicas of the stand (compose.yaml)
GRAFANA_PORT=3000 #
PROMETHEUS_PORT=9090 # APP_ENV selects config/<env>/config.yaml; the implementation supports only `dev`.
LOKI_PORT=3100
TEMPO_PORT=3200
BROKER_MANAGEMENT_PORT=15671
LB_STATS_PORT=8404
# Operator-local integration ports (only docker-compose.local.yaml publishes them).
TEST_POSTGRES_PORT=15432
TEST_REDIS_PORT=16379
# Service identities/CA/CRL are per-role mounts, set explicitly in compose.yaml:
# TLS_CA_FILE=/run/identity/current/ca.crt
# TLS_CERT_FILE=/run/identity/current/tls.crt
# TLS_KEY_FILE=/run/identity/current/tls.key
# TLS_CRL_FILE=/run/identity/current/ca.crl
# TLS_VERSION_FILE=/run/identity/current-version (atomic immutable-version selector)
# BAO_ADDR=https://openbao:8200; BAO_ROLE=api/worker/relay;
# BAO_KV_PATH=secret/data/<role>; credentials fetched by cert-auth at startup.
# Password PHC parameters: Argon2id v19 m=19456 KiB,t=2,p=1 (measured in REPORT).
# Shared login allowance: account8/minute, sourceIP120/minute, global16/second.
# Hashing concurrency: at most2 derivations per API replica; no unbounded queue.
APP_ENV=dev APP_ENV=dev
SERVER_HOST=0.0.0.0
SERVER_PORT=8080
SERVER_READ_HEADER_TIMEOUT=10s
SERVER_READ_TIMEOUT=60s
SERVER_SHUTDOWN_TIMEOUT=10s
# Предел размера тела запроса (байт): защищает реплику от чтения огромного тела
# до валидации. Для вложений LAB4 (до 10 MiB) значение нужно поднять.
SERVER_MAX_BODY_BYTES=262144 SERVER_MAX_BODY_BYTES=262144
LOG_LEVEL=info
LOG_FORMAT=json
# Synthetic credentials for the local stand only; override in .env for anything else.
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DATABASE=messenger
POSTGRES_USER=messenger
POSTGRES_PASSWORD=messenger
POSTGRES_SSL_MODE=disable
POSTGRES_MAX_CONNS=10
POSTGRES_MIN_CONNS=1
POSTGRES_MAX_CONN_LIFETIME=1h
POSTGRES_MAX_CONN_IDLE_TIME=30m
POSTGRES_CONNECT_TIMEOUT=5s
POSTGRES_QUERY_TIMEOUT=5s
REDIS_ENABLED=true
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
# -1 disables go-redis retries; 0 keeps the library default (3 retries).
REDIS_MAX_RETRIES=-1
REDIS_DIAL_TIMEOUT=300ms
REDIS_READ_TIMEOUT=200ms
REDIS_WRITE_TIMEOUT=200ms
REDIS_POOL_SIZE=10
CACHE_ENABLED=true
CACHE_CHAT_LIST_TTL=5m
CACHE_LOCK_TTL=10s
CACHE_LOCK_WAIT_TIMEOUT=2s
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Retention of a message Idempotency-Key in the shared store; contract 1.3.0
# requires at least 24 h.
IDEMPOTENCY_TTL_SECONDS=86400 IDEMPOTENCY_TTL_SECONDS=86400
# Lab3 stand (compose.yaml): number of API replicas behind the LB and per-replica
# CPU/RAM limits. Track 1 varies them to compare 1/2/4 replicas at a fixed total
# budget, e.g. API_REPLICAS=4 API_CPU_LIMIT=0.25 API_MEM_LIMIT=192M.
API_REPLICAS=2 API_REPLICAS=2
API_CPU_LIMIT=0.50 API_CPU_LIMIT=0.50
API_MEM_LIMIT=256M API_MEM_LIMIT=256M
POSTGRES_CPU_LIMIT=0.50
POSTGRES_MEM_LIMIT=320M # Connections of ONE API replica to PostgreSQL; the total is replicas × value.
# Track 1 checks whether the shared connection budget becomes the saturation
# point: at 4 replicas the default 10 means 40 connections against one database.
POSTGRES_MAX_CONNS=10 POSTGRES_MAX_CONNS=10
# CPU quota of the shared database. Track 1 shows it is the stand's saturation
# point: the API uses a fraction of its budget while PostgreSQL sits at its own.
POSTGRES_CPU_LIMIT=0.50
# Memory quota of the shared database. The track 1 series r/g/pool were measured
# with 512M, the db1cpu control — with 384M (see evidence/track1/profile-*.json).
POSTGRES_MEM_LIMIT=192M
# Loopback port of the HAProxy operator page (UP/DOWN of every replica).
LB_STATS_PORT=8404
# --- Lab4: private S3 object store (SeaweedFS) -------------------------------
# Synthetic local application credentials. infra/s3/s3.json must contain the
# same app values; scripts/check_s3_creds.py enforces that before the stand starts.
# Admin credentials live only in infra/s3/s3.json and s3-init defaults; never put
# them in .env, because the API service loads this file.
S3_ENDPOINT=http://localhost:8333
S3_PUBLIC_ENDPOINT=http://127.0.0.1:8333
S3_PORT=8333
S3_REGION=us-east-1
S3_BUCKET=messenger-attachments S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID=lab4app
S3_SECRET_ACCESS_KEY=lab4app-secret
# Attachment limits from contract 1.5.0.
MAX_UPLOAD_BYTES=10485760 MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000 MAX_IMAGE_PIXELS=40000000
# Presigned upload lifetime and the sweeper's safety window.
S3_PRESIGN_TTL=5m S3_PRESIGN_TTL=5m
S3_SWEEP_INTERVAL=1m S3_SWEEP_INTERVAL=1m
S3_SWEEP_GRACE=10m S3_SWEEP_GRACE=10m
# --- Lab5: durable queues and async image processing -------------------------
# Synthetic broker credentials for the local Compose stand. The relay/worker
# connect inside the compose network; the management UI is published only on
# loopback by compose.yaml.
BROKER_USER=messenger
BROKER_PASSWORD=messenger
BROKER_VHOST=messenger
BROKER_URL=amqp://messenger:messenger@broker:5672/messenger
BROKER_EXCHANGE=attachments.jobs
BROKER_QUEUE=attachment.process.v1
BROKER_DLX=attachments.dlx
BROKER_DLQ=attachment.process.dead
BROKER_MANAGEMENT_PORT=15672
BROKER_CPU_LIMIT=0.50
BROKER_MEM_LIMIT=384M
# Worker process bounds. Concurrency=1 is the safe default for a 40 MP image on
# the course VM; raise it together with WORKER_MEM_LIMIT.
WORKER_CONCURRENCY=1 WORKER_CONCURRENCY=1
WORKER_PREFETCH=1 WORKER_PREFETCH=1
WORKER_CPU_LIMIT=1.00 WORKER_CPU_LIMIT=1.00
WORKER_MEM_LIMIT=1G WORKER_MEM_LIMIT=1G
BROKER_CPU_LIMIT=0.50 WORKER_SHUTDOWN_TIMEOUT=30s
BROKER_MEM_LIMIT=384M WORKER_HEALTH_PORT=8081
# Shared job contract. The API chooses the pipeline version for new uploads.
PROCESSING_PIPELINE_VERSION=1 PROCESSING_PIPELINE_VERSION=1
PROCESSING_MAX_ATTEMPTS=5 PROCESSING_MAX_ATTEMPTS=5
PROCESSING_JOB_TIMEOUT=60s PROCESSING_JOB_TIMEOUT=120s
PROCESSING_LEASE_TTL=90s PROCESSING_LEASE_TTL=180s
PROCESSING_HEARTBEAT=15s PROCESSING_HEARTBEAT=30s
PROCESSING_RETRY_BASE=2s PROCESSING_RETRY_BASE=2s
PROCESSING_RETRY_CAP=60s PROCESSING_RETRY_CAP=60s
# Outbox relay and lease reaper.
OUTBOX_POLL_INTERVAL=1s OUTBOX_POLL_INTERVAL=1s
OUTBOX_CLAIM_TTL=30s OUTBOX_CLAIM_TTL=30s
OUTBOX_BATCH=20 OUTBOX_BATCH=20
@@ -69,6 +148,9 @@ OUTBOX_RECONCILE_AFTER=5m
OUTBOX_RETENTION=168h OUTBOX_RETENTION=168h
RELAY_CPU_LIMIT=0.25 RELAY_CPU_LIMIT=0.25
RELAY_MEM_LIMIT=128M RELAY_MEM_LIMIT=128M
RELAY_HEALTH_PORT=8082
# Staging cleanup and admission control.
STAGING_ORPHAN_GRACE=1h STAGING_ORPHAN_GRACE=1h
STAGING_FAILED_RETENTION=168h STAGING_FAILED_RETENTION=168h
ADMISSION_MAX_PENDING_PER_USER=20 ADMISSION_MAX_PENDING_PER_USER=20
@@ -76,10 +158,19 @@ ADMISSION_MAX_PENDING=200
ADMISSION_MAX_STAGED_BYTES=2147483648 ADMISSION_MAX_STAGED_BYTES=2147483648
ADMISSION_MAX_CONCURRENT_UPLOADS=8 ADMISSION_MAX_CONCURRENT_UPLOADS=8
# Telemetry is part of the full stand, not a plaintext optional profile. # --- Lab6: observability -----------------------------------------------------
# SDK/Collector settings; OTLP traffic must never carry message bodies,
# attachment bytes, credentials or user/chat/message ids as metric labels.
# Service names are set per service in compose.yaml (API/worker/relay must differ).
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
OTEL_METRIC_EXPORT_INTERVAL=15000
TELEMETRY_ENABLED=1 TELEMETRY_ENABLED=1
OTEL_TRACES_SAMPLER=always_on PROMETHEUS_PORT=9090
OTEL_METRIC_EXPORT_INTERVAL=5000 LOKI_PORT=3100
TEMPO_PORT=3200
GRAFANA_PORT=3000
OTEL_COLLECTOR_CPU_LIMIT=0.25 OTEL_COLLECTOR_CPU_LIMIT=0.25
OTEL_COLLECTOR_MEM_LIMIT=192M OTEL_COLLECTOR_MEM_LIMIT=192M
PROMETHEUS_CPU_LIMIT=0.50 PROMETHEUS_CPU_LIMIT=0.50
+104 -39
View File
@@ -1,15 +1,17 @@
name: Application name: Application
on: [push, pull_request] on: [push, pull_request]
permissions: permissions:
contents: read contents: read
env: env:
GO_VERSION: "1.27.3" GO_VERSION: "1.27.0"
GOLANGCI_LINT_VERSION: v2.15.0 GOLANGCI_LINT_VERSION: v2.13.2
jobs: jobs:
quality: lint:
name: Go invariants and static checks name: Lint
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -17,44 +19,107 @@ jobs:
with: with:
go-version: ${{ env.GO_VERSION }} go-version: ${{ env.GO_VERSION }}
cache: true cache: true
- run: make sqlc generate-mocks - run: make lint
- run: make lint unit-test
unit-test:
name: Unit tests
needs: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- run: make unit-test
build:
name: Docker build
needs: unit-test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
with:
context: .
push: false
tags: mtusi-messenger:ci
stand: stand:
name: Lab7 verified TLS and retained features name: Lab6 stand scenario (lab5 base)
needs: quality needs: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 30 timeout-minutes: 20
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-go@v5 - run: cp .env.example .env && sed -i 's/^TELEMETRY_ENABLED=.*/TELEMETRY_ENABLED=0/' .env
with: - run: ./scripts/init-secrets.sh
go-version: ${{ env.GO_VERSION }} - run: docker compose --env-file .env config --quiet
cache: true - run: docker compose --env-file .env up -d --build
- uses: actions/setup-python@v5 - name: Wait for readiness through the load balancer
with:
python-version: "3.14"
- run: cp .env.example .env
- name: Build, initialize, unseal and start isolated stand
run: make COMPOSE_PROJECT_NAME=mtusi-lab7-ci up
- name: Public HTTPS and trust
run: make COMPOSE_PROJECT_NAME=mtusi-lab7-ci test test-security
- name: Internal identities and permissions
run: make COMPOSE_PROJECT_NAME=mtusi-lab7-ci test-lab7
- name: Preserved asynchronous attachment features
run: make COMPOSE_PROJECT_NAME=mtusi-lab7-ci test-attachments test-presign test-queue test-idempotency
- name: Telemetry configuration and all three signals
run: | run: |
docker compose --project-name mtusi-lab7-ci --env-file .env exec -T prometheus promtool check config /etc/prometheus/prometheus.yml for attempt in $(seq 1 60); do
make COMPOSE_PROJECT_NAME=mtusi-lab7-ci test-observability if curl -fsS -o /dev/null http://localhost:8080/health/ready; then exit 0; fi
- name: Persist data through operator restart sleep 2
run: make COMPOSE_PROJECT_NAME=mtusi-lab7-ci test-persistence ACTION_SCRIPT=scripts/restart.sh done
- name: Publish sanitized evidence docker compose --env-file .env ps
if: always() exit 1
uses: actions/upload-artifact@v4 - name: Public smoke through the LB
with: run: make test
name: lab7-evidence - name: Attachment negative scenarios
path: evidence/lab7/ run: make test-attachments
- name: Isolated runner cleanup - name: Presigned direct upload (async complete)
if: always() run: make test-presign
run: docker compose --project-name mtusi-lab7-ci --env-file .env down -v - name: Worker process is separate and healthy
run: docker compose --env-file .env ps worker relay broker
- name: Async worker and broker durability
run: make test-queue
- name: Track 2 duplicate and stale-version harness
run: python3 scripts/lab5_track2.py --reps 1
- name: Parallel idempotency through the LB
run: python3 student-tests/idempotency_parallel.py --base-url http://localhost:8080
- name: LB removes a not-ready replica
run: make test-lb-readiness
- name: Upload, stop the serving replica, download through another
run: python3 student-tests/attachment_failover.py --base-url http://localhost:8080
- name: Stop one API replica and keep writing
run: make test-failover ACTION_SCRIPT=scripts/stop-one.sh
- name: Logs on failure
if: failure()
run: docker compose --env-file .env logs --tail 100 api worker relay
- if: always()
run: docker compose --env-file .env down -v
observability:
name: Lab6 observability stand
needs: build
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v4
- run: cp .env.example .env
- run: ./scripts/init-secrets.sh
- run: docker compose --env-file .env --profile telemetry config --quiet
- run: docker compose --env-file .env --profile telemetry up -d --build
- name: Validate Prometheus configuration and rules
run: |
docker compose --env-file .env --profile telemetry exec -T prometheus promtool check config /etc/prometheus/prometheus.yml
docker compose --env-file .env --profile telemetry exec -T prometheus sh -c 'promtool check rules /etc/prometheus/rules/*.yml'
- name: Wait for readiness through the LB
run: |
for attempt in $(seq 1 60); do
if curl -fsS -o /dev/null http://localhost:8080/health/ready; then exit 0; fi
sleep 2
done
docker compose --env-file .env ps
exit 1
- name: Public smoke with telemetry enabled
run: make test
- name: Observability and privacy checks
run: make test-observability
- name: Logs on failure
if: failure()
run: docker compose --env-file .env --profile telemetry logs --tail 120 api worker relay otel-collector prometheus loki tempo grafana
- if: always()
run: docker compose --env-file .env --profile telemetry down -v
+4 -6
View File
@@ -1,11 +1,9 @@
# syntax=docker/dockerfile:1.7 # syntax=docker/dockerfile:1.7
ARG GO_VERSION=1.27.3 ARG GO_VERSION=1.27.1
ARG ALPINE_VERSION=3.22 ARG ALPINE_VERSION=3.22
ARG GO_IMAGE_DIGEST=sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18
ARG ALPINE_IMAGE_DIGEST=sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f
FROM golang:${GO_VERSION}-alpine@${GO_IMAGE_DIGEST} AS build FROM golang:${GO_VERSION}-alpine AS build
# Platform of the produced binaries. Left empty on purpose: the classic builder # Platform of the produced binaries. Left empty on purpose: the classic builder
# does not supply these args, and the previous hardcoded `amd64` default silently # does not supply these args, and the previous hardcoded `amd64` default silently
# produced x86-64 binaries inside an arm64 image. Those ran under emulation and # produced x86-64 binaries inside an arm64 image. Those ran under emulation and
@@ -57,7 +55,7 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
-ldflags="-s -w -X main.version=${VERSION}" \ -ldflags="-s -w -X main.version=${VERSION}" \
-o /out/jobctl ./cmd/jobctl -o /out/jobctl ./cmd/jobctl
FROM alpine:${ALPINE_VERSION}@${ALPINE_IMAGE_DIGEST} AS runtime FROM alpine:${ALPINE_VERSION} AS runtime
RUN apk add --no-cache ca-certificates wget \ RUN apk add --no-cache ca-certificates wget \
&& addgroup -S -g 10001 app \ && addgroup -S -g 10001 app \
&& adduser -S -D -H -u 10001 -G app app && adduser -S -D -H -u 10001 -G app app
@@ -74,6 +72,6 @@ USER 10001:10001
EXPOSE 8080 EXPOSE 8080
STOPSIGNAL SIGTERM STOPSIGNAL SIGTERM
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD wget -q -O /dev/null http://127.0.0.1:8084/health/live || exit 1 CMD wget -q -O /dev/null "http://127.0.0.1:${SERVER_PORT:-8080}/health/live" || exit 1
ENTRYPOINT ["/usr/local/bin/messenger"] ENTRYPOINT ["/usr/local/bin/messenger"]
+119 -110
View File
@@ -1,100 +1,32 @@
PYTHON ?= python3 PYTHON ?= python3
GO ?= go
VERSION ?= $(shell git describe --always --dirty 2>/dev/null || echo dev) VERSION ?= $(shell git describe --always --dirty 2>/dev/null || echo dev)
BASE_URL ?= https://localhost:8443 export VERSION
LAB7_SECRETS_DIR ?= secrets/lab7 # Lab1–lab6 base still serves plain HTTP on 8080; the lab7 implementation moves
CA_FILE ?= $(LAB7_SECRETS_DIR)/pki/operator/current/ca.crt # the stand to the contract default https://localhost:8443.
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
PIPELINE ?= 2 PIPELINE ?= 2
ROLE ?= api TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
CERT_TTL ?= 1h
TLS_ARGS = --ca-file "$(CA_FILE)"
COMPOSE_BIN ?= docker compose
COMPOSE_FILE ?= compose.yaml
ENV_FILE ?= .env
COMPOSE = $(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE)
PYTHON_LOCAL = env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 $(PYTHON) PYTHON_LOCAL = env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 $(PYTHON)
LOCAL_BIN := $(CURDIR)/bin
GOLANGCI_LINT_VERSION ?= v2.15.0
GOLANGCI_LINT := $(LOCAL_BIN)/golangci-lint
OPENAPI_SPEC := contracts/openapi.json
OGEN_CONFIG := .ogen.yml
OAS_DIR := internal/transport/rest/internal/oas
-include .env .PHONY: help check validate test test-attachments test-presign load test-persistence test-failover test-security smoke-local load-local test-idempotency test-lb-readiness test-observability test-slo up up-base init-secrets down ps logs
export
ENV_KEYS := $(shell sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' .env 2>/dev/null)
CLEAN_ENV = env $(addprefix -u ,$(ENV_KEYS))
.DEFAULT_GOAL := help
.PHONY: help check validate prepare build bootstrap up down ps logs test test-security test-lab7 test-pki auth-budget pki-issue pki-renew renew-watch bao-unseal test-attachments test-presign test-queue test-faults test-track2 test-observability test-slo test-idempotency test-lb-readiness load test-persistence test-failover jobs-failed replay reprocess unit-test integration-test test-db-up test-db-down dev-up dev-down dev-reload migrate generate generate-api generate-mocks sqlc cover lint
help: help:
@echo "prepare/build/up: local PKI, image, operator Bao init/unseal and full verified-TLS stand" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "test/test-security/test-lab7: public HTTPS, external trust, complete internal security probes" @echo "up: lab6 stand with telemetry profile; up-base: lab5 regression without telemetry"
@echo "test-pki: 3 isolated lifecycle experiments; auth-budget: measured Argon2/login budget" @echo "down/ps/logs: same profile; test-observability/test-slo: lab6 checks"
@echo "pki-issue/pki-renew/renew-watch ROLE=api CERT_TTL=1h; bao-unseal: operator recovery"
check: check:
$(PYTHON) scripts/check_contract.py $(PYTHON) scripts/check_contract.py
$(PYTHON) scripts/check_s3_creds.py
validate: validate:
$(PYTHON) scripts/validate_openapi.py $(PYTHON) scripts/validate_openapi.py
prepare:
$(PYTHON_LOCAL) scripts/securityctl.py prepare
build: prepare
$(COMPOSE) build api
bootstrap:
$(PYTHON_LOCAL) scripts/securityctl.py bootstrap
up: build
$(PYTHON_LOCAL) scripts/securityctl.py up
down:
$(COMPOSE) down
ps:
$(COMPOSE) ps
logs:
$(COMPOSE) logs -f --tail 100
bao-unseal:
$(PYTHON_LOCAL) scripts/securityctl.py unseal
pki-issue:
$(PYTHON_LOCAL) scripts/securityctl.py issue "$(ROLE)" --ttl "$(CERT_TTL)"
pki-renew:
$(PYTHON_LOCAL) scripts/securityctl.py renew "$(ROLE)" --ttl "$(CERT_TTL)"
renew-watch:
$(PYTHON_LOCAL) scripts/securityctl.py renew "$(ROLE)" --ttl "$(CERT_TTL)" --watch --interval 1
renewer:
$(PYTHON_LOCAL) scripts/lab7_renewer.py --interval 1800 --ttl "$(CERT_TTL)"
renew-once:
$(PYTHON_LOCAL) scripts/lab7_renewer.py --once --ttl "$(CERT_TTL)" --output evidence/lab7/renewer.json
test: test:
$(PYTHON_LOCAL) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security:
$(PYTHON_LOCAL) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-lab7:
$(PYTHON_LOCAL) student-tests/lab7_security.py --base-url "$(BASE_URL)" $(TLS_ARGS) --output evidence/lab7/security.json
test-pki:
$(PYTHON_LOCAL) scripts/lab7_track2.py --reps 3 --duration 30 --output evidence/lab7/track2.json
auth-budget:
$(PYTHON_LOCAL) scripts/lab7_auth_benchmark.py --api $(TLS_ARGS) --output evidence/lab7/auth.json
test-attachments: test-attachments:
$(PYTHON_LOCAL) student-tests/attachments_negative.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) student-tests/attachments_negative.py --base-url "$(BASE_URL)" $(TLS_ARGS)
@@ -110,6 +42,7 @@ test-faults:
test-track2: test-track2:
$(PYTHON_LOCAL) scripts/lab5_track2.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) scripts/lab5_track2.py --base-url "$(BASE_URL)" $(TLS_ARGS)
# Lab6 observability and SLO checks (stand must be running with the telemetry profile).
test-observability: test-observability:
$(PYTHON_LOCAL) scripts/check_evidence.py $(PYTHON_LOCAL) scripts/check_evidence.py
$(PYTHON_LOCAL) scripts/lab6_verify.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) scripts/lab6_verify.py --base-url "$(BASE_URL)" $(TLS_ARGS)
@@ -117,78 +50,154 @@ test-observability:
test-slo: test-slo:
$(PYTHON_LOCAL) scripts/lab6_track2.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) scripts/lab6_track2.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-idempotency:
$(PYTHON_LOCAL) student-tests/idempotency_parallel.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-lb-readiness:
scripts/lb_readiness_check.sh
load: load:
$(PYTHON_LOCAL) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/restart.sh"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
$(PYTHON_LOCAL) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover: test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/stop-one.sh"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON_LOCAL) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON_LOCAL) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
# Lab7: external endpoint must reject an untrusted CA; internal mTLS is checked
# by the student's own tests per contracts/trust-matrix.md.
test-security:
$(PYTHON_LOCAL) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
# Локальный запуск без прокси: в окружении автора HTTP(S)_PROXY ломает localhost.
smoke-local:
$(PYTHON_LOCAL) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
load-local:
$(PYTHON_LOCAL) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
# Собственная проверка уровня 4: параллельные повторы одного Idempotency-Key
# через LB обязаны создать ровно одно сообщение.
test-idempotency:
$(PYTHON_LOCAL) student-tests/idempotency_parallel.py --base-url "$(BASE_URL)" $(TLS_ARGS)
# Собственная проверка уровня 4: LB обязан убрать из ротации реплику, которая
# осталась доступной, но потеряла БД (readiness 503).
test-lb-readiness:
scripts/lb_readiness_check.sh
COMPOSE_BIN ?= docker compose
COMPOSE_FILE ?= compose.yaml
ENV_FILE ?= .env
TELEMETRY_PROFILE ?= telemetry
up: init-secrets
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) --profile $(TELEMETRY_PROFILE) up -d --build
# Lab5 regression without the telemetry profile.
up-base: init-secrets
TELEMETRY_ENABLED=0 $(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) up -d --build
init-secrets:
./scripts/init-secrets.sh
down:
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) --profile $(TELEMETRY_PROFILE) down
ps:
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) --profile $(TELEMETRY_PROFILE) ps
logs:
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) --profile $(TELEMETRY_PROFILE) logs -f --tail 100
# Operator views: the failed registry is PostgreSQL, the DLQ is a backstop.
jobs-failed: jobs-failed:
$(PYTHON_LOCAL) scripts/securityctl.py jobctl failed $(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) run --rm --entrypoint /usr/local/bin/jobctl worker failed
replay: replay:
@test -n "$(JOB)" || (echo "Set JOB=<job_id>"; exit 2) @test -n "$(JOB)" || (echo "Set JOB=<job_id>"; exit 2)
$(PYTHON_LOCAL) scripts/securityctl.py jobctl replay -job "$(JOB)" $(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) run --rm --entrypoint /usr/local/bin/jobctl worker replay -job "$(JOB)"
reprocess: reprocess:
@test -n "$(ATTACHMENT)" || (echo "Set ATTACHMENT=<attachment_id>"; exit 2) @test -n "$(ATTACHMENT)" || (echo "Set ATTACHMENT=<attachment_id>"; exit 2)
$(PYTHON_LOCAL) scripts/securityctl.py jobctl reprocess -attachment "$(ATTACHMENT)" -pipeline "$(PIPELINE)" $(COMPOSE_BIN) --env-file $(ENV_FILE) -f $(COMPOSE_FILE) run --rm --entrypoint /usr/local/bin/jobctl worker reprocess -attachment "$(ATTACHMENT)" -pipeline "$(PIPELINE)"
.DEFAULT_GOAL := help
GO ?= go
APP_NAME ?= messenger
CMD_PKG := ./cmd/$(APP_NAME)
LOCAL_BIN := $(CURDIR)/bin
GOLANGCI_LINT_VERSION ?= v2.13.2
GOLANGCI_LINT := $(LOCAL_BIN)/golangci-lint
OPENAPI_SPEC := contracts/openapi.json
OGEN_CONFIG := .ogen.yml
OAS_DIR := internal/transport/rest/internal/oas
-include .env
export
# .env feeds local tooling, but its application variables must not leak into the
# Go test process: the config tests assert defaults and the dev YAML, so an
# ambient REDIS_ENABLED/CACHE_ENABLED would fail them.
ENV_KEYS := $(shell sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' .env 2>/dev/null)
CLEAN_ENV = env $(addprefix -u ,$(ENV_KEYS))
.PHONY: unit-test
unit-test: unit-test:
$(CLEAN_ENV) $(GO) test -race -shuffle=on -count=1 -timeout=5m ./... $(CLEAN_ENV) $(GO) test -race -shuffle=on -count=1 -timeout=5m ./...
.PHONY: integration-test
integration-test: integration-test:
$(PYTHON_LOCAL) scripts/lab7_integration.py $(GO) test -tags=integration -p 1 -count=1 -timeout=15m ./internal/storage/postgres ./internal/storage/redis
.PHONY: test-db-up test-db-down
test-db-up: test-db-up:
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f docker-compose.local.yaml up -d --no-build postgres redis @docker-compose -f docker-compose.local.yaml up -d --wait postgres redis
test-db-down: test-db-down:
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f docker-compose.local.yaml down @docker-compose -f docker-compose.local.yaml down
dev-up: build # не учитываем генеренные файлы, также cmd в подсчете покрытия
COMPOSE_FILE=docker-compose.local.yaml $(PYTHON_LOCAL) scripts/securityctl.py up COVER_EXCLUDE ?= /(mocks|oas)/|/cmd/
dev-down: .PHONY: cover
$(COMPOSE_BIN) --env-file $(ENV_FILE) -f docker-compose.local.yaml down cover:
$(CLEAN_ENV) $(GO) test -race -shuffle=on -count=1 -timeout=5m \
dev-reload: -covermode=atomic -coverprofile=coverage.out.tmp ./...
COMPOSE_FILE=docker-compose.local.yaml $(PYTHON_LOCAL) scripts/securityctl.py restart @grep -Ev '$(COVER_EXCLUDE)' coverage.out.tmp > coverage.out
@rm coverage.out.tmp
migrate: $(GO) tool cover -func=coverage.out | tail -n 1
$(COMPOSE) run --rm --no-deps migrate $(GO) tool cover -html=coverage.out
.PHONY: generate
generate: generate-api generate-mocks sqlc generate: generate-api generate-mocks sqlc
.PHONY: generate-api
generate-api: generate-api:
$(GO) run ./tools/specgen $(GO) run ./tools/specgen
$(GO) tool ogen --config $(OGEN_CONFIG) --target $(OAS_DIR) --package oas --clean .cache/openapi.codegen.json $(GO) tool ogen --config $(OGEN_CONFIG) --target $(OAS_DIR) --package oas --clean .cache/openapi.codegen.json
.PHONY: generate-mocks
generate-mocks: generate-mocks:
$(GO) tool mockery $(GO) tool mockery
.PHONY: sqlc
sqlc: sqlc:
$(GO) tool sqlc generate $(GO) tool sqlc generate
COVER_EXCLUDE ?= /(mocks|oas)/|/cmd/ .PHONY: dev-up dev-down dev-reload
cover: dev-up:
$(CLEAN_ENV) $(GO) test -race -shuffle=on -count=1 -timeout=5m -covermode=atomic -coverprofile=coverage.out.tmp ./... @docker-compose -f docker-compose.local.yaml up -d --build
@grep -Ev '$(COVER_EXCLUDE)' coverage.out.tmp > coverage.out
@rm coverage.out.tmp
$(GO) tool cover -func=coverage.out
$(GOLANGCI_LINT): go.mod Makefile dev-down:
@docker-compose -f docker-compose.local.yaml down
dev-reload:
@docker-compose -f docker-compose.local.yaml up -d --build --force-recreate
.PHONY: migrate
migrate:
$(GO) run ./cmd/migrate up
$(GOLANGCI_LINT):
GOBIN=$(LOCAL_BIN) $(GO) install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) GOBIN=$(LOCAL_BIN) $(GO) install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)
lint: $(GOLANGCI_LINT) lint: $(GOLANGCI_LINT)
+16 -81
View File
@@ -1,102 +1,37 @@
# Отчёт — лабораторная 7 # Отчёт — лабораторная 7
- Автор, группа: Кунецкий Владислав, bvt2303 - Автор, группа: TODO
- Целевая оценка: 5; выбран трек 2 (жизненный цикл PKI/secrets) - Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: ветка `lab7` в origin; реализация, отчёт и evidence — commit `1b6e96c` поверх skeleton `20afc2c` (ранние `3441f22`, `d923140`, `30b6672` объединены squash при публикации); PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab7/pulls/10. - Commit/PR: TODO после публикации
- Использованные источники: README lab7 и `contracts/trust-matrix.md`; OWASP Password Storage и File Upload Cheat Sheets; документация OpenBao (AppRole/cert auth, policies, PKI, production hardening); документация Go `crypto/tls`, `crypto/x509`, `os.Root`; документация HAProxy, RabbitMQ, SeaweedFS, Grafana/Loki/Tempo/Prometheus, OpenTelemetry Collector. ИИ-ассистент использовался для генерации и ревью кода, подготовки проверок и текста отчёта; все команды и наблюдения перепроверены на локальном стенде, секреты в отчёт не включались. - Использованные источники, библиотеки и помощь ИИ: TODO
## Запуск из чистого clone ## Запуск из чистого clone
Требования: Docker Desktop/Compose v2, Go 1.27.3, Python 3.9+, `make`, `openssl` в PATH. Внешние сервисы не нужны: все зависимости поднимаются из `compose.yaml`, версии образов закреплены digest. TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
```sh
cp .env.example .env
make up # prepare -> build -> bootstrap -> up; создаёт локальные PKI/секреты
make test # публичный HTTPS smoke
make test-security # внешний TLS trust + отрицательные проверки
```
`make up` создаёт PKI, backend credentials, init/unseal OpenBao, применяет миграции, инициализирует S3 и поднимает стенд. Секреты и приватные ключи создаются локально; в Git, образы и telemetry они не попадают. CA для тестов: `secrets/lab7/pki/operator/current/ca.crt` (публичный сертификат; приватный ключ остаётся у оператора). Готовность — `GET /health/ready` по `https://localhost:8443` с проверкой CA и hostname.
Дополнительные проверки:
```sh
make test-lab7 # security.json: полный набор отрицательных проверок
make test-pki # 3 изолированных прогона PKI lifecycle (трек 2)
make auth-budget # измеренный бюджет Argon2/login
make renewer # foreground renewal/CRL loop; под supervisor — постоянный
make renew-once # один цикл renew всех ролей + sync-crls (evidence/lab7/renewer.json)
make validate PYTHON=.venv/bin/python
make unit-test integration-test
python3 scripts/lab7_scan.py --output evidence/lab7/scans
```
Остановка: `make down` (volumes сохраняются). Намеренное удаление учебных данных: `make down`, затем `docker compose --env-file .env down --volumes --remove-orphans`, удалить `secrets/lab7` и `~/.local/share/mtusi-lab7/<project>` (root/unseal state). Команда удаляет все данные стенда и необратима.
## Архитектура и решения ## Архитектура и решения
Процессы: HAProxy LB (TLS ingress + mTLS к API), две Go API-реплики, worker, relay, PostgreSQL, Redis, RabbitMQ, SeaweedFS, OpenBao, OTel Collector с TLS-gateway, Prometheus, Loki, Tempo, Grafana. Одноразовые `migrate`, `s3init`, `volume-init`, `jobctl` — явные operator jobs. TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Клиент проходит TLS с проверкой CA и DNS SAN до LB; LB требует mTLS к каждой API-реплике, Go server требует точный URI `spiffe://mtusi/lb`. Для остальных связей — отдельные identities и проверка SAN/ACL по матрице: PostgreSQL native TLS + SCRAM и раздельные роли, S3 native TLS + SigV4 и role prefixes, RabbitMQ native mTLS с EXTERNAL-пользователями и ACL, Collector mTLS gateway с CN allowlist, Grafana→data sources mTLS с query-only allowlist, Redis TLS + ACL. OpenBao — не dev-mode, persistent raft; приложение аутентифицируется сертификатом, получает собственный KV и собственный PKI issue path; токены 60 s (max 300 s), KV freshness 60 s, admission закрывается за 1 s до ближайшего lease.
Секреты версионируются: immutable `versions/<name>` + атомарный regular-file `current-version`; Go и HAProxy перечитывают leaf/CRL на новых соединениях, trust changes требуют рестарта. `securityctl revoke` после `pki/revoke` явно вызывает OpenBao `GET /pki/crl/rotate` и публикует свежий CRL: `auto_rebuild` сам по себе обновляет только истёкший CRL, поэтому без rotate отозванный serial оставался бы вне bundle. Отдельный offline root/unseal state — у оператора (`~/.local/share/mtusi-lab7/<project>`, 0700/0600). `make renewer` — host-side supervisor loop: каждые 30 минут выпускает новые leaf для всех ролей (service cert auth; operator fallback только при классифицированном expiry, иначе fail loudly), перезагружает native owners и вызывает `sync-crls`; CRL обновляются чаще срока действия, offline root CRL — за сутки до NextUpdate. Если стенд был остановлен дольше TTL, `bootstrap`/`make up` вызывает `recover_transport` и перевыпускает истёкшие role-leaf до старта зависимостей (`expired_identities_renewed`). Loop не монтируется в app-контейнеры, потому что ему нужен Docker CLI для reload native services. Контейнеры: non-root, read_only где совместимо, `no-new-privileges`, drop ALL capabilities (кроме объяснённых), resource limits, отдельные сети `default`/`observability`/`edge`; наружу опубликованы только нужный TLS ingress и локальные admin-интерфейсы.
Из lab6 перенесены API/worker/relay, асинхронные вложения с outbox, идемпотентность, кэш/лимиты и наблюдаемость. В lab7 добавлены: TLS/mTLS на всех границах, OpenBao с cert auth и scoped policies, PKI lifecycle (renewal/expiry/revocation/CA rollover), Argon2id, общий login rate limit, hardening контейнеров, модель угроз и scan triage. Контракт OpenAPI 1.7.0 не менялся; публичные тесты не ослаблялись.
## Доказательства критериев ## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke, HTTPS CA/hostname | `make test`; `make test-security` | trusted HTTPS проходит; недоверенный CA отклоняется ошибкой верификации | `evidence/lab7/security.json` (`public_ca_hostname`), `final-verification.txt` | | Публичный smoke | make test | TODO | TODO |
| Argon2id salt/параметры | `make auth-budget`; `internal/platform/password` | m=19 MiB, t=2, p=1; host-бенчмарк Argon2 p50 14.7 ms, p95 17.0 ms; API login: 120 запросов, p50 5.2 ms, p95 57.6 ms, 429 при исчерпании бюджета; cgroup peak 76–92 MB (after) | `evidence/lab7/auth.json` | | Остальные пункты уровня 3 | TODO | TODO | TODO |
| LB→API обязательный mTLS + identity | `make test-lab7`; `make test-pki` | lb 200; нет cert/чужой CA/неверный URI — TLS rejection; отзыв старого LB отклоняется на свежем соединении | `security.json` (`mtls_and_telemetry_acl`), `track2.json` | | Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Backend TLS и минимальные права | `make test-lab7` | PostgreSQL SQLSTATE 42501 для чужих таблиц; S3 GET/PUT/DELETE/COPY по чужому prefix — 403 (worker bucket-level LIST возвращает metadata, задокументировано); Redis foreign key NOPERM; broker EXTERNAL ACL; Bao foreign KV/issuer 403 | `security.json` (`database_privileges`, `s3_prefix_acl`, `redis_tls_cache_acl`, `broker_external_acl`, `bao_api_policy`) | | Выбранный трек 5, если заявлен | TODO | TODO | TODO |
| OpenBao non-dev, scoped, persistent | `securityctl.py up`, `audit-summary`; `make test-lab7` | root token отозван; app использует cert auth; unseal — у оператора; KV/issuer только свои; audit пишет login/issue/revoke/renew | `security.json` (`bao_api_policy`), `track2.json` (`bootstrap.root_token_revoked`, `actions.bao_audit`), `bao-audit.txt` |
| Контейнеры без privileged/host/socket | `runtime_container_network_isolation` | apps non-root/read_only; из соседнего namespace connection refused; лишние capabilities сняты | `security.json`, `compose.yaml` |
| Rate limit/body limit/ACL/logout/expiry | `make test-lab7`; `make test` | общий 429 + `Retry-After`; чужой чат/вложение недоступны; logout и DB expiry закрывают доступ; forged `X-User-Id` не меняет identity | `security.json` (`shared_rate_limit`, `http_acl_logout_expiry_bounds`, `real_async_pipeline`) |
| Уровень 4: broker и Collector mTLS | `broker_external_acl`, `mtls_and_telemetry_acl` | разные identities; разрешённая роль 200/публикация, запрещённая роль 403, нет cert/чужой CA — TLS rejection | `security.json` |
| Отказ plaintext/чужому CA на backends и telemetry | `make test-lab7` | PostgreSQL/Redis/S3 plaintext-канал отвергнут; S3 с чужим CA — ca_rejected; Loki не содержит sentinel-секретов | `security.json` (`plaintext_refusal`, `credential_log_sentinels`) |
| Уровень 4: rehash, отсутствие утечек, login DoS | `auth-budget`, `credential_log_sentinels`; unit `TestAuthenticateUpgradesHashesWithCAS` | rehash старого hash реализован и покрыт unit-тестом (CAS), runtime-вход с legacy-PHC отдельно не снимался; пароли/токены не в логах; бюджет измерен | `auth.json`, `security.json`, `internal/service/session/service_test.go` |
| Уровень 4: ротация secret/leaf, отзыв, expiry/sealed | `make test-pki`; `make test-lab7` | leaf renewal без пересборки; отзыв старого leaf; sealed Bao закрывает admission; CA prepare→issue→retire с проверкой старой identity | `track2.json` |
| Уровень 4: hardening + scans + threat model | `runtime_container_network_isolation`; `scans/summary.json`; `security/THREAT_MODEL.md` | 13 образов просканированы, все scanner exits 0; достижимых findings в коде приложения нет; остаточные CVE разобраны по применимости | `scans/summary.json`, `security/SCAN_TRIAGE.md`, `THREAT_MODEL.md` |
| Уровень 5, трек 2 | `make test-pki` | 3 изолированных прогона: renewal/expiry/sealed/revocation/CA rollover под нагрузкой; измерены ошибки и восстановление; fallback на plaintext/verify-off отсутствует | `evidence/lab7/track2.json`, `renewer.json`, `bao-audit.txt` |
Примечание: `native-revocation.json`, `root-crl.json`, `verification.json`, `restart-scope.json`, `failover-scope.json`, `sequential-failover.json`, `track2-ca-before.json` и `track2-renewal-before.json` — pre-final fixtures предыдущих прогонов. Финальные заявления подкреплены `track2.json`, `security.json`, `auth.json`, `renewer.json`, `bao-audit.txt`, `resilience-final.txt` и `final-verification.txt`. TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
**Гипотеза трека 2:** при короткоживущих leaf и трёхфазном CA rollover стенд не имеет fallback на plaintext/verify-off, а окно отказа ограничено рестартом/сменой trust и восстанавливается без потери сообщений, вложений и sessions. Опровержение — любой успешный запрос без проверки TLS, сохранение старой identity после retire или потеря данных после recovery.
### Наблюдаемые отказы и восстановление
| Воздействие | Ожидание | Наблюдение | Время восстановления / потеря |
| --- | --- | --- | --- |
| Рестарт стенда (`make test-persistence ACTION_SCRIPT=scripts/restart.sh`) | сообщение, полные байты вложения и сессия сохраняются | Full attachment bytes, confirmed message and existing session preserved; имена volumes не изменились | данные не потеряны |
| Остановка одной API-реплики (`make test-failover ACTION_SCRIPT=scripts/stop-one.sh`) | вторая реплика продолжает сервис | 84 успешные записи, 0 failed attempts; message/attachment/session сохранены; stateful-сервисы не перезапускались | first recovery 1.365 s (`evidence/lab7/resilience-final.txt`) |
| Последовательная остановка обеих реплик (`student-tests/replica_failover.py`) | сервис восстанавливается после возврата реплик | 91 и 100 успешных записей, 0 failed; история 191 сообщение, дублей/потерь нет | 1.786 s / 0.889 s |
| Истечение API leaf под нагрузкой | admission закрывается, процесс завершается в bound, затем recovery | ready закрыт; bounded process exit; после issue 1h API восстановлен; сообщение/вложение сохранены | recovery 1.05–2.75 s в прогонах (`track2.json`) |
| Sealed OpenBao | admission закрывается не позже 60 s freshness; после unseal — recovery | ready закрыт; наблюдаемое закрытие 60.5–61.7 s (включая 1 s cadence watchdog); после unseal API/worker/relay восстановлены; сообщение/вложение сохранены | recovery 2.25–6.41 s (`track2.json`) |
| Отзыв старого leaf LB/Collector | свежие и resumption-попытки отклоняются | `tls_certificate_rejected`; новый leaf работает | без потери данных |
| CA rollover prepare→issue→retire | overlap старого trust, затем отказ старой identity и работа нового pipeline | старый leaf проходит в overlap; после retire отклоняется; новый upload/readiness, Bao/Redis/telemetry пути и retained bytes проходят | см. `track2.json` |
| Истечение offline root CRL | CRL обновляется оператором до final 24h | refreshed signed CRL, NextUpdate > 24h; unexpired CRL не перегенерируется; Docker targets не мутируются | без простоя |
## Эксперименты и отказы ## Эксперименты и отказы
Методика трека 2: `scripts/lab7_track2.py` создаёт отдельный compose-проект на каждый повтор (свои порты и volumes), поднимает полный стенд, гоняет замкнутый HTTPS-клиент 2 rps и выполняет фазы: baseline → leaf renewal (20 s TTL, watcher) → intentional expiry → recovery → sealed Bao → recovery → LB leaf revoke → worker S3 secret rotation → CA prepare/issue/retire. Для каждой фазы фиксируются HTTP-статусы, ошибки по классам, latency, окна отказа и восстановление. После каждой фазы CA rollover сначала прогоняется полный публичный upload pipeline (retry с 15 s timeout, deadline 180 s), затем проверяются контрактные детали. Ограничения: один Docker Desktop host, single-node PostgreSQL/Redis/RabbitMQ/SeaweedFS/OpenBao, замкнутый клиент — это lifecycle-проба, а не capacity benchmark; оба API leaf намеренно истекают (total outage, не A/B failover); TLS tickets/cache отключены. TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Результат трека: `evidence/lab7/track2.json` — 3/3 повторений, `passed: true`. Leaf renewal: по 139–140 запросов на прогон, 0 ошибок, p95 12.9–18.2 ms. Intentional expiry: recovery 1.05–2.75 s; sealed Bao: recovery 2.25–6.41 s; отзыв LB leaf: окна ≈ 0.5 s; CA prepare/issue/retire: 179.4–203.2 s на фазу, 114–153 ошибок на 355–402 запросов (1–2 connection/TLS, 6–8 HTTP 502, 107–144 HTTP 503 при rolling restart/store reload), затем `final_recovery_control` — 60/60 успешных, 0 ошибок. `warm_pipeline` после каждой фазы: 1 попытка, 0 ошибок; retire перепубликовал 19 identities, старый LB отклонён с `TLSV1_ALERT_UNKNOWN_CA`. Ошибки ограничены окнами рестартов и перечислены в `load.observed_outage_windows`; fallback на plaintext/verify-off отсутствует. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
Argon2/login: `auth.json` содержит два измерения. Host-бенчмарк `hash_verify`: m=19 MiB, t=2, p=1, p50 14.7 ms, p95 17.0 ms, peak RSS 48.0 MB; это верхняя оценка стоимости Argon2, не API-контейнер. API-проба `api_auth`: 120 запросов, p50 5.2 ms, p95 57.6 ms, 429 при превышении account/source/global лимитов, cgroup peak 76–92 MB (after). Бюджет дериваций ограничен per-process, `ErrBusy` отдаётся как 429 с `Retry-After`, неизвестный пользователь тратит тот же Argon2-бюджет (dummy verify), ошибка необязательного rehash не блокирует успешный вход. Ограничение: host-бенчмарк не воспроизводит CPU-квоту API; API-проба измеряет реальный контейнер, но включает сеть и rate limiter. | TODO | TODO | TODO | TODO |
Сканирование: `scans/summary.json` — 13 образов, все scanner exits 0; `govulncheck` не нашёл достижимых symbol/package findings в коде приложения (module-only GO-2026-5932 разобран в triage). Остаточные HIGH/MEDIUM относятся к инфраструктурным образам (Grafana/Loki и др.) и ограничены сетевыми границами, non-root, resource limits и отсутствием публикации; детали и residual risk — в `security/SCAN_TRIAGE.md`.
## Ограничения и следующие шаги ## Ограничения и следующие шаги
- Стенд single-node: нет HA для PostgreSQL/Redis/RabbitMQ/SeaweedFS/OpenBao; проверены отказ API-реплик и рестарты, но не отказ stateful-узла. TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Замкнутый клиент 2 rps и 30 s control-фазы — измерение lifecycle, не пропускная способность; p95 включает окна рестартов.
- Оба API leaf истекают намеренно, поэтому expiry-фаза измеряет fail-closed total outage и recovery, а не переключение между валидными leaf.
- TLS tickets/ClientSessionCache отключены: проверяется fresh connection и явная resumption-попытка, положительный resumption не заявляется.
- CA private key/unseal shares — offline у оператора; автоматизация их хранения не реализована и не заявляется.
- Модель оператора учебная: root key и 2-of-3 unseal shares лежат в одном operator-only каталоге на том же хосте (0700/0600), а operator-сертификат по политике эквивалентен root. Это не HSM и не раздельное хранение долей; отзыв root token — defense-in-depth, а не граница против скомпрометированного оператора.
- `jobctl`/миграции используют DB-роль оператора; отдельная least-privilege migration role — production-улучшение, не заявленное здесь.
- TLS-аудит покрывает заявленные mTLS/ACL-границы, plaintext-refusal для PostgreSQL/Redis/S3 и sentinel-скан Loki; Tempo-атрибуты и historic deleted logs не text-сканируются. Это остаточный пробел, перечисленный в threat model.
- `make renewer` — host-side loop под supervisor; в production его место занимает оркестратор/короткоживущие workload identities.
- Следующие шаги: HA stateful-слоя, динамические DB credentials, автоматическая ротация backend secrets по TTL, более строгий контроль первого bootstrap root of trust.
+60 -82
View File
@@ -7,8 +7,6 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"os" "os"
"os/signal"
"syscall"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
@@ -25,35 +23,23 @@ func main() {
os.Exit(2) os.Exit(2)
} }
switch os.Args[1] { cfg, err := config.Load()
case "failed", "replay", "reprocess", "duplicate", "inspect":
default:
usage()
os.Exit(2)
}
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func run() error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
cfg, err := config.LoadOperator()
if err != nil { if err != nil {
return fmt.Errorf("load config: %w", err) fmt.Fprintln(os.Stderr, "load config:", err)
os.Exit(1)
} }
log := logger.New(logger.WithLevel(cfg.SlogLevel()), logger.WithFormat(logger.FormatConsole)) log := logger.New(logger.WithLevel(cfg.SlogLevel()), logger.WithFormat(logger.FormatConsole))
slog.SetDefault(log) slog.SetDefault(log)
ctx, cancel := context.WithTimeout(ctx, 30*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() defer cancel()
store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second) store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second)
if err != nil { if err != nil {
return fmt.Errorf("connect database: %w", err) fmt.Fprintln(os.Stderr, "connect database:", err)
cancel()
os.Exit(1) //nolint:gocritic // main exits after DB setup failure
} }
defer store.Close() defer store.Close()
@@ -61,17 +47,18 @@ func run() error {
switch os.Args[1] { switch os.Args[1] {
case "failed": case "failed":
return runFailed(ctx, repo) runFailed(ctx, repo)
case "replay": case "replay":
return runReplay(ctx, repo, cfg) runReplay(ctx, repo, cfg)
case "reprocess": case "reprocess":
return runReprocess(ctx, repo, cfg) runReprocess(ctx, repo, cfg)
case "duplicate": case "duplicate":
return runDuplicate(ctx, repo) runDuplicate(ctx, repo)
case "inspect": case "inspect":
return runInspect(ctx, repo) runInspect(ctx, repo)
default: default:
return fmt.Errorf("unknown command %q", os.Args[1]) usage()
os.Exit(2)
} }
} }
@@ -85,132 +72,119 @@ func usage() {
inspect -attachment ATTACHMENT_ID`) inspect -attachment ATTACHMENT_ID`)
} }
func runFailed(ctx context.Context, repo *postgres.PipelineRepository) error { func runFailed(ctx context.Context, repo *postgres.PipelineRepository) {
flags := flag.NewFlagSet("failed", flag.ContinueOnError) flags := flag.NewFlagSet("failed", flag.ExitOnError)
limit := flags.Int("limit", 50, "maximum jobs") limit := flags.Int("limit", 50, "maximum jobs")
if err := flags.Parse(os.Args[2:]); err != nil { _ = flags.Parse(os.Args[2:])
return err
}
jobs, err := repo.ListFailedJobs(ctx, *limit) jobs, err := repo.ListFailedJobs(ctx, *limit)
if err != nil { if err != nil {
return err fail(err)
} }
return printJSON(jobs) printJSON(jobs)
} }
func runReplay(ctx context.Context, repo *postgres.PipelineRepository, cfg config.Config) error { func runReplay(ctx context.Context, repo *postgres.PipelineRepository, cfg config.Config) {
flags := flag.NewFlagSet("replay", flag.ContinueOnError) flags := flag.NewFlagSet("replay", flag.ExitOnError)
jobID := flags.String("job", "", "job id") jobID := flags.String("job", "", "job id")
attempts := flags.Int("attempts", cfg.Processing.MaxAttempts, "additional attempts") attempts := flags.Int("attempts", cfg.Processing.MaxAttempts, "additional attempts")
if err := flags.Parse(os.Args[2:]); err != nil { _ = flags.Parse(os.Args[2:])
return err
}
id, err := uuid.Parse(*jobID) id, err := uuid.Parse(*jobID)
if err != nil { if err != nil {
return fmt.Errorf("invalid job id: %w", err) fail(fmt.Errorf("invalid job id: %w", err))
} }
job, err := repo.ReplayJob(ctx, id, *attempts) job, err := repo.ReplayJob(ctx, id, *attempts)
if err != nil { if err != nil {
return err fail(err)
} }
return printJSON(job) printJSON(job)
} }
func runReprocess(ctx context.Context, repo *postgres.PipelineRepository, cfg config.Config) error { func runReprocess(ctx context.Context, repo *postgres.PipelineRepository, cfg config.Config) {
flags := flag.NewFlagSet("reprocess", flag.ContinueOnError) flags := flag.NewFlagSet("reprocess", flag.ExitOnError)
attachmentID := flags.String("attachment", "", "attachment id") attachmentID := flags.String("attachment", "", "attachment id")
version := flags.Int("pipeline", 2, "target pipeline version") version := flags.Int("pipeline", 2, "target pipeline version")
if err := flags.Parse(os.Args[2:]); err != nil { _ = flags.Parse(os.Args[2:])
return err
}
if _, ok := imageproc.Pipeline(*version); !ok { if _, ok := imageproc.Pipeline(*version); !ok {
return fmt.Errorf("unsupported pipeline version %d", *version) fail(fmt.Errorf("unsupported pipeline version %d", *version))
} }
id, err := uuid.Parse(*attachmentID) id, err := uuid.Parse(*attachmentID)
if err != nil { if err != nil {
return fmt.Errorf("invalid attachment id: %w", err) fail(fmt.Errorf("invalid attachment id: %w", err))
} }
jobID, err := uuid.NewV7() jobID, err := uuid.NewV7()
if err != nil { if err != nil {
return err fail(err)
} }
job, err := repo.Reprocess( job, err := repo.Reprocess(ctx, id, *version, cfg.Processing.MaxAttempts, jobID)
ctx,
id,
*version,
cfg.Processing.MaxAttempts,
jobID,
)
if err != nil { if err != nil {
return err fail(err)
} }
return printJSON(job) printJSON(job)
} }
func runDuplicate(ctx context.Context, repo *postgres.PipelineRepository) error { func runDuplicate(ctx context.Context, repo *postgres.PipelineRepository) {
flags := flag.NewFlagSet("duplicate", flag.ContinueOnError) flags := flag.NewFlagSet("duplicate", flag.ExitOnError)
attachmentID := flags.String("attachment", "", "attachment id") attachmentID := flags.String("attachment", "", "attachment id")
jobID := flags.String("job", "", "specific job id (old pipeline version)") jobID := flags.String("job", "", "specific job id (old pipeline version)")
if err := flags.Parse(os.Args[2:]); err != nil { _ = flags.Parse(os.Args[2:])
return err
}
if *jobID != "" { if *jobID != "" {
id, err := uuid.Parse(*jobID) id, err := uuid.Parse(*jobID)
if err != nil { if err != nil {
return fmt.Errorf("invalid job id: %w", err) fail(fmt.Errorf("invalid job id: %w", err))
} }
message, err := repo.DuplicateJob(ctx, id) message, err := repo.DuplicateJob(ctx, id)
if err != nil { if err != nil {
return err fail(err)
} }
return printJSON(message) printJSON(message)
return
} }
id, err := uuid.Parse(*attachmentID) id, err := uuid.Parse(*attachmentID)
if err != nil { if err != nil {
return fmt.Errorf("attachment or job id is required: %w", err) fail(fmt.Errorf("attachment or job id is required: %w", err))
} }
message, err := repo.Duplicate(ctx, id) message, err := repo.Duplicate(ctx, id)
if err != nil { if err != nil {
return err fail(err)
} }
return printJSON(message) printJSON(message)
} }
func runInspect(ctx context.Context, repo *postgres.PipelineRepository) error { func runInspect(ctx context.Context, repo *postgres.PipelineRepository) {
flags := flag.NewFlagSet("inspect", flag.ContinueOnError) flags := flag.NewFlagSet("inspect", flag.ExitOnError)
attachmentID := flags.String("attachment", "", "attachment id") attachmentID := flags.String("attachment", "", "attachment id")
if err := flags.Parse(os.Args[2:]); err != nil { _ = flags.Parse(os.Args[2:])
return err
}
id, err := uuid.Parse(*attachmentID) id, err := uuid.Parse(*attachmentID)
if err != nil { if err != nil {
return fmt.Errorf("invalid attachment id: %w", err) fail(fmt.Errorf("invalid attachment id: %w", err))
} }
attachment, err := repo.GetForID(ctx, id) attachment, err := repo.GetForID(ctx, id)
if err != nil { if err != nil {
return err fail(err)
} }
variants, err := repo.ListVariants(ctx, id, attachment.PipelineVersion) variants, err := repo.ListVariants(ctx, id, attachment.PipelineVersion)
if err != nil { if err != nil {
return err fail(err)
} }
var jobOutput any var jobOutput any
@@ -220,18 +194,22 @@ func runInspect(ctx context.Context, repo *postgres.PipelineRepository) error {
jobOutput = job jobOutput = job
} }
return printJSON(map[string]any{ printJSON(map[string]any{
"attachment": attachment, "attachment": attachment,
"variants": variants, "variants": variants,
"job": jobOutput, "job": jobOutput,
}) })
} }
func printJSON(value any) error { func printJSON(value any) {
encoder := json.NewEncoder(os.Stdout) encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
if err := encoder.Encode(value); err != nil { if err := encoder.Encode(value); err != nil {
return fmt.Errorf("write output: %w", err) fail(err)
} }
return nil }
func fail(err error) {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
} }
+96 -164
View File
@@ -5,20 +5,18 @@ import (
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"net"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
"sync"
"syscall" "syscall"
"time" "time"
"mtusi-messenger/internal/config" "mtusi-messenger/internal/config"
"mtusi-messenger/internal/health" "mtusi-messenger/internal/health"
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
"mtusi-messenger/internal/platform/bao"
"mtusi-messenger/internal/platform/cache" "mtusi-messenger/internal/platform/cache"
"mtusi-messenger/internal/platform/objectstore" "mtusi-messenger/internal/platform/objectstore"
"mtusi-messenger/internal/platform/tlsconfig"
"mtusi-messenger/internal/platform/token" "mtusi-messenger/internal/platform/token"
"mtusi-messenger/internal/service/attachment" "mtusi-messenger/internal/service/attachment"
"mtusi-messenger/internal/service/chat" "mtusi-messenger/internal/service/chat"
@@ -34,85 +32,58 @@ import (
var version = "dev" var version = "dev"
func main() { func main() {
if err := execute(); err != nil { log := logger.New()
logger.New().Error("api stopped with error", slog.Any("error", err))
os.Exit(1)
}
}
func execute() (err error) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
serviceCtx, manager, err := bao.Start(ctx, "api")
if err != nil {
return fmt.Errorf("start secret manager: %w", err)
}
var shutdown func(context.Context) error
defer func() {
manager.Stop()
shutdownCtx, cancel := manager.ShutdownContext(serviceCtx)
defer cancel()
if shutdown != nil {
err = errors.Join(err, shutdown(shutdownCtx))
}
err = errors.Join(err, manager.Close(serviceCtx))
if errors.Is(context.Cause(serviceCtx), bao.ErrExpired) {
err = errors.Join(err, bao.ErrExpired)
}
}()
cfg, err := config.Load() cfg, err := config.Load()
if err != nil { if err != nil {
return fmt.Errorf("load config: %w", err) log.Error("load config", slog.Any("error", err))
os.Exit(1)
} }
log := logger.New(
log = logger.New(
logger.WithLevel(cfg.SlogLevel()), logger.WithLevel(cfg.SlogLevel()),
logger.WithFormat(cfg.LoggerFormat()), logger.WithFormat(cfg.LoggerFormat()),
) )
shutdown, err = telemetry.Setup(serviceCtx, "messenger-api", version)
if err != nil { shutdown, telemetryErr := telemetry.Setup(context.Background(), "messenger-api", version)
return fmt.Errorf("setup telemetry: %w", err) if telemetryErr != nil {
log.Warn("telemetry setup failed; continuing without OTLP", slog.Any("error", telemetryErr))
shutdown = func(context.Context) error { return nil }
} }
log = telemetry.WrapLogger(log, "messenger-api", cfg.SlogLevel()) log = telemetry.WrapLogger(log, "messenger-api", cfg.SlogLevel())
slog.SetDefault(log) slog.SetDefault(log)
return run( if err := run(cfg, log); err != nil {
serviceCtx, log.Error("shutdown with error", slog.Any("error", err))
cfg, shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
log, _ = shutdown(shutdownCtx)
manager, cancel()
) os.Exit(1)
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := shutdown(shutdownCtx); err != nil {
log.Warn("telemetry shutdown failed", slog.Any("error", err))
}
} }
func run( func run(cfg config.Config, log *slog.Logger) error {
ctx context.Context, ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
cfg config.Config, defer stop()
log *slog.Logger,
manager *bao.Manager, store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, postgres.WithQueryTracer(telemetry.NewPGXTracer()))
) (err error) {
store, err := postgres.New(
ctx,
cfg.Postgres,
time.Duration(cfg.Idempotency.TTLSeconds)*time.Second,
postgres.WithQueryTracer(telemetry.NewPGXTracer()),
)
if err != nil { if err != nil {
return fmt.Errorf("connect database: %w", err) return fmt.Errorf("connect database: %w", err)
} }
defer func() { defer store.Close()
err = errors.Join(err, finish(ctx, manager, func(context.Context) error {
store.Close()
return nil
}))
}()
if err := telemetry.RegisterDBPool(store.PoolStats); err != nil { if err := telemetry.RegisterDBPool(store.PoolStats); err != nil {
log.WarnContext(ctx, "register db pool metrics", slog.Any("error", err)) log.Warn("register db pool metrics", slog.Any("error", err))
} }
if err := telemetry.RegisterProcessMetrics(); err != nil { if err := telemetry.RegisterProcessMetrics(); err != nil {
log.WarnContext(ctx, "register process metrics", slog.Any("error", err)) log.Warn("register process metrics", slog.Any("error", err))
} }
objectStoreConcrete, err := objectstore.New(objectstore.Config{ objectStoreConcrete, err := objectstore.New(objectstore.Config{
@@ -128,7 +99,6 @@ func run(
if err != nil { if err != nil {
return fmt.Errorf("connect object store: %w", err) return fmt.Errorf("connect object store: %w", err)
} }
defer objectStoreConcrete.Close()
objectStore := telemetry.WrapStore(objectStoreConcrete) objectStore := telemetry.WrapStore(objectStoreConcrete)
@@ -150,16 +120,39 @@ func run(
log, log,
) )
redisCache, err := connectRedis(ctx, cfg.Redis) sweeper := attachment.NewSweeper(
pipelineRepository,
objectStore,
store,
cfg.S3.SweepGrace,
cfg.Staging.OrphanGrace,
cfg.Staging.FailedRetention,
cfg.S3.SweepInterval,
log,
)
sweepCtx, stopSweeper := context.WithCancel(context.Background())
var sweepWait sync.WaitGroup
sweepWait.Add(1)
go func() {
defer sweepWait.Done()
sweeper.Run(sweepCtx)
}()
defer func() {
stopSweeper()
sweepWait.Wait()
}()
redisCache, err := connectRedis(cfg.Redis)
if err != nil { if err != nil {
return err return err
} }
defer func() { defer func() { _ = redisCache.Close() }()
err = errors.Join(err, finish(ctx, manager, func(context.Context) error {
return redisCache.Close()
}))
}()
sessionRepo := session.Repository(store.Sessions()) sessionRepo := session.Repository(store.Sessions())
chatRepo := chat.Repository(store.Chats()) chatRepo := chat.Repository(store.Chats())
@@ -184,7 +177,7 @@ func run(
) )
} }
log.InfoContext(ctx, "redis cache enabled", slog.String("host", cfg.Redis.Host), slog.Int("port", cfg.Redis.Port)) log.Info("redis cache enabled", slog.String("host", cfg.Redis.Host), slog.Int("port", cfg.Redis.Port))
} }
ttl := time.Duration(cfg.Session.TTLSeconds) * time.Second ttl := time.Duration(cfg.Session.TTLSeconds) * time.Second
@@ -208,59 +201,58 @@ func run(
if err != nil { if err != nil {
return fmt.Errorf("build router: %w", err) return fmt.Errorf("build router: %w", err)
} }
router = rest.WithLoginLimits(router, store, rest.DefaultLoginLimits(), log)
loader, err := tlsconfig.New(tlsconfig.FilesFromEnv())
if err != nil {
return fmt.Errorf("load server identity: %w", err)
}
server := &http.Server{ server := &http.Server{
Addr: net.JoinHostPort(cfg.Server.Host, "8080"), Addr: cfg.Addr(),
Handler: admission(ctx, router), Handler: router,
TLSConfig: loader.Server("spiffe://mtusi/lb"),
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout, ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout,
ReadTimeout: cfg.Server.ReadTimeout, ReadTimeout: cfg.Server.ReadTimeout,
BaseContext: func(net.Listener) context.Context { return ctx },
} }
healthServer := localHealthServer(ctx, health.New(pingers...), loader.VerifyTrustExact)
defer func() { errc := make(chan error, 1)
err = errors.Join(err, finish(ctx, manager, func(shutdownCtx context.Context) error {
results := make(chan error, 2) go func() {
for _, srv := range []*http.Server{server, healthServer} { log.Info("server started", slog.String("addr", cfg.Addr()))
go func() {
shutdownErr := srv.Shutdown(shutdownCtx) if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
if shutdownErr != nil { errc <- err
shutdownErr = errors.Join(shutdownErr, srv.Close()) }
}
results <- shutdownErr close(errc)
}()
}
return errors.Join(<-results, <-results)
}))
}() }()
errc := make(chan error, 2)
go func() { errc <- server.ListenAndServeTLS("", "") }()
go func() { errc <- healthServer.ListenAndServe() }()
log.InfoContext(ctx, "server started", slog.String("addr", server.Addr))
select { select {
case listenErr := <-errc: case err, ok := <-errc:
return fmt.Errorf("listen: %w", listenErr) if ok && err != nil {
case <-ctx.Done(): return fmt.Errorf("listen: %w", err)
}
return nil return nil
case <-ctx.Done():
} }
log.Info("shutdown signal received", slog.Duration("timeout", cfg.Server.ShutdownTimeout))
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
log.Info("server stopped")
return nil
} }
func connectRedis(ctx context.Context, cfg config.Redis) (cache.LockStore, error) { func connectRedis(cfg config.Redis) (cache.LockStore, error) {
if !cfg.Enabled { if !cfg.Enabled {
return cache.NoOpCache{}, nil return cache.NoOpCache{}, nil
} }
client, err := cache.NewRedis(ctx, cache.RedisConfig{ client, err := cache.NewRedis(cache.RedisConfig{
Host: cfg.Host, Host: cfg.Host,
Port: cfg.Port, Port: cfg.Port,
Username: cfg.Username,
Password: cfg.Password, Password: cfg.Password,
DB: cfg.DB, DB: cfg.DB,
MaxRetries: cfg.MaxRetries, MaxRetries: cfg.MaxRetries,
@@ -275,63 +267,3 @@ func connectRedis(ctx context.Context, cfg config.Redis) (cache.LockStore, error
return client, nil return client, nil
} }
func finish(parent context.Context, manager *bao.Manager, cleanup func(context.Context) error) error {
manager.Stop()
ctx, cancel := manager.ShutdownContext(parent)
defer cancel()
done := make(chan error, 1)
go func() { done <- cleanup(ctx) }()
select {
case err := <-done:
return err
case <-ctx.Done():
return fmt.Errorf("shutdown deadline: %w", ctx.Err())
}
}
func admission(ctx context.Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ctx.Err() != nil && r.URL.Path != "/health/live" {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
next.ServeHTTP(w, r)
})
}
func localHealthServer(ctx context.Context, checker *health.Checker, trust func() error) *http.Server {
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `{"status":"ok"}`)
})
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, _ *http.Request) {
if ctx.Err() != nil {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
probeCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if err := checker.Ping(probeCtx); err != nil || ctx.Err() != nil {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
if trust != nil {
if err := trust(); err != nil {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `{"status":"ok"}`)
})
return &http.Server{
Addr: "127.0.0.1:8084",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
BaseContext: func(net.Listener) context.Context { return ctx },
}
}
+17 -21
View File
@@ -7,16 +7,14 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"os" "os"
"os/signal"
"syscall"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3" "github.com/pressly/goose/v3"
"mtusi-messenger/internal/config" "mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
"mtusi-messenger/internal/storage/postgres"
"mtusi-messenger/internal/storage/postgres/migrations" "mtusi-messenger/internal/storage/postgres/migrations"
_ "github.com/jackc/pgx/v5/stdlib"
) )
func main() { func main() {
@@ -28,10 +26,8 @@ func main() {
} }
} }
func run(args []string) (err error) { func run(args []string) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) cfg, err := config.Load()
defer stop()
cfg, err := config.LoadOperator()
if err != nil { if err != nil {
return fmt.Errorf("load config: %w", err) return fmt.Errorf("load config: %w", err)
} }
@@ -46,14 +42,14 @@ func run(args []string) (err error) {
command = args[0] command = args[0]
} }
poolCfg, err := postgres.PoolConfig(cfg.Postgres) db, err := sql.Open("pgx", cfg.Postgres.DSN())
if err != nil { if err != nil {
return fmt.Errorf("database config: %w", err) return fmt.Errorf("open database: %w", err)
} }
db := stdlib.OpenDB(*poolCfg.ConnConfig)
defer func() { err = errors.Join(err, db.Close()) }()
pingCtx, cancel := context.WithTimeout(ctx, cfg.Postgres.ConnectTimeout) defer func() { _ = db.Close() }()
pingCtx, cancel := context.WithTimeout(context.Background(), cfg.Postgres.ConnectTimeout)
defer cancel() defer cancel()
if err := db.PingContext(pingCtx); err != nil { if err := db.PingContext(pingCtx); err != nil {
@@ -66,27 +62,27 @@ func run(args []string) (err error) {
return fmt.Errorf("set dialect: %w", err) return fmt.Errorf("set dialect: %w", err)
} }
if err := goCommand(ctx, db, command); err != nil { if err := goCommand(db, command); err != nil {
return err return err
} }
return nil return nil
} }
func goCommand(ctx context.Context, db *sql.DB, command string) error { func goCommand(db *sql.DB, command string) error {
switch command { switch command {
case "up": case "up":
return goose.UpContext(ctx, db, ".") return goose.Up(db, ".")
case "up-by-one": case "up-by-one":
return goose.UpByOneContext(ctx, db, ".") return goose.UpByOne(db, ".")
case "down": case "down":
return goose.DownContext(ctx, db, ".") return goose.Down(db, ".")
case "status": case "status":
return goose.StatusContext(ctx, db, ".") return goose.Status(db, ".")
case "version": case "version":
return goose.VersionContext(ctx, db, ".") return goose.Version(db, ".")
case "redo": case "redo":
return goose.RedoContext(ctx, db, ".") return goose.Redo(db, ".")
default: default:
return errors.New("unknown command: " + command + " (up, up-by-one, down, status, version, redo)") return errors.New("unknown command: " + command + " (up, up-by-one, down, status, version, redo)")
} }
+108 -191
View File
@@ -6,7 +6,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"net"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
@@ -19,7 +18,6 @@ import (
"mtusi-messenger/internal/domain" "mtusi-messenger/internal/domain"
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
"mtusi-messenger/internal/outbox" "mtusi-messenger/internal/outbox"
"mtusi-messenger/internal/platform/bao"
"mtusi-messenger/internal/storage/postgres" "mtusi-messenger/internal/storage/postgres"
"mtusi-messenger/internal/telemetry" "mtusi-messenger/internal/telemetry"
) )
@@ -29,84 +27,69 @@ const maxUnpublishedAge = 10 * time.Minute
var version = "dev" var version = "dev"
func main() { func main() {
if err := execute(); err != nil { log := logger.New()
logger.New().Error("relay stopped with error", slog.Any("error", err))
os.Exit(1)
}
}
func execute() (err error) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
serviceCtx, manager, err := bao.Start(ctx, "relay")
if err != nil {
return fmt.Errorf("start secret manager: %w", err)
}
var shutdown func(context.Context) error
defer func() {
manager.Stop()
shutdownCtx, cancel := manager.ShutdownContext(serviceCtx)
defer cancel()
if shutdown != nil {
err = errors.Join(err, shutdown(shutdownCtx))
}
err = errors.Join(err, manager.Close(serviceCtx))
if errors.Is(context.Cause(serviceCtx), bao.ErrExpired) {
err = errors.Join(err, bao.ErrExpired)
}
}()
cfg, err := config.Load() cfg, err := config.Load()
if err != nil { if err != nil {
return fmt.Errorf("load config: %w", err) log.Error("load config", slog.Any("error", err))
os.Exit(1)
} }
log := logger.New(
log = logger.New(
logger.WithLevel(cfg.SlogLevel()), logger.WithLevel(cfg.SlogLevel()),
logger.WithFormat(cfg.LoggerFormat()), logger.WithFormat(cfg.LoggerFormat()),
) )
shutdown, err = telemetry.Setup(serviceCtx, "messenger-relay", version)
if err != nil { shutdown, telemetryErr := telemetry.Setup(context.Background(), "messenger-relay", version)
return fmt.Errorf("setup telemetry: %w", err) if telemetryErr != nil {
log.Warn("telemetry setup failed; continuing without OTLP", slog.Any("error", telemetryErr))
shutdown = func(context.Context) error { return nil }
} }
log = telemetry.WrapLogger(log, "messenger-relay", cfg.SlogLevel()) log = telemetry.WrapLogger(log, "messenger-relay", cfg.SlogLevel())
slog.SetDefault(log) slog.SetDefault(log)
return run(
serviceCtx, if err := run(cfg, log); err != nil {
cfg, log.Error("shutdown with error", slog.Any("error", err))
log, shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
manager, _ = shutdown(shutdownCtx)
) cancel()
os.Exit(1)
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := shutdown(shutdownCtx); err != nil {
log.Warn("telemetry shutdown failed", slog.Any("error", err))
}
} }
type publisher struct { type publisher struct {
cfg broker.Config cfg broker.Config
mu sync.Mutex log *slog.Logger
conn *broker.Client mu sync.Mutex
isClosed bool conn *broker.Client
} }
func (p *publisher) client(ctx context.Context) (*broker.Client, error) { func (p *publisher) client() (*broker.Client, error) {
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()
if p.isClosed || ctx.Err() != nil {
return nil, context.Canceled
}
if p.conn != nil && p.conn.Connected() { if p.conn != nil && p.conn.Connected() {
return p.conn, nil return p.conn, nil
} }
if p.conn != nil { if p.conn != nil {
if err := p.conn.Close(); err != nil { _ = p.conn.Close()
return nil, fmt.Errorf("close disconnected broker: %w", err)
}
p.conn = nil p.conn = nil
} }
conn, err := broker.Dial(p.cfg) conn, err := broker.Dial(p.cfg)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if ctx.Err() != nil {
return nil, errors.Join(context.Canceled, conn.Close())
}
p.conn = conn p.conn = conn
return conn, nil return conn, nil
} }
@@ -115,23 +98,27 @@ func (p *publisher) PublishConfirmed(
routingKey string, routingKey string,
message domain.JobMessage, message domain.JobMessage,
) error { ) error {
conn, err := p.client(ctx) conn, err := p.client()
if err != nil { if err != nil {
return err return err
} }
if err := conn.PublishConfirmed(ctx, routingKey, message); err != nil { if err := conn.PublishConfirmed(ctx, routingKey, message); err != nil {
p.mu.Lock() p.mu.Lock()
if p.conn == conn { if p.conn == conn {
_ = p.conn.Close()
p.conn = nil p.conn = nil
} }
p.mu.Unlock() p.mu.Unlock()
return errors.Join(err, conn.Close())
return err
} }
return nil return nil
} }
func (p *publisher) Connect(ctx context.Context) error { func (p *publisher) Connect() error {
_, err := p.client(ctx) _, err := p.client()
return err return err
} }
@@ -140,165 +127,121 @@ func (p *publisher) Connected() bool {
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()
return !p.isClosed && p.conn != nil && p.conn.Connected() return p.conn != nil && p.conn.Connected()
} }
func (p *publisher) Close() error { func (p *publisher) Close() {
p.mu.Lock() p.mu.Lock()
p.isClosed = true defer p.mu.Unlock()
conn := p.conn
p.conn = nil if p.conn != nil {
p.mu.Unlock() _ = p.conn.Close()
if conn != nil { p.conn = nil
return conn.Close()
} }
return nil
} }
func brokerConfig(cfg config.Config) broker.Config { func brokerConfig(cfg config.Config) broker.Config {
return broker.Config{ return broker.Config{
URL: cfg.Broker.URL, URL: cfg.Broker.URL,
Exchange: cfg.Broker.Exchange, Exchange: cfg.Broker.Exchange,
DLX: cfg.Broker.DLX,
Queue: cfg.Broker.Queue, Queue: cfg.Broker.Queue,
DLQ: cfg.Broker.DLQ,
ConnectTimeout: cfg.Broker.ConnectTimeout, ConnectTimeout: cfg.Broker.ConnectTimeout,
ConfirmTimeout: cfg.Broker.ConfirmTimeout, ConfirmTimeout: cfg.Broker.ConfirmTimeout,
Heartbeat: cfg.Broker.Heartbeat, Heartbeat: cfg.Broker.Heartbeat,
Prefetch: cfg.Broker.Prefetch, Prefetch: cfg.Broker.Prefetch,
Role: "relay",
Producer: true,
} }
} }
func run( func run(cfg config.Config, log *slog.Logger) error {
ctx context.Context,
cfg config.Config,
log *slog.Logger,
manager *bao.Manager,
) (err error) {
if cfg.Broker.URL == "" { if cfg.Broker.URL == "" {
return errors.New("broker url is required for relay") return errors.New("BROKER_URL is required for relay")
} }
if err := requireLoopback(cfg.Relay.HealthAddr); err != nil {
return err ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
} defer stop()
store, err := postgres.New(
ctx, store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, postgres.WithQueryTracer(telemetry.NewPGXTracer()))
cfg.Postgres,
time.Duration(cfg.Idempotency.TTLSeconds)*time.Second,
postgres.WithQueryTracer(telemetry.NewPGXTracer()),
)
if err != nil { if err != nil {
return fmt.Errorf("connect database: %w", err) return fmt.Errorf("connect database: %w", err)
} }
defer func() { defer store.Close()
err = errors.Join(err, finish(ctx, manager, func(context.Context) error {
store.Close()
return nil
}))
}()
if err := telemetry.RegisterDBPool(store.PoolStats); err != nil { if err := telemetry.RegisterDBPool(store.PoolStats); err != nil {
log.WarnContext(ctx, "register db pool metrics", slog.Any("error", err)) log.Warn("register db pool metrics", slog.Any("error", err))
} }
if err := telemetry.RegisterProcessMetrics(); err != nil { if err := telemetry.RegisterProcessMetrics(); err != nil {
log.WarnContext(ctx, "register process metrics", slog.Any("error", err)) log.Warn("register process metrics", slog.Any("error", err))
} }
pub := &publisher{cfg: brokerConfig(cfg)} pub := &publisher{cfg: brokerConfig(cfg), log: log}
closeDone := make(chan error, 1) defer pub.Close()
stopClose := context.AfterFunc(ctx, func() { closeDone <- pub.Close() })
defer stopClose()
defer func() {
err = errors.Join(err, finish(ctx, manager, func(shutdownCtx context.Context) error {
select {
case closeErr := <-closeDone:
return closeErr
case <-shutdownCtx.Done():
return shutdownCtx.Err()
}
}))
}()
if err := pub.Connect(ctx); err != nil { if err := pub.Connect(); err != nil {
log.WarnContext(ctx, "broker is not reachable yet; relay will retry", slog.Any("error", err)) log.Warn("broker is not reachable yet; relay will retry", slog.Any("error", err))
} }
relay := outbox.New( relay := outbox.New(store.Pipeline(), pub, outbox.Config{
store.Pipeline(), Owner: "relay-" + cfg.Broker.Queue,
pub, PollInterval: cfg.Outbox.PollInterval,
outbox.Config{ ClaimTTL: cfg.Outbox.ClaimTTL,
Owner: "relay-" + cfg.Broker.Queue, Batch: cfg.Outbox.Batch,
PollInterval: cfg.Outbox.PollInterval, ReaperInterval: cfg.Outbox.ReaperInterval,
ClaimTTL: cfg.Outbox.ClaimTTL, ReconcileAfter: cfg.Outbox.ReconcileAfter,
Batch: cfg.Outbox.Batch, Retention: cfg.Outbox.Retention,
ReaperInterval: cfg.Outbox.ReaperInterval, }, log)
ReconcileAfter: cfg.Outbox.ReconcileAfter,
Retention: cfg.Outbox.Retention,
},
log,
)
if err := telemetry.RegisterRelayMetrics(store.Pipeline().OldestActiveJobAge, relay.Health, func(ctx context.Context) (int64, error) { if err := telemetry.RegisterRelayMetrics(store.Pipeline().OldestActiveJobAge, relay.Health, func(ctx context.Context) (int64, error) {
return store.Pipeline().CountOverdueJobs(ctx, 30*time.Second) return store.Pipeline().CountOverdueJobs(ctx, 30*time.Second)
}); err != nil { }); err != nil {
log.WarnContext(ctx, "register relay metrics", slog.Any("error", err)) log.Warn("register relay metrics", slog.Any("error", err))
} }
relayCtx, cancelRelay := context.WithCancel(ctx)
defer cancelRelay()
relayDone := make(chan struct{}) relayDone := make(chan struct{})
go func() { go func() {
defer close(relayDone) defer close(relayDone)
relay.Run(ctx)
relay.Run(relayCtx)
}() }()
server := healthServer(
ctx, server := healthServer(cfg.Relay.HealthAddr, store, pub, relay, log)
cfg.Relay.HealthAddr,
store, go func() {
pub, if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
relay, log.Error("health server failed", slog.Any("error", err))
) }
serverDone := make(chan error, 1)
go func() { serverDone <- server.ListenAndServe() }()
defer func() {
err = errors.Join(err, finish(ctx, manager, func(shutdownCtx context.Context) error {
serverErr := server.Shutdown(shutdownCtx)
if serverErr != nil {
serverErr = errors.Join(serverErr, server.Close())
}
select {
case <-relayDone:
return serverErr
case <-shutdownCtx.Done():
return errors.Join(serverErr, shutdownCtx.Err())
}
}))
}() }()
select {
case <-ctx.Done(): <-ctx.Done()
return nil cancelRelay()
case serverErr := <-serverDone: <-relayDone
return fmt.Errorf("health listener: %w", serverErr)
} shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return server.Shutdown(shutdownCtx)
} }
func healthServer( func healthServer(
serviceCtx context.Context,
addr string, addr string,
store *postgres.Store, store *postgres.Store,
pub *publisher, pub *publisher,
relay *outbox.Relay, relay *outbox.Relay,
_ *slog.Logger,
) *http.Server { ) *http.Server {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/health/live", func(w http.ResponseWriter, _ *http.Request) {
writeHealth(w, http.StatusOK, map[string]any{"status": "ok"}) writeHealth(w, http.StatusOK, map[string]any{"status": "ok"})
}) })
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
if serviceCtx.Err() != nil { ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
ctx, cancel := context.WithTimeout(serviceCtx, 3*time.Second)
defer cancel() defer cancel()
if err := store.Ping(ctx); err != nil { if err := store.Ping(ctx); err != nil {
@@ -308,8 +251,11 @@ func healthServer(
} }
if !pub.Connected() { if !pub.Connected() {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"}) if err := pub.Connect(); err != nil {
return writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
} }
oldest, err := relay.Health(ctx) oldest, err := relay.Health(ctx)
@@ -319,7 +265,7 @@ func healthServer(
return return
} }
if oldest > maxUnpublishedAge || serviceCtx.Err() != nil { if oldest > maxUnpublishedAge {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{ writeHealth(w, http.StatusServiceUnavailable, map[string]any{
"status": "unavailable", "status": "unavailable",
"outbox_oldest_seconds": int(oldest.Seconds()), "outbox_oldest_seconds": int(oldest.Seconds()),
@@ -338,9 +284,6 @@ func healthServer(
Addr: addr, Addr: addr,
Handler: mux, Handler: mux,
ReadHeaderTimeout: 5 * time.Second, ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
BaseContext: func(net.Listener) context.Context { return serviceCtx },
} }
} }
@@ -349,29 +292,3 @@ func writeHealth(w http.ResponseWriter, status int, body map[string]any) {
w.WriteHeader(status) w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body) _ = json.NewEncoder(w).Encode(body)
} }
func requireLoopback(addr string) error {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("health listener address: %w", err)
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
return errors.New("health listener must bind a loopback ip")
}
return nil
}
func finish(parent context.Context, manager *bao.Manager, cleanup func(context.Context) error) error {
manager.Stop()
ctx, cancel := manager.ShutdownContext(parent)
defer cancel()
done := make(chan error, 1)
go func() { done <- cleanup(ctx) }()
select {
case err := <-done:
return err
case <-ctx.Done():
return fmt.Errorf("shutdown deadline: %w", ctx.Err())
}
}
+109 -83
View File
@@ -1,38 +1,35 @@
// Command s3init idempotently creates the private attachment bucket using // Command s3init bootstraps the private attachment bucket. It is idempotent:
// operator-only file credentials over the shared TLS trust boundary. // it runs before the API on every compose up, verifies the bucket and the
// application identity, and exits successfully when everything is in place.
package main package main
import ( import (
"bytes"
"context" "context"
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"net"
"net/http"
"net/url"
"os" "os"
"os/signal"
"strings" "strings"
"syscall"
"time" "time"
"github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go" "github.com/aws/smithy-go"
"github.com/google/uuid"
"mtusi-messenger/internal/platform/secretfile"
"mtusi-messenger/internal/platform/tlsconfig"
) )
const bootstrapTimeout = 120 * time.Second const bootstrapTimeout = 120 * time.Second
type settings struct { type settings struct {
Endpoint string Endpoint string
Region string Region string
Bucket string Bucket string
AccessKey string AdminAccessKey string
SecretKey string AdminSecretKey string
AppAccessKey string
AppSecretKey string
} }
func main() { func main() {
@@ -50,16 +47,21 @@ func run(log *slog.Logger) error {
return err return err
} }
signalCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) ctx, cancel := context.WithTimeout(context.Background(), bootstrapTimeout)
defer stop()
ctx, cancel := context.WithTimeout(signalCtx, bootstrapTimeout)
defer cancel() defer cancel()
client, transport, err := newClient(cfg)
if err != nil { admin := newClient(cfg, cfg.AdminAccessKey, cfg.AdminSecretKey)
app := newClient(cfg, cfg.AppAccessKey, cfg.AppSecretKey)
if err := waitForBucket(ctx, admin, cfg.Bucket); err != nil {
return err return err
} }
defer transport.CloseIdleConnections()
if err := waitForBucket(ctx, client, cfg.Bucket); err != nil { if err := probeAppIdentity(ctx, app, cfg.Bucket); err != nil {
return err
}
if err := probeForbiddenPrefix(ctx, app, cfg.Bucket); err != nil {
return err return err
} }
@@ -73,60 +75,38 @@ func run(log *slog.Logger) error {
func loadSettings() (settings, error) { func loadSettings() (settings, error) {
cfg := settings{ cfg := settings{
Endpoint: strings.TrimSpace(os.Getenv("S3_ENDPOINT")), Endpoint: strings.TrimSpace(os.Getenv("S3_ENDPOINT")),
Region: strings.TrimSpace(os.Getenv("S3_REGION")), Region: strings.TrimSpace(os.Getenv("S3_REGION")),
Bucket: strings.TrimSpace(os.Getenv("S3_BUCKET")), Bucket: strings.TrimSpace(os.Getenv("S3_BUCKET")),
AdminAccessKey: strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY")),
AdminSecretKey: strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_ACCESS_KEY")),
AppAccessKey: strings.TrimSpace(os.Getenv("S3_ACCESS_KEY_ID")),
AppSecretKey: strings.TrimSpace(os.Getenv("S3_SECRET_ACCESS_KEY")),
} }
endpoint, err := url.Parse(cfg.Endpoint)
if err != nil || endpoint.Scheme != "https" || endpoint.Hostname() == "" || endpoint.User != nil { switch {
return settings{}, errors.New("s3 endpoint must be an https url without credentials") case cfg.Endpoint == "":
} return settings{}, errors.New("S3_ENDPOINT is required")
if endpoint.RawQuery != "" || endpoint.Fragment != "" { case cfg.Region == "":
return settings{}, errors.New("s3 endpoint must not contain a query or fragment") return settings{}, errors.New("S3_REGION is required")
} case cfg.Bucket == "":
if cfg.Region == "" || cfg.Bucket == "" { return settings{}, errors.New("S3_BUCKET is required")
return settings{}, errors.New("s3 region and bucket are required") case cfg.AdminAccessKey == "" || cfg.AdminSecretKey == "":
} return settings{}, errors.New("S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_ACCESS_KEY are required")
cfg.AccessKey, err = operatorSecret("S3_ACCESS_KEY_ID_FILE") case cfg.AppAccessKey == "" || cfg.AppSecretKey == "":
if err != nil { return settings{}, errors.New("S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are required")
return settings{}, err
}
cfg.SecretKey, err = operatorSecret("S3_SECRET_ACCESS_KEY_FILE")
if err != nil {
return settings{}, err
} }
return cfg, nil return cfg, nil
} }
func newClient(cfg settings) (*s3.Client, *http.Transport, error) { func newClient(cfg settings, accessKey, secretKey string) *s3.Client {
clientTLS, err := tlsconfig.NewClientFromEnv("") return s3.New(s3.Options{
if err != nil {
return nil, nil, fmt.Errorf("configure object store tls: %w", err)
}
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSClientConfig: clientTLS,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
IdleConnTimeout: 30 * time.Second,
}
client := s3.New(s3.Options{
Region: cfg.Region, Region: cfg.Region,
BaseEndpoint: aws.String(cfg.Endpoint), BaseEndpoint: aws.String(cfg.Endpoint),
UsePathStyle: true, UsePathStyle: true,
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""), Credentials: credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""),
HTTPClient: &http.Client{
Transport: transport,
Timeout: 15 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return errors.New("object store redirects are not permitted")
},
},
}) })
return client, transport, nil
} }
func waitForBucket(ctx context.Context, client *s3.Client, bucket string) error { func waitForBucket(ctx context.Context, client *s3.Client, bucket string) error {
@@ -156,6 +136,68 @@ func waitForBucket(ctx context.Context, client *s3.Client, bucket string) error
} }
} }
func probeAppIdentity(ctx context.Context, client *s3.Client, bucket string) error {
key := "staging/.bootstrap/" + uuid.NewString()
if _, err := client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: bytes.NewReader([]byte("ok")),
ContentLength: aws.Int64(2),
ContentType: aws.String("text/plain"),
}); err != nil {
return fmt.Errorf("application identity cannot write: %w", err)
}
defer func() {
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
})
}()
if _, err := client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}); err != nil {
return fmt.Errorf("application identity cannot read: %w", err)
}
if _, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
Prefix: aws.String("staging/"),
}); err != nil {
return fmt.Errorf("application identity cannot list: %w", err)
}
return nil
}
func probeForbiddenPrefix(ctx context.Context, client *s3.Client, bucket string) error {
key := "forbidden/" + uuid.NewString()
_, err := client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: bytes.NewReader([]byte("must not be stored")),
})
if err == nil {
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
})
return errors.New("application identity can write outside the allowed prefixes; check infra/s3/s3.json")
}
var apiErr smithy.APIError
if !errors.As(err, &apiErr) || apiErr.ErrorCode() != "AccessDenied" {
return fmt.Errorf("forbidden-prefix probe returned an unexpected error: %w", err)
}
return nil
}
func isNotFound(err error) bool { func isNotFound(err error) bool {
var apiErr smithy.APIError var apiErr smithy.APIError
if errors.As(err, &apiErr) { if errors.As(err, &apiErr) {
@@ -179,19 +221,3 @@ func isBucketExists(err error) bool {
return false return false
} }
func operatorSecret(env string) (string, error) {
path := strings.TrimSpace(os.Getenv(env))
if path == "" {
return "", fmt.Errorf("%s is required", env)
}
value, err := secretfile.Read(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", env, err)
}
secret := strings.TrimSpace(string(value))
if secret == "" {
return "", fmt.Errorf("%s is empty", env)
}
return secret, nil
}
+87 -190
View File
@@ -6,7 +6,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"net"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
@@ -17,9 +16,7 @@ import (
"mtusi-messenger/internal/broker" "mtusi-messenger/internal/broker"
"mtusi-messenger/internal/config" "mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
"mtusi-messenger/internal/platform/bao"
"mtusi-messenger/internal/platform/objectstore" "mtusi-messenger/internal/platform/objectstore"
"mtusi-messenger/internal/service/attachment"
"mtusi-messenger/internal/storage/postgres" "mtusi-messenger/internal/storage/postgres"
"mtusi-messenger/internal/telemetry" "mtusi-messenger/internal/telemetry"
"mtusi-messenger/internal/worker" "mtusi-messenger/internal/worker"
@@ -28,87 +25,61 @@ import (
var version = "dev" var version = "dev"
func main() { func main() {
if err := execute(); err != nil { log := logger.New()
logger.New().Error("worker stopped with error", slog.Any("error", err))
os.Exit(1)
}
}
func execute() (err error) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
serviceCtx, manager, err := bao.Start(ctx, "worker")
if err != nil {
return fmt.Errorf("start secret manager: %w", err)
}
var shutdown func(context.Context) error
defer func() {
manager.Stop()
shutdownCtx, cancel := manager.ShutdownContext(serviceCtx)
defer cancel()
if shutdown != nil {
err = errors.Join(err, shutdown(shutdownCtx))
}
err = errors.Join(err, manager.Close(serviceCtx))
if errors.Is(context.Cause(serviceCtx), bao.ErrExpired) {
err = errors.Join(err, bao.ErrExpired)
}
}()
cfg, err := config.Load() cfg, err := config.Load()
if err != nil { if err != nil {
return fmt.Errorf("load config: %w", err) log.Error("load config", slog.Any("error", err))
os.Exit(1)
} }
log := logger.New(
log = logger.New(
logger.WithLevel(cfg.SlogLevel()), logger.WithLevel(cfg.SlogLevel()),
logger.WithFormat(cfg.LoggerFormat()), logger.WithFormat(cfg.LoggerFormat()),
) )
shutdown, err = telemetry.Setup(serviceCtx, "messenger-worker", version)
if err != nil { shutdown, telemetryErr := telemetry.Setup(context.Background(), "messenger-worker", version)
return fmt.Errorf("setup telemetry: %w", err) if telemetryErr != nil {
log.Warn("telemetry setup failed; continuing without OTLP", slog.Any("error", telemetryErr))
shutdown = func(context.Context) error { return nil }
} }
log = telemetry.WrapLogger(log, "messenger-worker", cfg.SlogLevel()) log = telemetry.WrapLogger(log, "messenger-worker", cfg.SlogLevel())
slog.SetDefault(log) slog.SetDefault(log)
return run(
serviceCtx, if err := run(cfg, log); err != nil {
cfg, log.Error("shutdown with error", slog.Any("error", err))
log, shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
manager, _ = shutdown(shutdownCtx)
) cancel()
os.Exit(1)
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := shutdown(shutdownCtx); err != nil {
log.Warn("telemetry shutdown failed", slog.Any("error", err))
}
} }
func run( func run(cfg config.Config, log *slog.Logger) error {
ctx context.Context,
cfg config.Config,
log *slog.Logger,
manager *bao.Manager,
) (err error) {
if cfg.Broker.URL == "" { if cfg.Broker.URL == "" {
return errors.New("broker url is required for worker") return errors.New("BROKER_URL is required for worker")
} }
if err := requireLoopback(cfg.Worker.HealthAddr); err != nil {
return err ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
} defer stop()
store, err := postgres.New(
ctx, store, err := postgres.New(ctx, cfg.Postgres, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, postgres.WithQueryTracer(telemetry.NewPGXTracer()))
cfg.Postgres,
time.Duration(cfg.Idempotency.TTLSeconds)*time.Second,
postgres.WithQueryTracer(telemetry.NewPGXTracer()),
)
if err != nil { if err != nil {
return fmt.Errorf("connect database: %w", err) return fmt.Errorf("connect database: %w", err)
} }
defer func() { defer store.Close()
err = errors.Join(err, finish(ctx, manager, func(context.Context) error {
store.Close()
return nil
}))
}()
if err := telemetry.RegisterDBPool(store.PoolStats); err != nil { if err := telemetry.RegisterDBPool(store.PoolStats); err != nil {
log.WarnContext(ctx, "register db pool metrics", slog.Any("error", err)) log.Warn("register db pool metrics", slog.Any("error", err))
} }
if err := telemetry.RegisterProcessMetrics(); err != nil { if err := telemetry.RegisterProcessMetrics(); err != nil {
log.WarnContext(ctx, "register process metrics", slog.Any("error", err)) log.Warn("register process metrics", slog.Any("error", err))
} }
objectStoreConcrete, err := objectstore.New(objectstore.Config{ objectStoreConcrete, err := objectstore.New(objectstore.Config{
@@ -124,88 +95,59 @@ func run(
if err != nil { if err != nil {
return fmt.Errorf("connect object store: %w", err) return fmt.Errorf("connect object store: %w", err)
} }
defer objectStoreConcrete.Close()
objectStore := telemetry.WrapStore(objectStoreConcrete) objectStore := telemetry.WrapStore(objectStoreConcrete)
workerInstance := worker.New( workerInstance := worker.New(store.Pipeline(), objectStore, worker.Config{
store.Pipeline(), Concurrency: cfg.Worker.Concurrency,
objectStore, LeaseTTL: cfg.Processing.LeaseTTL,
worker.Config{ Heartbeat: cfg.Processing.Heartbeat,
Concurrency: cfg.Worker.Concurrency, JobTimeout: cfg.Processing.JobTimeout,
LeaseTTL: cfg.Processing.LeaseTTL, RetryBase: cfg.Processing.RetryBase,
Heartbeat: cfg.Processing.Heartbeat, RetryCap: cfg.Processing.RetryCap,
JobTimeout: cfg.Processing.JobTimeout, MaxUploadBytes: cfg.S3.MaxUploadBytes,
RetryBase: cfg.Processing.RetryBase, MaxImagePixels: cfg.S3.MaxImagePixels,
RetryCap: cfg.Processing.RetryCap, }, log)
MaxUploadBytes: cfg.S3.MaxUploadBytes,
MaxImagePixels: cfg.S3.MaxImagePixels,
},
log,
)
if err := telemetry.RegisterWorkerMetrics(workerInstance.Busy, int64(cfg.Worker.Concurrency)); err != nil { if err := telemetry.RegisterWorkerMetrics(workerInstance.Busy, int64(cfg.Worker.Concurrency)); err != nil {
log.WarnContext(ctx, "register worker metrics", slog.Any("error", err)) log.Warn("register worker metrics", slog.Any("error", err))
} }
sweeper := attachment.NewSweeper( server := healthServer(cfg.Worker.HealthAddr, store, objectStore, workerInstance)
store.Pipeline(),
objectStore, var serverWait sync.WaitGroup
store, serverWait.Add(1)
cfg.S3.SweepGrace,
cfg.Staging.OrphanGrace,
cfg.Staging.FailedRetention,
cfg.S3.SweepInterval,
log,
)
sweepDone := make(chan struct{})
go func() { go func() {
defer close(sweepDone) defer serverWait.Done()
sweeper.Run(ctx)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error("health server failed", slog.Any("error", err))
}
}() }()
consumerDone := make(chan error, 1)
runCtx, cancelRun := context.WithCancel(ctx)
defer cancelRun()
consumerDone := make(chan struct{})
go func() { go func() {
consumerDone <- consumeWithReconnect( defer close(consumerDone)
ctx,
cfg, consumeWithReconnect(runCtx, cfg, workerInstance, log)
workerInstance,
log,
)
}() }()
server := healthServer(
ctx, <-ctx.Done()
cfg.Worker.HealthAddr, cancelRun()
store, <-consumerDone
objectStore,
workerInstance, shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Worker.ShutdownTimeout)
) defer cancel()
serverDone := make(chan error, 1)
go func() { serverDone <- server.ListenAndServe() }() _ = server.Shutdown(shutdownCtx)
defer func() { serverWait.Wait()
err = errors.Join(err, finish(ctx, manager, func(shutdownCtx context.Context) error {
serverErr := server.Shutdown(shutdownCtx) return nil
if serverErr != nil {
serverErr = errors.Join(serverErr, server.Close())
}
select {
case <-sweepDone:
case <-shutdownCtx.Done():
return errors.Join(serverErr, shutdownCtx.Err())
}
select {
case consumerErr := <-consumerDone:
return errors.Join(serverErr, consumerErr)
case <-shutdownCtx.Done():
return errors.Join(serverErr, shutdownCtx.Err())
}
}))
}()
select {
case <-ctx.Done():
return nil
case serverErr := <-serverDone:
return fmt.Errorf("health listener: %w", serverErr)
}
} }
func consumeWithReconnect( func consumeWithReconnect(
@@ -213,34 +155,24 @@ func consumeWithReconnect(
cfg config.Config, cfg config.Config,
workerInstance *worker.Worker, workerInstance *worker.Worker,
log *slog.Logger, log *slog.Logger,
) error { ) {
for ctx.Err() == nil { for ctx.Err() == nil {
client, err := broker.Dial(brokerConfig(cfg)) client, err := broker.Dial(brokerConfig(cfg))
if err != nil { if err != nil {
log.WarnContext(ctx, "broker dial failed, retrying", slog.Any("error", err)) log.WarnContext(ctx, "broker dial failed, retrying", slog.Any("error", err))
if !sleepCtx(ctx, 2*time.Second) { if !sleepCtx(ctx, 2*time.Second) {
return nil return
} }
continue continue
} }
var closeOnce sync.Once
var closeErr error
closeClient := func() {
closeOnce.Do(func() { closeErr = client.Close() })
}
stopClose := context.AfterFunc(ctx, closeClient)
err = workerInstance.Run(ctx, client) err = workerInstance.Run(ctx, client)
stopClose() _ = client.Close()
closeClient()
if closeErr != nil && ctx.Err() == nil {
log.WarnContext(ctx, "close broker failed", slog.Any("error", closeErr))
}
if ctx.Err() != nil { if ctx.Err() != nil {
return closeErr return
} }
if err != nil { if err != nil {
@@ -248,10 +180,9 @@ func consumeWithReconnect(
} }
if !sleepCtx(ctx, 2*time.Second) { if !sleepCtx(ctx, 2*time.Second) {
return nil return
} }
} }
return nil
} }
func sleepCtx(ctx context.Context, d time.Duration) bool { func sleepCtx(ctx context.Context, d time.Duration) bool {
@@ -270,18 +201,17 @@ func brokerConfig(cfg config.Config) broker.Config {
return broker.Config{ return broker.Config{
URL: cfg.Broker.URL, URL: cfg.Broker.URL,
Exchange: cfg.Broker.Exchange, Exchange: cfg.Broker.Exchange,
DLX: cfg.Broker.DLX,
Queue: cfg.Broker.Queue, Queue: cfg.Broker.Queue,
DLQ: cfg.Broker.DLQ,
ConnectTimeout: cfg.Broker.ConnectTimeout, ConnectTimeout: cfg.Broker.ConnectTimeout,
ConfirmTimeout: cfg.Broker.ConfirmTimeout, ConfirmTimeout: cfg.Broker.ConfirmTimeout,
Heartbeat: cfg.Broker.Heartbeat, Heartbeat: cfg.Broker.Heartbeat,
Prefetch: cfg.Worker.Prefetch, Prefetch: cfg.Worker.Prefetch,
Role: "worker",
Producer: false,
} }
} }
func healthServer( func healthServer(
serviceCtx context.Context,
addr string, addr string,
store *postgres.Store, store *postgres.Store,
objectStore objectstore.Store, objectStore objectstore.Store,
@@ -289,16 +219,12 @@ func healthServer(
) *http.Server { ) *http.Server {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/health/live", func(w http.ResponseWriter, _ *http.Request) {
writeHealth(w, http.StatusOK, map[string]any{"status": "ok"}) writeHealth(w, http.StatusOK, map[string]any{"status": "ok"})
}) })
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
if serviceCtx.Err() != nil { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return
}
ctx, cancel := context.WithTimeout(serviceCtx, 5*time.Second)
defer cancel() defer cancel()
if err := store.Ping(ctx); err != nil { if err := store.Ping(ctx); err != nil {
@@ -314,7 +240,7 @@ func healthServer(
} }
running, connected := workerInstance.Ready() running, connected := workerInstance.Ready()
if !running || !connected || serviceCtx.Err() != nil { if !running || !connected {
writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"}) writeHealth(w, http.StatusServiceUnavailable, map[string]any{"status": "unavailable"})
return return
@@ -327,9 +253,6 @@ func healthServer(
Addr: addr, Addr: addr,
Handler: mux, Handler: mux,
ReadHeaderTimeout: 5 * time.Second, ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 6 * time.Second,
BaseContext: func(net.Listener) context.Context { return serviceCtx },
} }
} }
@@ -338,29 +261,3 @@ func writeHealth(w http.ResponseWriter, status int, body map[string]any) {
w.WriteHeader(status) w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body) _ = json.NewEncoder(w).Encode(body)
} }
func requireLoopback(addr string) error {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("health listener address: %w", err)
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
return errors.New("health listener must bind a loopback ip")
}
return nil
}
func finish(parent context.Context, manager *bao.Manager, cleanup func(context.Context) error) error {
manager.Stop()
ctx, cancel := manager.ShutdownContext(parent)
defer cancel()
done := make(chan error, 1)
go func() { done <- cleanup(ctx) }()
select {
case err := <-done:
return err
case <-ctx.Done():
return fmt.Errorf("shutdown deadline: %w", ctx.Err())
}
}
+473 -709
View File
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -17,9 +17,10 @@ postgres:
host: localhost host: localhost
port: 5432 port: 5432
database: messenger database: messenger
user: "" user: messenger
password: "" # Dev default for a local run without environment overrides; POSTGRES_PASSWORD wins.
ssl_mode: verify-full password: messenger
ssl_mode: disable
max_conns: 10 max_conns: 10
min_conns: 1 min_conns: 1
max_conn_lifetime: 1h max_conn_lifetime: 1h
+28 -90
View File
@@ -1,99 +1,37 @@
# Матрица доверия — реализованный стенд lab7 # Матрица доверия — заполнить в решении lab7
## Identities, CA и leases Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
Все TLS endpoints проверяются по CA и DNS SAN; TLS ≥1.2. Offline root находится | Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
у оператора вне checkout, OpenBao выдаёт EC P-256 leaf через внутренний intermediate. | --- | --- | --- | --- |
URI service identity — `spiffe://mtusi/<role>`; DNS SANs задаёт | Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
`scripts/lab7_environment.py:ROLES`. Доверенный CA сам по себе не является ACL. | 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 |
Default leaf TTL — 1h, максимум PKI role — 1h; host-side `make renewer` Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
выпускает новые leaf каждые 30 минут и синхронизирует CRL; исследовательский renewal/expiry
использует 20s. Cert-auth tokens: 60s, max/explicit max300s. KV freshness у Go
приложения — 60s, независимо от срока leaf и token; admission закрывается за1s
до ближайшего deadline (наблюдаемое закрытие при sealed Bao: 60.5–61.7s с учётом
1s cadence watchdog). Backend KV passwords/SigV4 keys статические и живут до
явной ротации — это не динамические60s credentials. Session TTL3600s;
server хранит только SHA-256 token hash.
| Связь | Endpoint / протокол | Проверка identity и права | Lease / reload | Положительная и отрицательная проверка | ## Обязательные отрицательные проверки
| --- | --- | --- | --- | --- |
| Клиент → ingress/LB | `https://localhost:8443`, TLS, Bearer | DNS SANlocalhost; без clientcert. LB заменяет forwarding headers и удаляет X-User-Id | LB leaf; пользовательская session3600s/logout/expiry | `make test test-security`; `public_ca_hostname`, `http_acl_logout_expiry_bounds`, `shared_rate_limit` |
| LB → все API-реплики | `api-replica:8080`, native mTLS | LB проверяет SANapi-replica/CA/CRL; Go server требует точный URI`spiffe://mtusi/lb` | Atomic leaf/CRL reload Go; trust changes restart; tickets/cache off | `mtls_and_telemetry_acl`: lb200; absent/wrongCA/wrongURI TLS拒绝; `make test-pki` oldLB revoke/retire |
| API/worker/relay → PostgreSQL | `postgres:5432`, native TLS+SCRAM, verify-full | Раздельные messenger_api/worker/relay roles; no superuser/DDL. Worker/relay не читают users/sessions/messages | Статический password в ownKV; connection lifetime30s; credentials change → bounded restart | `database_privileges`: SQLSTATE42501; `make integration-test` actual nativeTLS DB suites |
| API/worker → S3 | `https://seaweedfs:8333`, native TLS+SigV4 | API stagingRead/Write, finalRead; worker managed-prefixRead/Write+bucketList; foreign GET/PUT/DELETE/COPY/bucket 403, worker bucket-level LIST returns managed metadata (documented limitation) | Static keys until explicitrotation; role-specific ownKV. No claim of required clientcert on S3HTTP | `s3_prefix_acl`: GET/PUT/DELETE/COPY+fullreadback; `make test-presign test-queue`; workerkeyrotation inPKIstudy |
| Relay/API outbox/worker → broker | `broker:5671`, native mTLS/EXTERNAL-only | API commits DBoutbox, relay publishes onlyattachments.jobs; worker consumes onlyattachment.process.v1. First DNS SAN principal, anchored broker ACL | Leaf+broker user permissions; nativeprincipal revoke distinct from serial CRL | `broker_external_acl`: positive relaypublish/workerconsume; opposite/topology/wrongDNS403, no-cert/wrongCA TLS rejection |
| API/worker/relay → Collector | `otel-collector:4318`, mTLS gateway → loopback14318 | Exact CNapi/worker/relay and POST/v1/{traces,metrics,logs}; unknownCN/verb/path denied | Gateway loads CA/CRL atstartup; revoke/rollover restarts gateways; app pools are not claimed drained | `mtls_and_telemetry_acl`: api200, lb403, missing/wrongCA rejection; full `make test-observability` |
| Collector → telemetry backends | Loki`https://loki:3100`; TempoGRPCS`tempo:4437` | CollectorCN onlylogpush/OTLP; no dataquery. Native hops127.0.0.1:13100/14317 | Distinct collectorleaf; fixedsingletenantfake | `mtls_and_telemetry_acl` collectorquery403; actual traces/logs in `make test-observability` |
| Grafana → data sources | Prometheus9090/Loki3100/Tempo3200, HTTPS/mTLS | GrafanaCN query allowlist; push/delete/admin/reload forbidden; CA+hostname verified | Ownleaf in secureJsonData rendered outsideGit; rotation rerenders/restarts | `mtls_and_telemetry_acl` forbiddenwrite403; Grafana/dataSources/TraceQL correlation intelemetrygate |
| API/worker/relay → OpenBao | `https://openbao:8200`, verifiedTLS+cert-auth | Authrole checks CN+URI; ownsecret/data/<role> and ownpki/issue/<role> only; no root/defaultpolicy | Token60s/max300s; cert reauth; KVfresh60s; independentleafdeadline | `bao_api_policy`: ownKV200, foreignKV/issuer/policyadmin403; `make test-pki` renewal/expiry/recovery |
| Оператор → OpenBao/Grafana/S3 admin | LoopbackHTTPS8200/3000/8333 | Separate operatorcertificate+scopedBaopolicy; Grafana localpassword; SigV4S3operator. No anonymousadmin | Root token revoked afterbootstrap; unseal2-of-3 hoststate; operatorleafrotation | `securityctl.py up`, `audit-summary`, S3readinessfullbytes; noappoperatorcredentialmounts inisolation |
| API → Redis | `redis:6379`, nativeTLS+ACLpassword | `cache` user: chat_list:* / lock:chat_list:* onlyGET/SET/DEL/PING/EVAL/scripts; default useroff | StaticownKVpassword; RedisAOF persists; no requiredclientcert claimed | `redis_tls_cache_acl`: PONG/allowedcache, foreignkeyNOPERM; nativeTLS integrationDB7 |
| Replication/cluster channels | ExternalreplicationN/A: allstatefulstores single-node | BaoRaftcluster127.0.0.1:8201nativeTLS; S3master/filer/volume oneclosednamespace, internalgRPCmTLSCNs3; telemetrygossiploopback | NoHAclaim forDB/S3/broker/Bao/host | `runtime_container_network_isolation`; `seaweed_auxiliary_mtls`; actualpersistence/bothAPIreplicafailures |
## Служебные, scrape и health каналы 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. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
| Канал | Boundary / identity | Проверка | ## Bootstrap и эксплуатация
| --- | --- | --- |
| Local API/worker/relay health8084/8081/8082 | Namespace loopback, no business API; no hostpublication | Из соседнего defaultnamespaceconnection_refused; Gohealthcloses admission onauthorizationexpiry |
| HAProxy stats8404 | mTLS, CNoperator/prometheus; monitoronly/metrics | Separate healthbackend excluded fromAPI SLI; Prometheus scrape overTLS |
| Collector metrics8888/8889, health13134 | mTLS/CNprometheus oroperator; localhops18888/18889/13133 | Privateportprobes, fulltelemetryscrapes |
| Prometheus/Loki/Tempo selfmetrics | HTTPS/mTLS/CNprometheus GETmetrics/ready only | Wrongqueryrole403; native19090/13100/13200 andgRPC/gossip notnetwork-accessible |
| RabbitMQ management15671, scrape15693 | mTLS HAProxy → loopback15672/15692; operatoradmin Basic onlymanagement, Prometheus onlyscrape | NoAMQP5672 orplaintextmanagement published; brokerACL/scapedata |
| S3 auxiliary18333 | Native mTLS, onlyCNs3; HTTP2 ALPNh2 | api/worker/operator/no-cert denied, s3TLSchannelaccepted; not anadminmethodproof |
| S3 master/filer/volume | HTTP9333/8888/8080 andgRPC19333/18888/18080 onnamespace loopback; gRPC additionallyCNs3 | Neighbor namespaceconnection_refused; Iceberg8181/Lance9101 disabled, not excluded |
| Migrations/S3-init/volume-init | Explicitoperatorjobs; no rootCA/unseal mount | Migrate DBoperator only; S3init operator only; volume-init has no network/socket, CHOWN/DAC_OVERRIDE only |
Native plaintext hops exist **only within the shared Linux network namespace** В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
of a backend+its TLS gateway, or S3co-located internal HTTP components. A helper
compares actual `/proc/self/ns/net`, not just containerIDs. None of these listeners
is a published bypass; only TLS owner joins routable networks. `default` is used
by apps, `observability` by telemetry, `edge` by their TLS owners.
## Bootstrap, current-version и отзыв 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 — хорошее расширение, но не обязательное название технологии.
1. `cp .env.example .env; make up`: offlinekeys/backendcredentials/complete role Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
versions are generated locally; init/unseal/provision/migrations follow.
2. RootCA/privateoperator/unseal state is in `~/.local/share/mtusi-lab7/<project>`
with0700/0600. Only public CA/intermediate/CRLs and each role's own leaf/key
enter role mounts. Operator recovery material never enters app/images/Git.
3. Native consumers use `current` alias. Every Go snapshot reads one bounded
regular `current-version` selector and immutable `versions/<name>`; cert/key/CA/CRL
cannot be mixed across a swap. Selector is owner/group-readable before atomic
publication. No last-known-invalid fallback, arbitrary path or symlink retry.
4. `make pki-renew ROLE=api CERT_TTL=1h` and `renew-watch` use owncert-auth. Token
renewal cannot renew theleaf. Missing/expired/revoked material fails closed.
5. `securityctl.py revoke ROLE --serial SERIAL`: publishes issuer-signed CRLs,
updates BaoauthCRLs, then restarts native CRL-consuming HAProxy gateways.
Existing application TLS/DB/S3/broker pools are not claimed to be drained;
only fresh/resumption attempts are measured.
Go verifies currentCRLs onfreshconnections. Principalcompromise also requires
backendcredential/token/authrole disable; RabbitMQ EXTERNAL user/connection
revocation is separate and not falsely represented by CRLfileupdate.
6. Offline rootCRLs are regenerated before their final24h and onoperator sync;
nativegateways are reconciled on `up`. StaleCRL verification is never disabled.
7. CArollover uses prepare(overlapCA/CRLs+authtrust) → issue(newintermediate/leaves)
→ retire(oldCA/issuer/authCRLs). Retire re-publishes every running role identity
with a new-only trust bundle (the leaf is unchanged), so an old certificate is
rejected by trust, not by a missing CRL; a process whose mounted trust differs
from its startup roots fails closed (`restart required`). Prepare/retire reload
api/worker/relay one replica at a time; issue only reloads native owners and
Go re-reads the new leaf on fresh handshakes. Readiness closes on root removal
so LB retires a not-yet-restarted replica instead of routing into TLS failures.
Study checks oldtrustedleaf during overlap, fresh/resumption attempts after
retirement, newpipeline/Redis/Bao/telemetry paths and retained message/filebytes;
each phase waits for the full
public upload pipeline before asserting contract details.
## Обязательные отрицательные наборы
- CA/hostname errors are checked as verification errors, not TCPtimeouts.
- API/broker/Collector: allowedidentitypositive, absentcert, foreignCA andsameCA
forbiddenrole negatives. HTTP403 aftertrustedmTLS is distinguished from TLSdenial.
- Foreignchat/attachment access, forgedX-User-Id, logout/DBexpiry, uploadbounds,
shared429/Retry-After, nativeDB/S3/broker/Baopolicy allow/deny are runtime-tested.
- Leaf/CArevocation checks freshconnections and explicit resumptionattempts;
tickets/cacheoff means no claim of a positively resumedsession.
- `evidence/lab7/security.json`, `verification.json`, `restart-scope.json`,
`failover-scope.json`, `sequential-failover.json` andPKIstudy contain sanitized
observations; [scantriage](../security/SCAN_TRIAGE.md) names residualrisk.
+278 -7
View File
@@ -1,12 +1,283 @@
# Secure local/operator integration ports; never a published API bypass. name: mtusi-messenger-lab6
include:
- path: compose.yaml # Built once by the api service; migrate and s3-init consume the same image.
x-app: &app
image: mtusi-messenger:lab6
services: services:
postgres: postgres:
networks: [default, edge] image: postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_DB: ${POSTGRES_DB:-messenger}
ports: ports:
- "127.0.0.1:${TEST_POSTGRES_PORT:-15432}:5432" - "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres18-data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10
start_period: 5s
restart: unless-stopped
redis: redis:
networks: [default, edge] image: redis:7.4-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499
command:
- redis-server
- --appendonly
- "yes"
- --appendfsync
- everysec
- --save
- "60"
- "1"
ports: ports:
- "127.0.0.1:${TEST_REDIS_PORT:-16379}:6379" - "127.0.0.1:${REDIS_PORT:-6379}:6379"
volumes:
- redis7-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
start_period: 3s
restart: unless-stopped
seaweedfs:
image: chrislusf/seaweedfs:3.80@sha256:1055999e08eed1789b0ae45d235126e4495e23d3fb9d6396293fd42539b1ae6a
command:
- server
- -s3
- -s3.config=/etc/seaweedfs/s3.json
- -dir=/data
- -master.volumeSizeLimitMB=64
volumes:
- ./infra/s3/s3.json:/etc/seaweedfs/s3.json:ro
- seaweedfs-data:/data
ports:
- "127.0.0.1:${S3_PORT:-8333}:8333"
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8333/healthz || exit 1"]
interval: 5s
timeout: 3s
retries: 20
start_period: 60s
restart: unless-stopped
broker:
image: rabbitmq:4.3.7-management-alpine@sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528
hostname: broker
environment:
RABBITMQ_DEFAULT_USER: ${BROKER_USER:-messenger}
RABBITMQ_DEFAULT_PASS: ${BROKER_PASSWORD:-messenger}
RABBITMQ_DEFAULT_VHOST: ${BROKER_VHOST:-messenger}
volumes:
- rabbitmq-data:/var/lib/rabbitmq
ports:
- "127.0.0.1:${BROKER_MANAGEMENT_PORT:-15672}:15672"
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 10s
timeout: 5s
retries: 12
start_period: 30s
restart: unless-stopped
s3-init:
<<: *app
entrypoint: ["/usr/local/bin/s3init"]
environment:
S3_ENDPOINT: http://seaweedfs:8333
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY:-lab4admin}
S3_ADMIN_SECRET_ACCESS_KEY: ${S3_ADMIN_SECRET_ACCESS_KEY:-lab4admin-secret}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-lab4app}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-lab4app-secret}
depends_on:
seaweedfs:
condition: service_healthy
healthcheck:
disable: true
restart: "no"
migrate:
<<: *app
entrypoint: ["/usr/local/bin/migrate"]
command: ["up"]
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_SSL_MODE: disable
depends_on:
postgres:
condition: service_healthy
restart: "no"
api:
<<: *app
build:
context: .
dockerfile: Dockerfile
env_file:
- path: .env
required: false
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_SSL_MODE: disable
REDIS_ENABLED: "${REDIS_ENABLED:-true}"
REDIS_HOST: redis
REDIS_PORT: "6379"
CACHE_ENABLED: "${CACHE_ENABLED:-true}"
S3_ENDPOINT: http://seaweedfs:8333
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:8333}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-lab4app}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-lab4app-secret}
S3_USE_PATH_STYLE: "true"
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
PROCESSING_PIPELINE_VERSION: ${PROCESSING_PIPELINE_VERSION:-1}
PROCESSING_MAX_ATTEMPTS: ${PROCESSING_MAX_ATTEMPTS:-5}
PROCESSING_JOB_TIMEOUT: ${PROCESSING_JOB_TIMEOUT:-120s}
PROCESSING_LEASE_TTL: ${PROCESSING_LEASE_TTL:-180s}
PROCESSING_HEARTBEAT: ${PROCESSING_HEARTBEAT:-30s}
PROCESSING_RETRY_BASE: ${PROCESSING_RETRY_BASE:-2s}
PROCESSING_RETRY_CAP: ${PROCESSING_RETRY_CAP:-60s}
STAGING_ORPHAN_GRACE: ${STAGING_ORPHAN_GRACE:-1h}
STAGING_FAILED_RETENTION: ${STAGING_FAILED_RETENTION:-168h}
ADMISSION_MAX_PENDING_PER_USER: ${ADMISSION_MAX_PENDING_PER_USER:-20}
ADMISSION_MAX_PENDING: ${ADMISSION_MAX_PENDING:-200}
ADMISSION_MAX_STAGED_BYTES: ${ADMISSION_MAX_STAGED_BYTES:-2147483648}
ADMISSION_MAX_CONCURRENT_UPLOADS: ${ADMISSION_MAX_CONCURRENT_UPLOADS:-8}
ports:
- "127.0.0.1:${SERVER_PORT:-8080}:8080"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
interval: 10s
timeout: 3s
retries: 5
start_period: 5s
restart: unless-stopped
worker:
<<: *app
entrypoint: ["/usr/local/bin/worker"]
env_file:
- path: .env
required: false
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_SSL_MODE: disable
S3_ENDPOINT: http://seaweedfs:8333
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:8333}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-lab4app}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-lab4app-secret}
S3_USE_PATH_STYLE: "true"
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
BROKER_URL: ${BROKER_URL:-amqp://messenger:messenger@broker:5672/messenger}
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1}
WORKER_PREFETCH: ${WORKER_PREFETCH:-1}
WORKER_HEALTH_ADDR: ":8081"
FAULTS_ENABLED: ${FAULTS_ENABLED:-0}
FAULT_TARGET_JOB: ${FAULT_TARGET_JOB:-}
PROCESSING_PIPELINE_VERSION: ${PROCESSING_PIPELINE_VERSION:-1}
PROCESSING_MAX_ATTEMPTS: ${PROCESSING_MAX_ATTEMPTS:-5}
PROCESSING_JOB_TIMEOUT: ${PROCESSING_JOB_TIMEOUT:-120s}
PROCESSING_LEASE_TTL: ${PROCESSING_LEASE_TTL:-180s}
PROCESSING_HEARTBEAT: ${PROCESSING_HEARTBEAT:-30s}
PROCESSING_RETRY_BASE: ${PROCESSING_RETRY_BASE:-2s}
PROCESSING_RETRY_CAP: ${PROCESSING_RETRY_CAP:-60s}
ports:
- "127.0.0.1:${WORKER_HEALTH_PORT:-8081}:8081"
depends_on:
postgres:
condition: service_healthy
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
broker:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8081/health/ready"]
interval: 10s
timeout: 5s
retries: 12
start_period: 10s
restart: unless-stopped
relay:
<<: *app
entrypoint: ["/usr/local/bin/relay"]
env_file:
- path: .env
required: false
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_SSL_MODE: disable
BROKER_URL: ${BROKER_URL:-amqp://messenger:messenger@broker:5672/messenger}
RELAY_HEALTH_ADDR: ":8082"
FAULTS_ENABLED: ${FAULTS_ENABLED:-0}
FAULT_TARGET_JOB: ${FAULT_TARGET_JOB:-}
ports:
- "127.0.0.1:${RELAY_HEALTH_PORT:-8082}:8082"
depends_on:
postgres:
condition: service_healthy
migrate:
condition: service_completed_successfully
broker:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8082/health/ready"]
interval: 10s
timeout: 5s
retries: 12
start_period: 10s
restart: unless-stopped
volumes:
postgres18-data:
name: mtusi-messenger-lab6-postgres18-data
redis7-data:
name: mtusi-messenger-lab6-redis7-data
seaweedfs-data:
name: mtusi-messenger-lab6-seaweedfs-data
rabbitmq-data:
name: mtusi-messenger-lab6-rabbitmq-data
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1 +0,0 @@
{"audit_events": {"update auth/cert/login": 1658, "update pki/issue/api": 18, "update pki/issue/worker": 34, "update pki/issue/relay": 12, "update pki/issue/lb": 14, "update pki/issue/postgres": 12, "update pki/issue/redis": 12, "update pki/issue/s3": 12, "update pki/issue/broker": 12, "update pki/issue/collector": 14, "update pki/issue/prometheus": 14, "update pki/issue/loki": 14, "update pki/issue/tempo": 14, "update pki/issue/grafana": 14, "update pki/issue/openbao": 14, "update pki/issue/operator": 14, "update auth/token/renew-self": 8746, "update pki/revoke": 10, "update pki/issue/rogue": 4}, "raw_credentials_exported": false}
-51
View File
@@ -1,51 +0,0 @@
{
"after": [
{
"id": "6dc424bc61ca96d86e3633154dd7106c9721ac2d1f562bff84749232ac72f36b",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": false,
"service": "api",
"started_at": "2026-11-09T17:49:12.241804012Z",
"volumes": []
},
{
"id": "78e96f0ca9d35adf9b9f2d4bb73c25fbdc24463a331eee1ec61882d1ee2cb2e3",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:49:12.311174933Z",
"volumes": []
}
],
"before": [
{
"id": "6dc424bc61ca96d86e3633154dd7106c9721ac2d1f562bff84749232ac72f36b",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:49:12.241804012Z",
"volumes": []
},
{
"id": "78e96f0ca9d35adf9b9f2d4bb73c25fbdc24463a331eee1ec61882d1ee2cb2e3",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:49:12.311174933Z",
"volumes": []
}
],
"command": "make test-failover ACTION_SCRIPT=scripts/stop-one.sh",
"failed_attempts": 0,
"first_recovery_seconds": 0.815,
"message_attachment_session_preserved": true,
"successful_writes": 92,
"unchanged_services": [
"postgres",
"redis",
"seaweedfs",
"broker",
"openbao",
"lb"
]
}
-15
View File
@@ -1,15 +0,0 @@
2026-11-10, final image mtusi-messenger:lab7 (working tree -> lab7 branch)
go test ./... PASS
make lint PASS, 0 issues
make check PASS (offline structure/Python)
make validate PYTHON=.venv/bin/python PASS (OpenAPI 3.1 + JSON Schema)
make test PASS (public HTTPS smoke)
make test-security PASS (trusted HTTPS; untrusted CA rejected)
make test-lab7 14/14 security groups passed
make test-pki 3/3 repetitions passed
make auth-budget measured (hash_verify + api_auth)
make renew-once 15 roles + CRL sync passed
make test-persistence ACTION_SCRIPT=scripts/restart.sh PASS
make test-failover ACTION_SCRIPT=scripts/stop-one.sh PASS (93 writes, 0 failed, 1.36 s)
python3 scripts/check_evidence.py PASS (no obvious secrets/signed URLs/tokens)
Note: test-pki ran on the build immediately before the last best-effort rehash helper extraction; the PKI/trust/CA code was unchanged by that refactor. Smoke/security/auth were rerun on the final image after the rebuild.
-2
View File
@@ -1,2 +0,0 @@
ok mtusi-messenger/internal/storage/postgres 14.665s
ok mtusi-messenger/internal/storage/redis 4.080s
-15
View File
@@ -1,15 +0,0 @@
{
"scenario": "authorized API old leaf revoked at native Collector gateway",
"old_before_status": 200,
"old_after_classification": "tls_certificate_rejected",
"replacement_status": 200,
"revocation": {
"role": "api",
"revoked_serial": "6714be6074b176d9af075abe183d4667b04b10c3",
"crls_updated": true,
"native_gateway_crls_reloaded": true,
"old_connections_drained": true
},
"images_rebuilt": false,
"private_old_material_deleted": true
}
-10
View File
@@ -1,10 +0,0 @@
{
"command": "targeted Controller.wait_s3 missing-established-object scenario",
"missing_object_http_status": 404,
"deadline_seconds": 2,
"observed_failure_seconds": 2.000884750392288,
"readiness_fail_closed": true,
"established_missing_object_not_reseeded": true,
"original_marker_unchanged": true,
"original_full_body_readback_after_restore": true
}
-86
View File
@@ -1,86 +0,0 @@
{
"timestamp": "2026-11-10T11:14:31.210330+00:00",
"ttl": "1h",
"roles": {
"api": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"api\", \"serial_number\": \"1aa48f2c79560ee6255a712c07546a1e2674bd3b\", \"not_after\": \"Nov 10 12:14:31 2026 GMT\"}"
},
"worker": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"worker\", \"serial_number\": \"26be7b87f0b59ce4afaaa7025e64f7a14f83ad64\", \"not_after\": \"Nov 10 12:14:31 2026 GMT\"}"
},
"relay": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"relay\", \"serial_number\": \"56db38bc020935548ed33112df3e4872753fb5b1\", \"not_after\": \"Nov 10 12:14:32 2026 GMT\"}"
},
"lb": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"lb\", \"serial_number\": \"1f4dd141b7245ead56b2b76f30de0ae5c2f08b60\", \"not_after\": \"Nov 10 12:14:32 2026 GMT\"}"
},
"postgres": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"postgres\", \"serial_number\": \"2c22edc594ad37460d218aff16744a1e1eabab8a\", \"not_after\": \"Nov 10 12:14:33 2026 GMT\"}"
},
"redis": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"redis\", \"serial_number\": \"1fe0f04dc1406f8504cc1e276bef84d75b9ba7d6\", \"not_after\": \"Nov 10 12:14:33 2026 GMT\"}"
},
"s3": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"s3\", \"serial_number\": \"500905f19677e271be1123b81312e333c837df77\", \"not_after\": \"Nov 10 12:14:34 2026 GMT\"}"
},
"broker": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"broker\", \"serial_number\": \"68673bd02eb82a061229fb567a81827a553b02de\", \"not_after\": \"Nov 10 12:14:45 2026 GMT\"}"
},
"collector": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"collector\", \"serial_number\": \"69bfc8ed94a3176a23706d6b04c535e52de70f07\", \"not_after\": \"Nov 10 12:14:57 2026 GMT\"}"
},
"prometheus": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"prometheus\", \"serial_number\": \"0ae5d6a037b34083d50e230753c1303d3a995042\", \"not_after\": \"Nov 10 12:15:28 2026 GMT\"}"
},
"loki": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"loki\", \"serial_number\": \"02ccff65b5564f63b1f079bdc113bdc3e09d0a5f\", \"not_after\": \"Nov 10 12:15:28 2026 GMT\"}"
},
"tempo": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"tempo\", \"serial_number\": \"2f934d2031a9168bd54e5d27194f5f9b97d10516\", \"not_after\": \"Nov 10 12:15:30 2026 GMT\"}"
},
"grafana": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"grafana\", \"serial_number\": \"2bd436cc066dbd03ec24d900e36a5aa8cd0857e8\", \"not_after\": \"Nov 10 12:15:33 2026 GMT\"}"
},
"openbao": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"openbao\", \"serial_number\": \"18bf225b8d809f02b344f0b1f0e53bfb6f5e50f5\", \"not_after\": \"Nov 10 12:15:34 2026 GMT\"}"
},
"operator": {
"ok": true,
"mode": "renew",
"output": "{\"role\": \"operator\", \"serial_number\": \"1466d3f2b333fe21138e4886d4e57ccc845d07f0\", \"not_after\": \"Nov 10 12:15:38 2026 GMT\"}"
}
},
"crls": {
"ok": true,
"output": "{\"crls_updated\": true, \"identities_republished\": 18}"
},
"passed": true
}
-7
View File
@@ -1,7 +0,0 @@
2026-11-10, final image mtusi-messenger:lab7
make test-persistence ACTION_SCRIPT=scripts/restart.sh
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
{"observed_instances_before": 2, "successful_writes": 84, "failed_attempts": 0, "first_recovery_seconds": 1.365}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
-251
View File
@@ -1,251 +0,0 @@
{
"measurement": "one Docker stats --no-stream sample; not a peak/capacity benchmark",
"rows": [
{
"BlockIO": "11.1MB / 284MB",
"CPUPerc": "0.79%",
"Container": "7d38be7a2d93250ca144a0ea7e98441e09f37ae96761d2f162270398fb75434f",
"ID": "7d38be7a2d93",
"MemPerc": "18.93%",
"MemUsage": "60.57MiB / 320MiB",
"Name": "mtusi-messenger-lab6-postgres-1",
"NetIO": "11.3MB / 74.4MB",
"PIDs": "13"
},
{
"BlockIO": "147kB / 12.3kB",
"CPUPerc": "0.38%",
"Container": "f4be51e848db72d494d0f81e2e828c5bc85887c4263f15310029ca5039bd6eac",
"ID": "f4be51e848db",
"MemPerc": "3.47%",
"MemUsage": "4.441MiB / 128MiB",
"Name": "mtusi-messenger-lab6-redis-1",
"NetIO": "1.12MB / 38.1MB",
"PIDs": "7"
},
{
"BlockIO": "4.1kB / 0B",
"CPUPerc": "0.00%",
"Container": "147b9f653169aac4ba28af1deedfb318c83a8674ba537e542f71607ae9b946d7",
"ID": "147b9f653169",
"MemPerc": "16.95%",
"MemUsage": "10.85MiB / 64MiB",
"Name": "mtusi-messenger-lab6-loki-tls-1",
"NetIO": "6.82MB / 34.6MB",
"PIDs": "5"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.00%",
"Container": "4ca25f85d3e0dc61a22113a2ef8d61a87f66beef1831e36d871f9960d1ab9ab0",
"ID": "4ca25f85d3e0",
"MemPerc": "15.99%",
"MemUsage": "10.23MiB / 64MiB",
"Name": "mtusi-messenger-lab6-grafana-tls-1",
"NetIO": "272kB / 98.2kB",
"PIDs": "5"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.63%",
"Container": "d2911f0e6850c716f9602073046c61bf94d6009de249243c59da4e052c7f4bd6",
"ID": "d2911f0e6850",
"MemPerc": "23.72%",
"MemUsage": "15.18MiB / 64MiB",
"Name": "mtusi-messenger-lab6-broker-admin-tls-1",
"NetIO": "9.21MB / 47MB",
"PIDs": "5"
},
{
"BlockIO": "4.1kB / 0B",
"CPUPerc": "0.02%",
"Container": "cf0f3e7996aa9006c5c0fbd40d3eb079368d0a4f792eed070e6174653e45f202",
"ID": "cf0f3e7996aa",
"MemPerc": "17.06%",
"MemUsage": "10.92MiB / 64MiB",
"Name": "mtusi-messenger-lab6-tempo-tls-1",
"NetIO": "7.66MB / 17.7MB",
"PIDs": "5"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.19%",
"Container": "8e19759e46485bcdb3bb73beb5082f2537a380e504a3ce30765b4f4dcc504f25",
"ID": "8e19759e4648",
"MemPerc": "17.69%",
"MemUsage": "11.32MiB / 64MiB",
"Name": "mtusi-messenger-lab6-collector-tls-1",
"NetIO": "57.3MB / 41.6MB",
"PIDs": "5"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.00%",
"Container": "0975fe463bb0d3f1ecc0ea2c543b64a9d7ea0ddd0b687ec4bd92c815c15dbf27",
"ID": "0975fe463bb0",
"MemPerc": "16.03%",
"MemUsage": "10.26MiB / 64MiB",
"Name": "mtusi-messenger-lab6-prometheus-tls-1",
"NetIO": "283MB / 34.8MB",
"PIDs": "5"
},
{
"BlockIO": "131kB / 0B",
"CPUPerc": "0.37%",
"Container": "ba887c008d7293f890e1476be9bbce0d3309d297af0fe0f18b8d6a6bce3f1384",
"ID": "ba887c008d72",
"MemPerc": "5.29%",
"MemUsage": "13.54MiB / 256MiB",
"Name": "mtusi-messenger-lab6-api-2",
"NetIO": "11.7MB / 15.7MB",
"PIDs": "9"
},
{
"BlockIO": "73.7kB / 0B",
"CPUPerc": "0.13%",
"Container": "b0edb201d4010d67ce0f39fc516a867adb0b34c6fcc4c1ccadeec7e7f66cd19e",
"ID": "b0edb201d401",
"MemPerc": "5.27%",
"MemUsage": "13.5MiB / 256MiB",
"Name": "mtusi-messenger-lab6-api-1",
"NetIO": "11.7MB / 15.5MB",
"PIDs": "9"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.18%",
"Container": "11f8bb80fc16a72e2bc56353d47c16765151625959d9c8e2388336ef9b8c1e0a",
"ID": "11f8bb80fc16",
"MemPerc": "9.38%",
"MemUsage": "12MiB / 128MiB",
"Name": "mtusi-messenger-lab6-relay-1",
"NetIO": "3.76MB / 6.24MB",
"PIDs": "8"
},
{
"BlockIO": "65.5kB / 0B",
"CPUPerc": "0.15%",
"Container": "9207c3d42f1e50188efe5757c3c2869f33f96b5d7bf07faa84d5d109c20aef6c",
"ID": "9207c3d42f1e",
"MemPerc": "1.42%",
"MemUsage": "14.51MiB / 1GiB",
"Name": "mtusi-messenger-lab6-worker-1",
"NetIO": "47.4MB / 6.33MB",
"PIDs": "9"
},
{
"BlockIO": "1.21MB / 0B",
"CPUPerc": "0.16%",
"Container": "a11152720aac3bd90254fa0fa6080ed7ae4bb31c977452fcb57bd4842437f685",
"ID": "a11152720aac",
"MemPerc": "27.38%",
"MemUsage": "70.09MiB / 256MiB",
"Name": "mtusi-messenger-lab6-s3-1",
"NetIO": "3.19MB / 95MB",
"PIDs": "10"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.20%",
"Container": "6d00987f050d14af10ae5b24a91435ba2da1fbb9e59b8d7e68ff795d37952099",
"ID": "6d00987f050d",
"MemPerc": "18.20%",
"MemUsage": "11.65MiB / 64MiB",
"Name": "mtusi-messenger-lab6-lb-1",
"NetIO": "4.99MB / 20.8MB",
"PIDs": "5"
},
{
"BlockIO": "9.22MB / 29.1MB",
"CPUPerc": "0.60%",
"Container": "c13f8ada0b058159cd1786434cdd817031d0aab60220a20b1a6722d5e221629c",
"ID": "c13f8ada0b05",
"MemPerc": "8.75%",
"MemUsage": "67.22MiB / 768MiB",
"Name": "mtusi-messenger-lab6-tempo-1",
"NetIO": "7.66MB / 17.7MB",
"PIDs": "10"
},
{
"BlockIO": "20.8MB / 459kB",
"CPUPerc": "2.28%",
"Container": "36ecbf91a52bca1dc3ac266656b0a4a3227f15d337455a69926b28412e1ce6ee",
"ID": "36ecbf91a52b",
"MemPerc": "36.51%",
"MemUsage": "140.2MiB / 384MiB",
"Name": "mtusi-messenger-lab6-broker-1",
"NetIO": "9.21MB / 47MB",
"PIDs": "54"
},
{
"BlockIO": "5.01MB / 938kB",
"CPUPerc": "0.27%",
"Container": "42b6a9e1330f8304ee6924e03423730f7c53f5fdf868b0a7575a26585758dc7e",
"ID": "42b6a9e1330f",
"MemPerc": "38.93%",
"MemUsage": "249.1MiB / 640MiB",
"Name": "mtusi-messenger-lab6-seaweedfs-1",
"NetIO": "3.19MB / 95MB",
"PIDs": "8"
},
{
"BlockIO": "39.9MB / 2MB",
"CPUPerc": "0.90%",
"Container": "1d9e067c6d26f7d2613c4d520d4f5bb96e906a318d35928aac030ae05b0a17a5",
"ID": "1d9e067c6d26",
"MemPerc": "25.53%",
"MemUsage": "81.68MiB / 320MiB",
"Name": "mtusi-messenger-lab6-loki-1",
"NetIO": "6.82MB / 34.6MB",
"PIDs": "10"
},
{
"BlockIO": "380MB / 5.21MB",
"CPUPerc": "0.92%",
"Container": "8229a7ef578fa3e4cf72a825af7d6836647de44d9f2d504c5ec5cdc307d70f93",
"ID": "8229a7ef578f",
"MemPerc": "45.68%",
"MemUsage": "233.9MiB / 512MiB",
"Name": "mtusi-messenger-lab6-grafana-1",
"NetIO": "272kB / 98.2kB",
"PIDs": "105"
},
{
"BlockIO": "300MB / 341MB",
"CPUPerc": "1.73%",
"Container": "a0dcf9498a38d7b8b1be8cef9c1fa67f56d31e9cdb2c3a75de3c2bffb422a622",
"ID": "a0dcf9498a38",
"MemPerc": "27.68%",
"MemUsage": "88.59MiB / 320MiB",
"Name": "mtusi-messenger-lab6-prometheus-1",
"NetIO": "283MB / 34.8MB",
"PIDs": "8"
},
{
"BlockIO": "154MB / 0B",
"CPUPerc": "0.88%",
"Container": "aad8b0935730a028d67bc63725e52b9a90e186ad73daa33719679219830692bd",
"ID": "aad8b0935730",
"MemPerc": "63.35%",
"MemUsage": "121.6MiB / 192MiB",
"Name": "mtusi-messenger-lab6-otel-collector-1",
"NetIO": "57.3MB / 41.6MB",
"PIDs": "8"
},
{
"BlockIO": "54MB / 103MB",
"CPUPerc": "0.42%",
"Container": "6cc7c1aab331d35c424fffd4604932cff2fd25eaa86233d68af7f8ba368c09dd",
"ID": "6cc7c1aab331",
"MemPerc": "23.67%",
"MemUsage": "60.59MiB / 256MiB",
"Name": "mtusi-messenger-lab6-openbao-1",
"NetIO": "10.6MB / 12.2MB",
"PIDs": "9"
}
],
"vm": {
"cpus": 4,
"memory_bytes": 8307167232
}
}
-483
View File
@@ -1,483 +0,0 @@
{
"after": [
{
"id": "6dc424bc61ca96d86e3633154dd7106c9721ac2d1f562bff84749232ac72f36b",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:49:12.241804012Z",
"volumes": []
},
{
"id": "78e96f0ca9d35adf9b9f2d4bb73c25fbdc24463a331eee1ec61882d1ee2cb2e3",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:49:12.311174933Z",
"volumes": []
},
{
"id": "36ecbf91a52bca1dc3ac266656b0a4a3227f15d337455a69926b28412e1ce6ee",
"image": "sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528",
"running": true,
"service": "broker",
"started_at": "2026-11-09T17:48:35.591857217Z",
"volumes": [
"mtusi-messenger-lab6_rabbitmq-data"
]
},
{
"id": "886a18334276270e1d4600c3d732ce08ceea44f838451b004aa2f37a8fb8810f",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "broker-admin-tls",
"started_at": "2026-11-09T17:49:06.024062987Z",
"volumes": []
},
{
"id": "9c7cb81c85ffdca49f6449f5d1b73972e90dfaa5dde0f43b19a3a6c47c925cce",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "collector-tls",
"started_at": "2026-11-09T17:49:05.93028472Z",
"volumes": []
},
{
"id": "8229a7ef578fa3e4cf72a825af7d6836647de44d9f2d504c5ec5cdc307d70f93",
"image": "sha256:9f7aa1e1e3246aade5792d35a738049f7f32f89cd51d1956cf426a4e86268a84",
"running": true,
"service": "grafana",
"started_at": "2026-11-09T17:48:34.843817591Z",
"volumes": [
"mtusi-messenger-lab6_grafana-data"
]
},
{
"id": "c0d70abdd1b7c9876b03ee24cce57174d23e32bd68b69125239133dd12995537",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "grafana-tls",
"started_at": "2026-11-09T17:49:05.891655005Z",
"volumes": []
},
{
"id": "6d00987f050d14af10ae5b24a91435ba2da1fbb9e59b8d7e68ff795d37952099",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "lb",
"started_at": "2026-11-09T17:49:12.37228931Z",
"volumes": []
},
{
"id": "1d9e067c6d26f7d2613c4d520d4f5bb96e906a318d35928aac030ae05b0a17a5",
"image": "sha256:be31579ac047e9f78b81e48f3b69d3af709e7299b431d5aa78bcda43382f9511",
"running": true,
"service": "loki",
"started_at": "2026-11-09T17:48:35.128041359Z",
"volumes": [
"mtusi-messenger-lab6_loki-data"
]
},
{
"id": "855c6e543694796e222b3a6d12b518a50f7a2dc3c7f57707a0d7d23565d3bf70",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "loki-tls",
"started_at": "2026-11-09T17:49:06.056135949Z",
"volumes": []
},
{
"id": "6cc7c1aab331d35c424fffd4604932cff2fd25eaa86233d68af7f8ba368c09dd",
"image": "sha256:5046911075e137e154ce49ab051502f4ec7cf367d484ae4a4dce665d9b90561f",
"running": true,
"service": "openbao",
"started_at": "2026-11-09T17:48:32.966437544Z",
"volumes": [
"mtusi-messenger-lab6_openbao-audit",
"mtusi-messenger-lab6_openbao-raft-data"
]
},
{
"id": "aad8b0935730a028d67bc63725e52b9a90e186ad73daa33719679219830692bd",
"image": "sha256:340c9ca6a36617084c6661bdc4f0fe92b7cda5a805d61673ec8db375fddc522b",
"running": true,
"service": "otel-collector",
"started_at": "2026-11-09T17:48:39.529892928Z",
"volumes": []
},
{
"id": "d039deb141cadb3741fdbcd64d3dcae8653a1c9c2fad06928c3afab30d5cba7a",
"image": "sha256:123b17998ccaf47e53b502e8c6a1e79afd8f579c6f3eec83c563da026f957395",
"running": true,
"service": "postgres",
"started_at": "2026-11-09T17:48:34.527818375Z",
"volumes": [
"mtusi-messenger-lab6_postgres18-data"
]
},
{
"id": "a0dcf9498a38d7b8b1be8cef9c1fa67f56d31e9cdb2c3a75de3c2bffb422a622",
"image": "sha256:fa3302279710be2f21a8301ec17a8b4f2301fd829bd113839b3b6b02b6f191a2",
"running": true,
"service": "prometheus",
"started_at": "2026-11-09T17:48:34.575175557Z",
"volumes": [
"mtusi-messenger-lab6_prometheus-data"
]
},
{
"id": "c132e4c0463c642c878be8f019adc6ea412091c14aa36ac108831348e04bc2c8",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "prometheus-tls",
"started_at": "2026-11-09T17:49:05.995209315Z",
"volumes": []
},
{
"id": "6b5d87edafed608b12d639512369f25201b039428cfe92a284d3abdd227bf3d6",
"image": "sha256:c5d34a98396a4775e223c74e929162c35c5a2182901ba26b50ade939941ce14b",
"running": true,
"service": "redis",
"started_at": "2026-11-09T17:48:34.548345189Z",
"volumes": [
"mtusi-messenger-lab6_redis7-data"
]
},
{
"id": "7527503180f7ff48bdd7b5c0ffe35fd1afed40fed37966dd76eec64925f824eb",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "relay",
"started_at": "2026-11-09T17:49:12.286372113Z",
"volumes": []
},
{
"id": "a11152720aac3bd90254fa0fa6080ed7ae4bb31c977452fcb57bd4842437f685",
"image": "sha256:f7a49e3f3972ebed5be2ed4befa4a0c68eb7bdddba6e692d42729ceb545134b8",
"running": true,
"service": "s3",
"started_at": "2026-11-09T17:49:05.862741573Z",
"volumes": [
"68cfe1544e4b4c38b628fcccd543bab36e6db31f8125427cce1910ffdf152d27"
]
},
{
"id": "42b6a9e1330f8304ee6924e03423730f7c53f5fdf868b0a7575a26585758dc7e",
"image": "sha256:f7a49e3f3972ebed5be2ed4befa4a0c68eb7bdddba6e692d42729ceb545134b8",
"running": true,
"service": "seaweedfs",
"started_at": "2026-11-09T17:48:59.541759754Z",
"volumes": [
"mtusi-messenger-lab6_seaweedfs-data"
]
},
{
"id": "c13f8ada0b058159cd1786434cdd817031d0aab60220a20b1a6722d5e221629c",
"image": "sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38",
"running": true,
"service": "tempo",
"started_at": "2026-11-09T17:48:34.710097969Z",
"volumes": [
"mtusi-messenger-lab6_tempo-data"
]
},
{
"id": "7ba31deb6284b993212a6eaf3fab4534aadea27adc9c3f5d87662f7caa5cf9af",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "tempo-tls",
"started_at": "2026-11-09T17:49:05.963147722Z",
"volumes": []
},
{
"id": "5721b1bd16140a6c7c6ec996c7fc09ea72690ea5a2c22b247648df39abff6e72",
"image": "sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f",
"running": false,
"service": "volume-init",
"started_at": "2026-11-09T17:42:17.421314543Z",
"volumes": [
"mtusi-messenger-lab6_grafana-data",
"mtusi-messenger-lab6_loki-data",
"mtusi-messenger-lab6_openbao-audit",
"mtusi-messenger-lab6_openbao-raft-data",
"mtusi-messenger-lab6_postgres18-data",
"mtusi-messenger-lab6_prometheus-data",
"mtusi-messenger-lab6_rabbitmq-data",
"mtusi-messenger-lab6_redis7-data",
"mtusi-messenger-lab6_seaweedfs-data",
"mtusi-messenger-lab6_tempo-data"
]
},
{
"id": "5b9060d0bbe1839c50cebca3c954298c24b32e0a4aa68eebe4dbc74a8267d90c",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "worker",
"started_at": "2026-11-09T17:49:12.241160455Z",
"volumes": []
}
],
"before": [
{
"id": "6dc424bc61ca96d86e3633154dd7106c9721ac2d1f562bff84749232ac72f36b",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:38:31.932939071Z",
"volumes": []
},
{
"id": "78e96f0ca9d35adf9b9f2d4bb73c25fbdc24463a331eee1ec61882d1ee2cb2e3",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "api",
"started_at": "2026-11-09T17:38:31.867142361Z",
"volumes": []
},
{
"id": "36ecbf91a52bca1dc3ac266656b0a4a3227f15d337455a69926b28412e1ce6ee",
"image": "sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528",
"running": true,
"service": "broker",
"started_at": "2026-11-09T16:50:33.292613189Z",
"volumes": [
"mtusi-messenger-lab6_rabbitmq-data"
]
},
{
"id": "eca35fbeb8c0cd1a21211dac175592c4a154ab2993b3524242d8e0d3e0e37b3f",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "broker-admin-tls",
"started_at": "2026-11-09T17:38:31.457677446Z",
"volumes": []
},
{
"id": "49e4144a7f5f69a325c07c19836b3ab40c06de238caa3a8809429e173b848850",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "collector-tls",
"started_at": "2026-11-09T17:38:30.744262456Z",
"volumes": []
},
{
"id": "8229a7ef578fa3e4cf72a825af7d6836647de44d9f2d504c5ec5cdc307d70f93",
"image": "sha256:9f7aa1e1e3246aade5792d35a738049f7f32f89cd51d1956cf426a4e86268a84",
"running": true,
"service": "grafana",
"started_at": "2026-11-09T16:50:32.46372704Z",
"volumes": [
"mtusi-messenger-lab6_grafana-data"
]
},
{
"id": "ad3bfb9aca712923479c6717781c89f0b6ec51980949dbe2ccca95c6cc548721",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "grafana-tls",
"started_at": "2026-11-09T17:38:31.334261143Z",
"volumes": []
},
{
"id": "6d00987f050d14af10ae5b24a91435ba2da1fbb9e59b8d7e68ff795d37952099",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "lb",
"started_at": "2026-11-09T17:38:37.335492745Z",
"volumes": []
},
{
"id": "1d9e067c6d26f7d2613c4d520d4f5bb96e906a318d35928aac030ae05b0a17a5",
"image": "sha256:be31579ac047e9f78b81e48f3b69d3af709e7299b431d5aa78bcda43382f9511",
"running": true,
"service": "loki",
"started_at": "2026-11-09T16:50:32.692135394Z",
"volumes": [
"mtusi-messenger-lab6_loki-data"
]
},
{
"id": "860bcb786ba551f0dab75ee92789c17ba4f5da2770d9073bc5bfa140c6d443c4",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "loki-tls",
"started_at": "2026-11-09T17:38:31.292594653Z",
"volumes": []
},
{
"id": "6cc7c1aab331d35c424fffd4604932cff2fd25eaa86233d68af7f8ba368c09dd",
"image": "sha256:5046911075e137e154ce49ab051502f4ec7cf367d484ae4a4dce665d9b90561f",
"running": true,
"service": "openbao",
"started_at": "2026-11-09T16:50:30.595362071Z",
"volumes": [
"mtusi-messenger-lab6_openbao-audit",
"mtusi-messenger-lab6_openbao-raft-data"
]
},
{
"id": "aad8b0935730a028d67bc63725e52b9a90e186ad73daa33719679219830692bd",
"image": "sha256:340c9ca6a36617084c6661bdc4f0fe92b7cda5a805d61673ec8db375fddc522b",
"running": true,
"service": "otel-collector",
"started_at": "2026-11-09T16:50:35.15935884Z",
"volumes": []
},
{
"id": "d039deb141cadb3741fdbcd64d3dcae8653a1c9c2fad06928c3afab30d5cba7a",
"image": "sha256:123b17998ccaf47e53b502e8c6a1e79afd8f579c6f3eec83c563da026f957395",
"running": true,
"service": "postgres",
"started_at": "2026-11-09T17:38:18.438516673Z",
"volumes": [
"mtusi-messenger-lab6_postgres18-data"
]
},
{
"id": "a0dcf9498a38d7b8b1be8cef9c1fa67f56d31e9cdb2c3a75de3c2bffb422a622",
"image": "sha256:fa3302279710be2f21a8301ec17a8b4f2301fd829bd113839b3b6b02b6f191a2",
"running": true,
"service": "prometheus",
"started_at": "2026-11-09T16:50:32.255745761Z",
"volumes": [
"mtusi-messenger-lab6_prometheus-data"
]
},
{
"id": "e15e2129d438cd90ba9686acfa5ec00523230647a43cfc3e7290b73f4bc66965",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "prometheus-tls",
"started_at": "2026-11-09T17:38:31.250742923Z",
"volumes": []
},
{
"id": "6b5d87edafed608b12d639512369f25201b039428cfe92a284d3abdd227bf3d6",
"image": "sha256:c5d34a98396a4775e223c74e929162c35c5a2182901ba26b50ade939941ce14b",
"running": true,
"service": "redis",
"started_at": "2026-11-09T17:38:18.493395669Z",
"volumes": [
"mtusi-messenger-lab6_redis7-data"
]
},
{
"id": "7527503180f7ff48bdd7b5c0ffe35fd1afed40fed37966dd76eec64925f824eb",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "relay",
"started_at": "2026-11-09T17:38:31.751453151Z",
"volumes": []
},
{
"id": "4c9dc89246275682f4f848ce68d9b20adc1919bab63ac1dbd256d59a20abf033",
"image": "sha256:f7a49e3f3972ebed5be2ed4befa4a0c68eb7bdddba6e692d42729ceb545134b8",
"running": true,
"service": "s3",
"started_at": "2026-11-09T17:38:18.928393231Z",
"volumes": [
"68cfe1544e4b4c38b628fcccd543bab36e6db31f8125427cce1910ffdf152d27"
]
},
{
"id": "42b6a9e1330f8304ee6924e03423730f7c53f5fdf868b0a7575a26585758dc7e",
"image": "sha256:f7a49e3f3972ebed5be2ed4befa4a0c68eb7bdddba6e692d42729ceb545134b8",
"running": true,
"service": "seaweedfs",
"started_at": "2026-11-09T16:50:57.611450545Z",
"volumes": [
"mtusi-messenger-lab6_seaweedfs-data"
]
},
{
"id": "c13f8ada0b058159cd1786434cdd817031d0aab60220a20b1a6722d5e221629c",
"image": "sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38",
"running": true,
"service": "tempo",
"started_at": "2026-11-09T17:38:31.367902689Z",
"volumes": [
"mtusi-messenger-lab6_tempo-data"
]
},
{
"id": "d14cc9321a16bba368ce4a6a3cc6488183cd20c0093706cb75f4c65227e99c80",
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"running": true,
"service": "tempo-tls",
"started_at": "2026-11-09T17:38:31.496595102Z",
"volumes": []
},
{
"id": "5721b1bd16140a6c7c6ec996c7fc09ea72690ea5a2c22b247648df39abff6e72",
"image": "sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f",
"running": false,
"service": "volume-init",
"started_at": "2026-11-09T17:42:17.421314543Z",
"volumes": [
"mtusi-messenger-lab6_grafana-data",
"mtusi-messenger-lab6_loki-data",
"mtusi-messenger-lab6_openbao-audit",
"mtusi-messenger-lab6_openbao-raft-data",
"mtusi-messenger-lab6_postgres18-data",
"mtusi-messenger-lab6_prometheus-data",
"mtusi-messenger-lab6_rabbitmq-data",
"mtusi-messenger-lab6_redis7-data",
"mtusi-messenger-lab6_seaweedfs-data",
"mtusi-messenger-lab6_tempo-data"
]
},
{
"id": "5b9060d0bbe1839c50cebca3c954298c24b32e0a4aa68eebe4dbc74a8267d90c",
"image": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"running": true,
"service": "worker",
"started_at": "2026-11-09T17:38:31.810992367Z",
"volumes": []
}
],
"commands": [
"make test test-security test-lab7 test-attachments test-presign test-queue test-idempotency test-observability",
"make test-persistence ACTION_SCRIPT=scripts/restart.sh"
],
"persistence_result": "Full attachment bytes, confirmed message and existing session preserved.",
"recreated_services_observed": [
"broker-admin-tls",
"collector-tls",
"grafana-tls",
"loki-tls",
"prometheus-tls",
"s3",
"tempo-tls"
],
"restarted_services_observed": [
"api",
"broker",
"grafana",
"lb",
"loki",
"openbao",
"otel-collector",
"postgres",
"prometheus",
"redis",
"relay",
"seaweedfs",
"tempo",
"worker"
],
"same_volume_names": true,
"scope_note": "Before snapshot precedes the acceptance group, whose async scenarios also restart components; after snapshot follows the explicit persistence hook.",
"verified_volume_names": [
"68cfe1544e4b4c38b628fcccd543bab36e6db31f8125427cce1910ffdf152d27",
"mtusi-messenger-lab6_grafana-data",
"mtusi-messenger-lab6_loki-data",
"mtusi-messenger-lab6_openbao-audit",
"mtusi-messenger-lab6_openbao-raft-data",
"mtusi-messenger-lab6_postgres18-data",
"mtusi-messenger-lab6_prometheus-data",
"mtusi-messenger-lab6_rabbitmq-data",
"mtusi-messenger-lab6_redis7-data",
"mtusi-messenger-lab6_seaweedfs-data",
"mtusi-messenger-lab6_tempo-data"
]
}
-10
View File
@@ -1,10 +0,0 @@
{
"scenario": "expired offline root CRL operator refresh",
"expired_before": "Nov 9 19:18:56 2026 GMT",
"next_update_after": "Nov 16 19:18:57 2026 GMT",
"refreshed_signed_crl": true,
"valid_for_more_than_24h": true,
"same_ca_key_certificate_revocation_index": true,
"unexpired_crl_not_regenerated": true,
"docker_targets_mutated": false
}
File diff suppressed because it is too large Load Diff
@@ -1 +0,0 @@
exit=0
File diff suppressed because it is too large Load Diff
-6
View File
@@ -1,6 +0,0 @@
exit=0
2026-11-09T19:35:09Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:09Z INFO Detected OS family="alpine" version="3.22.8"
2026-11-09T19:35:09Z INFO [alpine] Detecting vulnerabilities... os_version="3.22" repository="3.22" pkg_num=16
2026-11-09T19:35:09Z INFO Number of language-specific files num=0
2026-11-09T19:35:09Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
-674
View File
@@ -1,674 +0,0 @@
{
"SchemaVersion": 2,
"Trivy": {
"Version": "0.76.2"
},
"ReportID": "01a1c1ce-ad4d-700f-8a55-15afec675080",
"CreatedAt": "2026-11-09T19:35:09.90100584Z",
"ArtifactID": "sha256:062964a69725bb96611dae2ac911a5a1ab3f8d32fe6f096f267d77f09e55a99c",
"ArtifactName": "/cache/image-853e0d6c0dd947f58dd86f85f0e67fb1.tar",
"ArtifactType": "container_image",
"Metadata": {
"Size": 8821760,
"OS": {
"Family": "alpine",
"Name": "3.22.8"
},
"ImageID": "sha256:062964a69725bb96611dae2ac911a5a1ab3f8d32fe6f096f267d77f09e55a99c",
"DiffIDs": [
"sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
],
"ImageConfig": {
"architecture": "arm64",
"created": "2026-11-05T18:01:07.081961554Z",
"history": [
{
"created": "2026-11-05T18:01:07.081961554Z",
"created_by": "ADD alpine-minirootfs-3.22.8-aarch64.tar.gz / # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-11-05T18:01:07.081961554Z",
"created_by": "CMD [\"/bin/sh\"]",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
}
],
"os": "linux",
"rootfs": {
"type": "layers",
"diff_ids": [
"sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
]
},
"config": {
"Cmd": [
"/bin/sh"
],
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"WorkingDir": "/"
},
"variant": "v8"
},
"Layers": [
{
"Size": 8821760,
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
}
]
},
"Results": [
{
"Target": "/cache/image-853e0d6c0dd947f58dd86f85f0e67fb1.tar (alpine 3.22.8)",
"Class": "os-pkgs",
"Type": "alpine",
"Packages": [
{
"ID": "alpine-baselayout@3.7.0-r0",
"Name": "alpine-baselayout",
"Identifier": {
"PURL": "pkg:apk/alpine/alpine-baselayout@3.7.0-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "80538c6754a60b00"
},
"Version": "3.7.0-r0",
"Arch": "aarch64",
"SrcName": "alpine-baselayout",
"SrcVersion": "3.7.0-r0",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"alpine-baselayout-data@3.7.0-r0",
"busybox-binsh@1.37.0-r20"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:6a5ba6200cd120c428e2fd651e81ec53263b7069",
"InstalledFiles": [
"etc/motd",
"etc/crontabs/root",
"etc/modprobe.d/aliases.conf",
"etc/modprobe.d/blacklist.conf",
"etc/modprobe.d/i386.conf",
"etc/profile.d/20locale.sh",
"etc/profile.d/README",
"etc/profile.d/color_prompt.sh.disabled",
"usr/lib/sysctl.d/00-alpine.conf",
"var/lock",
"var/run",
"var/spool/mail",
"var/spool/cron/crontabs"
],
"AnalyzedBy": "apk"
},
{
"ID": "alpine-baselayout-data@3.7.0-r0",
"Name": "alpine-baselayout-data",
"Identifier": {
"PURL": "pkg:apk/alpine/alpine-baselayout-data@3.7.0-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "a7e57b099b2d1fa5"
},
"Version": "3.7.0-r0",
"Arch": "aarch64",
"SrcName": "alpine-baselayout",
"SrcVersion": "3.7.0-r0",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:aa910e13f8c581cb17403192b96d62607edf49ce",
"InstalledFiles": [
"etc/fstab",
"etc/group",
"etc/hostname",
"etc/hosts",
"etc/inittab",
"etc/modules",
"etc/mtab",
"etc/nsswitch.conf",
"etc/passwd",
"etc/profile",
"etc/protocols",
"etc/services",
"etc/shadow",
"etc/shells",
"etc/sysctl.conf"
],
"AnalyzedBy": "apk"
},
{
"ID": "alpine-keys@2.5-r0",
"Name": "alpine-keys",
"Identifier": {
"PURL": "pkg:apk/alpine/alpine-keys@2.5-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "f5fb4a123ae1c2f2"
},
"Version": "2.5-r0",
"Arch": "aarch64",
"SrcName": "alpine-keys",
"SrcVersion": "2.5-r0",
"Licenses": [
"MIT"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:f83bb63d294a84b4ff09100b5743b0277020842d",
"InstalledFiles": [
"etc/apk/keys/alpine-devel@lists.alpinelinux.org-524d27bb.rsa.pub",
"etc/apk/keys/alpine-devel@lists.alpinelinux.org-58199dcc.rsa.pub",
"etc/apk/keys/alpine-devel@lists.alpinelinux.org-616a9724.rsa.pub",
"etc/apk/keys/alpine-devel@lists.alpinelinux.org-616adfeb.rsa.pub",
"etc/apk/keys/alpine-devel@lists.alpinelinux.org-616ae350.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-4a6a0840.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-5243ef4b.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-524d27bb.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-5261cecb.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-58199dcc.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-58cbb476.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-58e4f17d.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-5e69ca50.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-60ac2099.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-6165ee59.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-61666e3f.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-616a9724.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-616abc23.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-616ac3bc.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-616adfeb.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-616ae350.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-616db30d.rsa.pub",
"usr/share/apk/keys/alpine-devel@lists.alpinelinux.org-66ba20fe.rsa.pub",
"usr/share/apk/keys/aarch64/alpine-devel@lists.alpinelinux.org-58199dcc.rsa.pub",
"usr/share/apk/keys/aarch64/alpine-devel@lists.alpinelinux.org-616ae350.rsa.pub",
"usr/share/apk/keys/armhf/alpine-devel@lists.alpinelinux.org-524d27bb.rsa.pub",
"usr/share/apk/keys/armhf/alpine-devel@lists.alpinelinux.org-616a9724.rsa.pub",
"usr/share/apk/keys/armv7/alpine-devel@lists.alpinelinux.org-524d27bb.rsa.pub",
"usr/share/apk/keys/armv7/alpine-devel@lists.alpinelinux.org-616adfeb.rsa.pub",
"usr/share/apk/keys/loongarch64/alpine-devel@lists.alpinelinux.org-66ba20fe.rsa.pub",
"usr/share/apk/keys/mips64/alpine-devel@lists.alpinelinux.org-5e69ca50.rsa.pub",
"usr/share/apk/keys/ppc64le/alpine-devel@lists.alpinelinux.org-58cbb476.rsa.pub",
"usr/share/apk/keys/ppc64le/alpine-devel@lists.alpinelinux.org-616abc23.rsa.pub",
"usr/share/apk/keys/riscv64/alpine-devel@lists.alpinelinux.org-60ac2099.rsa.pub",
"usr/share/apk/keys/riscv64/alpine-devel@lists.alpinelinux.org-616db30d.rsa.pub",
"usr/share/apk/keys/s390x/alpine-devel@lists.alpinelinux.org-58e4f17d.rsa.pub",
"usr/share/apk/keys/s390x/alpine-devel@lists.alpinelinux.org-616ac3bc.rsa.pub",
"usr/share/apk/keys/x86/alpine-devel@lists.alpinelinux.org-4a6a0840.rsa.pub",
"usr/share/apk/keys/x86/alpine-devel@lists.alpinelinux.org-5243ef4b.rsa.pub",
"usr/share/apk/keys/x86/alpine-devel@lists.alpinelinux.org-61666e3f.rsa.pub",
"usr/share/apk/keys/x86_64/alpine-devel@lists.alpinelinux.org-4a6a0840.rsa.pub",
"usr/share/apk/keys/x86_64/alpine-devel@lists.alpinelinux.org-5261cecb.rsa.pub",
"usr/share/apk/keys/x86_64/alpine-devel@lists.alpinelinux.org-6165ee59.rsa.pub"
],
"AnalyzedBy": "apk"
},
{
"ID": "alpine-release@3.22.8-r0",
"Name": "alpine-release",
"Identifier": {
"PURL": "pkg:apk/alpine/alpine-release@3.22.8-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "7ab887a31dc9c119"
},
"Version": "3.22.8-r0",
"Arch": "aarch64",
"SrcName": "alpine-base",
"SrcVersion": "3.22.8-r0",
"Licenses": [
"MIT"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"alpine-keys@2.5-r0"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:4af9f3cd61f0e18093ff99bc78021fe029958507",
"InstalledFiles": [
"etc/alpine-release",
"etc/issue",
"etc/os-release",
"etc/secfixes.d/alpine",
"usr/lib/os-release"
],
"AnalyzedBy": "apk"
},
{
"ID": "apk-tools@2.14.13-r0",
"Name": "apk-tools",
"Identifier": {
"PURL": "pkg:apk/alpine/apk-tools@2.14.13-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "66cf42c8bed88018"
},
"Version": "2.14.13-r0",
"Arch": "aarch64",
"SrcName": "apk-tools",
"SrcVersion": "2.14.13-r0",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"ca-certificates-bundle@20261020-r0",
"libapk2@2.14.13-r0",
"libcrypto3@3.5.9-r0",
"musl@1.2.5-r13",
"zlib@1.3.2-r1"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:769d962ad2c94c8b81db4550b3f9ca927859cd5f",
"InstalledFiles": [
"sbin/apk"
],
"AnalyzedBy": "apk"
},
{
"ID": "busybox@1.37.0-r20",
"Name": "busybox",
"Identifier": {
"PURL": "pkg:apk/alpine/busybox@1.37.0-r20?arch=aarch64\u0026distro=3.22.8",
"UID": "ea369e1946c12b0e"
},
"Version": "1.37.0-r20",
"Arch": "aarch64",
"SrcName": "busybox",
"SrcVersion": "1.37.0-r20",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Sören Tempel \u003csoeren+alpine@soeren-tempel.net\u003e",
"DependsOn": [
"musl@1.2.5-r13"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:5a047bc1147cb2cef3e7d5aead7e7eda126d331e",
"InstalledFiles": [
"bin/busybox",
"etc/securetty",
"etc/busybox-paths.d/busybox",
"etc/logrotate.d/acpid",
"etc/network/if-up.d/dad",
"etc/udhcpc/udhcpc.conf",
"usr/share/udhcpc/default.script"
],
"AnalyzedBy": "apk"
},
{
"ID": "busybox-binsh@1.37.0-r20",
"Name": "busybox-binsh",
"Identifier": {
"PURL": "pkg:apk/alpine/busybox-binsh@1.37.0-r20?arch=aarch64\u0026distro=3.22.8",
"UID": "9052000c01dd5cf7"
},
"Version": "1.37.0-r20",
"Arch": "aarch64",
"SrcName": "busybox",
"SrcVersion": "1.37.0-r20",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Sören Tempel \u003csoeren+alpine@soeren-tempel.net\u003e",
"DependsOn": [
"busybox@1.37.0-r20"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:61e5587c5a511ae964278741862b41769ac3a867",
"InstalledFiles": [
"bin/sh"
],
"AnalyzedBy": "apk"
},
{
"ID": "ca-certificates-bundle@20261020-r0",
"Name": "ca-certificates-bundle",
"Identifier": {
"PURL": "pkg:apk/alpine/ca-certificates-bundle@20261020-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "faaecc1036341a0a"
},
"Version": "20261020-r0",
"Arch": "aarch64",
"SrcName": "ca-certificates",
"SrcVersion": "20261020-r0",
"Licenses": [
"MPL-2.0",
"MIT"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:ece46ebfa17b1099abbf8638c273bc2fba59c1b1",
"InstalledFiles": [
"etc/ssl/cert.pem",
"etc/ssl/certs/ca-certificates.crt",
"etc/ssl1.1/cert.pem",
"etc/ssl1.1/certs"
],
"AnalyzedBy": "apk"
},
{
"ID": "libapk2@2.14.13-r0",
"Name": "libapk2",
"Identifier": {
"PURL": "pkg:apk/alpine/libapk2@2.14.13-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "d8b5a7bd3ea246f5"
},
"Version": "2.14.13-r0",
"Arch": "aarch64",
"SrcName": "apk-tools",
"SrcVersion": "2.14.13-r0",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"ca-certificates-bundle@20261020-r0",
"libcrypto3@3.5.9-r0",
"libssl3@3.5.9-r0",
"musl@1.2.5-r13",
"zlib@1.3.2-r1"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:635a5c14425e27f41ca965b6ad95d588a6e65dfe",
"InstalledFiles": [
"usr/lib/libapk.so.2.14.10"
],
"AnalyzedBy": "apk"
},
{
"ID": "libcrypto3@3.5.9-r0",
"Name": "libcrypto3",
"Identifier": {
"PURL": "pkg:apk/alpine/libcrypto3@3.5.9-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "9d90f22fd3db60f5"
},
"Version": "3.5.9-r0",
"Arch": "aarch64",
"SrcName": "openssl",
"SrcVersion": "3.5.9-r0",
"Licenses": [
"Apache-2.0"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"musl@1.2.5-r13"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:669e2c5f2534992b9667625fc1b24452db2d2cdf",
"InstalledFiles": [
"etc/ssl/ct_log_list.cnf",
"etc/ssl/ct_log_list.cnf.dist",
"etc/ssl/openssl.cnf",
"etc/ssl/openssl.cnf.dist",
"usr/lib/libcrypto.so.3",
"usr/lib/engines-3/afalg.so",
"usr/lib/engines-3/capi.so",
"usr/lib/engines-3/loader_attic.so",
"usr/lib/engines-3/padlock.so",
"usr/lib/ossl-modules/legacy.so"
],
"AnalyzedBy": "apk"
},
{
"ID": "libssl3@3.5.9-r0",
"Name": "libssl3",
"Identifier": {
"PURL": "pkg:apk/alpine/libssl3@3.5.9-r0?arch=aarch64\u0026distro=3.22.8",
"UID": "2ccbd1bba4c8bd34"
},
"Version": "3.5.9-r0",
"Arch": "aarch64",
"SrcName": "openssl",
"SrcVersion": "3.5.9-r0",
"Licenses": [
"Apache-2.0"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"libcrypto3@3.5.9-r0",
"musl@1.2.5-r13"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:4e6113e53c5cdf8fe033bb4ad8e9c6ef0a7b68e8",
"InstalledFiles": [
"usr/lib/libssl.so.3"
],
"AnalyzedBy": "apk"
},
{
"ID": "musl@1.2.5-r13",
"Name": "musl",
"Identifier": {
"PURL": "pkg:apk/alpine/musl@1.2.5-r13?arch=aarch64\u0026distro=3.22.8",
"UID": "713021714b5cfbcc"
},
"Version": "1.2.5-r13",
"Arch": "aarch64",
"SrcName": "musl",
"SrcVersion": "1.2.5-r13",
"Licenses": [
"MIT"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:240a91d94c228debea090d1bcceb87d1ec518e3b",
"InstalledFiles": [
"lib/ld-musl-aarch64.so.1",
"lib/libc.musl-aarch64.so.1"
],
"AnalyzedBy": "apk"
},
{
"ID": "musl-utils@1.2.5-r13",
"Name": "musl-utils",
"Identifier": {
"PURL": "pkg:apk/alpine/musl-utils@1.2.5-r13?arch=aarch64\u0026distro=3.22.8",
"UID": "79cdbe281551d3f7"
},
"Version": "1.2.5-r13",
"Arch": "aarch64",
"SrcName": "musl",
"SrcVersion": "1.2.5-r13",
"Licenses": [
"MIT",
"BSD-2-Clause",
"GPL-2.0-or-later"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"musl@1.2.5-r13",
"scanelf@1.3.8-r1"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:c332ed470c77dfa47d91bf63789b2a072626ca32",
"InstalledFiles": [
"sbin/ldconfig",
"usr/bin/getconf",
"usr/bin/getent",
"usr/bin/iconv",
"usr/bin/ldd"
],
"AnalyzedBy": "apk"
},
{
"ID": "scanelf@1.3.8-r1",
"Name": "scanelf",
"Identifier": {
"PURL": "pkg:apk/alpine/scanelf@1.3.8-r1?arch=aarch64\u0026distro=3.22.8",
"UID": "681ca53ce2c190eb"
},
"Version": "1.3.8-r1",
"Arch": "aarch64",
"SrcName": "pax-utils",
"SrcVersion": "1.3.8-r1",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"musl@1.2.5-r13"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:82fa8fe048b9de6a4679cca0ce6fe01d0eb29816",
"InstalledFiles": [
"usr/bin/scanelf"
],
"AnalyzedBy": "apk"
},
{
"ID": "ssl_client@1.37.0-r20",
"Name": "ssl_client",
"Identifier": {
"PURL": "pkg:apk/alpine/ssl_client@1.37.0-r20?arch=aarch64\u0026distro=3.22.8",
"UID": "3777bfe85f6b40f3"
},
"Version": "1.37.0-r20",
"Arch": "aarch64",
"SrcName": "busybox",
"SrcVersion": "1.37.0-r20",
"Licenses": [
"GPL-2.0-only"
],
"Maintainer": "Sören Tempel \u003csoeren+alpine@soeren-tempel.net\u003e",
"DependsOn": [
"libcrypto3@3.5.9-r0",
"libssl3@3.5.9-r0",
"musl@1.2.5-r13"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:1e06739dccdbae4cc06110f3ea288eec5edb98b6",
"InstalledFiles": [
"usr/bin/ssl_client"
],
"AnalyzedBy": "apk"
},
{
"ID": "zlib@1.3.2-r1",
"Name": "zlib",
"Identifier": {
"PURL": "pkg:apk/alpine/zlib@1.3.2-r1?arch=aarch64\u0026distro=3.22.8",
"UID": "ade68dcaf43890f8"
},
"Version": "1.3.2-r1",
"Arch": "aarch64",
"SrcName": "zlib",
"SrcVersion": "1.3.2-r1",
"Licenses": [
"Zlib"
],
"Maintainer": "Natanael Copa \u003cncopa@alpinelinux.org\u003e",
"DependsOn": [
"musl@1.2.5-r13"
],
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"Digest": "sha1:0763adbc20823d56b1868aec2ceb284b51050010",
"InstalledFiles": [
"usr/lib/libz.so.1",
"usr/lib/libz.so.1.3.2"
],
"AnalyzedBy": "apk"
}
],
"Vulnerabilities": [
{
"VulnerabilityID": "CVE-2026-4738",
"PkgID": "zlib@1.3.2-r1",
"PkgName": "zlib",
"PkgIdentifier": {
"PURL": "pkg:apk/alpine/zlib@1.3.2-r1?arch=aarch64\u0026distro=3.22.8",
"UID": "ade68dcaf43890f8"
},
"InstalledVersion": "1.3.2-r1",
"FixedVersion": "1.4-r0",
"Status": "fixed",
"Layer": {
"Digest": "sha256:fea5b91588ca539ff8a89d7d5df6c6d65d6ab7bd89145ba57f32c302cf02ffbe",
"DiffID": "sha256:d0af45c05d06b9fef7731c3ddeeb7141f22477266bb3895a68d3492af49d191b"
},
"PrimaryURL": "https://avd.aquasec.com/nvd/cve-2026-4738",
"DataSource": {
"ID": "alpine",
"Name": "Alpine Secdb",
"URL": "https://secdb.alpinelinux.org/"
},
"Fingerprint": "sha256:308fbf4f9c89b7c1b1ce4d1fa209a58fd96ffbc7cd4cb07ef87fb1803238e952",
"Title": "Improper Restriction of Operations within the Bounds of a Memory Buffe ...",
"Description": "Improper Restriction of Operations within the Bounds of a Memory Buffer vulnerability in OSGeo gdal (frmts/zlib/contrib/infback9 modules). This vulnerability is associated with program files inftree9.C‎.\n\nThis issue affects gdal: before 3.11.0.",
"Severity": "MEDIUM",
"CweIDs": [
"CWE-119"
],
"VendorSeverity": {
"bitnami": 4,
"julia": 4,
"ubuntu": 2
},
"CVSS": {
"bitnami": {
"V40Vector": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H/E:A/S:P/AU:Y/R:U/V:C/RE:L/U:Amber",
"V40Score": 9.4
},
"julia": {
"V40Vector": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H/E:A/S:P/AU:Y/R:U/V:C/RE:L/U:Amber",
"V40Score": 9.4
}
},
"References": [
"https://github.com/OSGeo/gdal/pull/12244",
"https://github.com/advisories/GHSA-hp6p-5qh5-w9fj",
"https://nvd.nist.gov/vuln/detail/CVE-2026-4738",
"https://www.cve.org/CVERecord?id=CVE-2026-4738"
],
"PublishedDate": "2026-03-24T04:17:29Z",
"LastModifiedDate": "2026-06-17T10:57:09.03Z"
}
]
}
]
}
-7
View File
@@ -1,7 +0,0 @@
exit=0
2026-11-09T19:35:13Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:14Z INFO Detected OS family="alpine" version="3.24.3"
2026-11-09T19:35:14Z INFO [alpine] Detecting vulnerabilities... os_version="3.24" repository="3.24" pkg_num=29
2026-11-09T19:35:14Z INFO Number of language-specific files num=1
2026-11-09T19:35:14Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:14Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-8
View File
@@ -1,8 +0,0 @@
exit=0
2026-11-09T19:35:25Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:30Z INFO Detected OS family="alpine" version="3.24.3"
2026-11-09T19:35:30Z INFO [alpine] Detecting vulnerabilities... os_version="3.24" repository="3.24" pkg_num=33
2026-11-09T19:35:30Z INFO Number of language-specific files num=15
2026-11-09T19:35:30Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:30Z INFO [node-pkg] Detecting vulnerabilities...
2026-11-09T19:35:30Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-7
View File
@@ -1,7 +0,0 @@
exit=0
2026-11-09T19:35:32Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:32Z INFO Detected OS family="debian" version="12.13"
2026-11-09T19:35:32Z INFO [debian] Detecting vulnerabilities... os_version="12" pkg_num=4
2026-11-09T19:35:32Z INFO Number of language-specific files num=1
2026-11-09T19:35:32Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:32Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-7
View File
@@ -1,7 +0,0 @@
exit=0
2026-11-09T19:35:32Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:33Z INFO Detected OS family="debian" version="12.13"
2026-11-09T19:35:33Z INFO [debian] Detecting vulnerabilities... os_version="12" pkg_num=4
2026-11-09T19:35:33Z INFO Number of language-specific files num=1
2026-11-09T19:35:33Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:33Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-6
View File
@@ -1,6 +0,0 @@
exit=0
2026-11-09T19:35:33Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:33Z INFO Detected OS family="alpine" version="3.24.4"
2026-11-09T19:35:33Z INFO [alpine] Detecting vulnerabilities... os_version="3.24" repository="3.24" pkg_num=24
2026-11-09T19:35:33Z INFO Number of language-specific files num=0
2026-11-09T19:35:33Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-7
View File
@@ -1,7 +0,0 @@
exit=0
2026-11-09T19:35:35Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:35Z INFO Detected OS family="alpine" version="3.22.8"
2026-11-09T19:35:35Z INFO [alpine] Detecting vulnerabilities... os_version="3.22" repository="3.22" pkg_num=21
2026-11-09T19:35:35Z INFO Number of language-specific files num=6
2026-11-09T19:35:35Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:35Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-7
View File
@@ -1,7 +0,0 @@
exit=0
2026-11-09T19:35:36Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:36Z INFO Detected OS family="alpine" version="3.24.3"
2026-11-09T19:35:36Z INFO [alpine] Detecting vulnerabilities... os_version="3.24" repository="3.24" pkg_num=28
2026-11-09T19:35:36Z INFO Number of language-specific files num=1
2026-11-09T19:35:36Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:36Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-5
View File
@@ -1,5 +0,0 @@
exit=0
2026-11-09T19:35:38Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:38Z INFO Number of language-specific files num=1
2026-11-09T19:35:38Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:39Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-7
View File
@@ -1,7 +0,0 @@
exit=0
2026-11-09T19:35:40Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:40Z INFO Detected OS family="alpine" version="3.24.4"
2026-11-09T19:35:40Z INFO [alpine] Detecting vulnerabilities... os_version="3.24" repository="3.24" pkg_num=53
2026-11-09T19:35:40Z INFO Number of language-specific files num=1
2026-11-09T19:35:40Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:40Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-5
View File
@@ -1,5 +0,0 @@
exit=0
2026-11-09T19:35:42Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:43Z INFO Number of language-specific files num=2
2026-11-09T19:35:43Z INFO [gobinary] Detecting vulnerabilities...
2026-11-09T19:35:43Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-6
View File
@@ -1,6 +0,0 @@
exit=0
2026-11-09T19:35:44Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:44Z INFO Detected OS family="alpine" version="3.23.7"
2026-11-09T19:35:44Z INFO [alpine] Detecting vulnerabilities... os_version="3.23" repository="3.23" pkg_num=30
2026-11-09T19:35:44Z INFO Number of language-specific files num=0
2026-11-09T19:35:44Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
File diff suppressed because it is too large Load Diff
-8
View File
@@ -1,8 +0,0 @@
exit=0
2026-11-09T19:35:45Z INFO [vuln] Vulnerability scanning is enabled
2026-11-09T19:35:45Z INFO Detected OS family="alpine" version="3.21.10"
2026-11-09T19:35:45Z INFO [alpine] Detecting vulnerabilities... os_version="3.21" repository="3.21" pkg_num=19
2026-11-09T19:35:45Z INFO Number of language-specific files num=0
2026-11-09T19:35:45Z WARN Using severities from other vendors for some vulnerabilities. Read https://trivy.dev/docs/v0.76/guide/scanner/vulnerability#severity-selection for details.
2026-11-09T19:35:45Z WARN This OS version is no longer supported by the distribution family="alpine" version="3.21.10"
2026-11-09T19:35:45Z WARN The vulnerability detection may be insufficient because security updates are not provided
File diff suppressed because it is too large Load Diff
-142
View File
@@ -1,142 +0,0 @@
{
"govulncheck": {
"exit": 0,
"tool": "golang.org/x/vuln/cmd/govulncheck@v1.9.0",
"advisories": {
"symbol": [],
"package_only": [],
"module_only": [
"GO-2026-5932"
]
}
},
"images": [
{
"image": "alpine:3.22@sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f",
"exit": 0,
"file": "image-00.json",
"counts": {
"MEDIUM": 1
}
},
{
"image": "chrislusf/seaweedfs:4.51@sha256:f7a49e3f3972ebed5be2ed4befa4a0c68eb7bdddba6e692d42729ceb545134b8",
"exit": 0,
"file": "image-01.json",
"counts": {
"MEDIUM": 2,
"HIGH": 2,
"UNKNOWN": 1
}
},
{
"image": "grafana/grafana:13.2.5@sha256:9f7aa1e1e3246aade5792d35a738049f7f32f89cd51d1956cf426a4e86268a84",
"exit": 0,
"file": "image-02.json",
"counts": {
"MEDIUM": 103,
"HIGH": 49,
"UNKNOWN": 5,
"LOW": 6
}
},
{
"image": "grafana/loki:3.6.4@sha256:be31579ac047e9f78b81e48f3b69d3af709e7299b431d5aa78bcda43382f9511",
"exit": 0,
"file": "image-03.json",
"counts": {
"UNKNOWN": 5,
"LOW": 7,
"MEDIUM": 45,
"HIGH": 54,
"CRITICAL": 2
}
},
{
"image": "grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38",
"exit": 0,
"file": "image-04.json",
"counts": {
"UNKNOWN": 4,
"HIGH": 2,
"MEDIUM": 3
}
},
{
"image": "haproxy:3.2-alpine@sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
"exit": 0,
"file": "image-05.json",
"counts": {
"MEDIUM": 1
}
},
{
"image": "mtusi-messenger:lab7",
"exit": 0,
"file": "image-06.json",
"counts": {
"MEDIUM": 1,
"UNKNOWN": 5
}
},
{
"image": "openbao/openbao:2.7.2@sha256:5046911075e137e154ce49ab051502f4ec7cf367d484ae4a4dce665d9b90561f",
"exit": 0,
"file": "image-07.json",
"counts": {
"MEDIUM": 6,
"HIGH": 3,
"UNKNOWN": 1
}
},
{
"image": "otel/opentelemetry-collector-contrib:0.164.0@sha256:340c9ca6a36617084c6661bdc4f0fe92b7cda5a805d61673ec8db375fddc522b",
"exit": 0,
"file": "image-08.json",
"counts": {
"HIGH": 2,
"UNKNOWN": 1,
"MEDIUM": 1
}
},
{
"image": "postgres:18-alpine@sha256:123b17998ccaf47e53b502e8c6a1e79afd8f579c6f3eec83c563da026f957395",
"exit": 0,
"file": "image-09.json",
"counts": {
"MEDIUM": 32,
"UNKNOWN": 1,
"CRITICAL": 1,
"HIGH": 25,
"LOW": 3
}
},
{
"image": "prom/prometheus:v3.15.1@sha256:fa3302279710be2f21a8301ec17a8b4f2301fd829bd113839b3b6b02b6f191a2",
"exit": 0,
"file": "image-10.json",
"counts": {
"UNKNOWN": 2,
"HIGH": 2,
"MEDIUM": 2
}
},
{
"image": "rabbitmq:4.3.7-management-alpine@sha256:1528a88eebf2bc4d0ab7e9d5d9bc542e9bdf5e1b105e65848fcf8de5c2186528",
"exit": 0,
"file": "image-11.json",
"counts": {
"MEDIUM": 1
}
},
{
"image": "redis:7.4-alpine@sha256:c5d34a98396a4775e223c74e929162c35c5a2182901ba26b50ade939941ce14b",
"exit": 0,
"file": "image-12.json",
"counts": {
"MEDIUM": 1
}
}
],
"trivy": "aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb"
}
-513
View File
@@ -1,513 +0,0 @@
{
"limitations": [
"Authorized local synthetic stand only; privilege tests use administrator SET ROLE over a local Unix socket.",
"Actual workflow confirms queue processing; standalone consume probe requeues unacknowledged deliveries.",
"Session expiry uses an operator expiry update, not a claim about the default configured TTL."
],
"passed": true,
"project": "mtusi-messenger-lab6",
"results": [
{
"classification": "passed",
"details": {
"wrong_ca": "ca_rejected",
"wrong_hostname": "hostname_rejected"
},
"name": "public_ca_hostname",
"passed": true,
"seconds": 0.027
},
{
"classification": "passed",
"details": {
"absent": {
"classification": "tls_certificate_rejected",
"detail": "TLSV13_ALERT_CERTIFICATE_REQUIRED"
},
"api_wrong_ca_client": {
"classification": "tls_certificate_rejected",
"detail": "TLSV1_ALERT_UNKNOWN_CA"
},
"broker_wrong_ca_client": {
"classification": "tls_certificate_rejected"
},
"collector_absent": {
"classification": "tls_certificate_rejected",
"detail": "TLSV13_ALERT_CERTIFICATE_REQUIRED"
},
"collector_api": {
"classification": "http_response",
"serial": "69BFC8ED94A3176A23706D6B04C535E52DE70F07",
"status": 200
},
"collector_lb": {
"classification": "http_response",
"serial": "69BFC8ED94A3176A23706D6B04C535E52DE70F07",
"status": 403
},
"collector_wrong_ca_client": {
"classification": "tls_certificate_rejected",
"detail": "TLSV1_ALERT_UNKNOWN_CA"
},
"lb": {
"classification": "http_response",
"serial": "1AA48F2C79560EE6255A712C07546A1E2674BD3B",
"status": 200
},
"loki_collector_route": {
"classification": "http_response",
"serial": "02CCFF65B5564F63B1F079BDC113BDC3E09D0A5F",
"status": 403
},
"loki_grafana_route": {
"classification": "http_response",
"serial": "02CCFF65B5564F63B1F079BDC113BDC3E09D0A5F",
"status": 403
},
"otel-collector_api_route": {
"classification": "http_response",
"serial": "69BFC8ED94A3176A23706D6B04C535E52DE70F07",
"status": 403
},
"prometheus_grafana_route": {
"classification": "http_response",
"serial": "0AE5D6A037B34083D50E230753C1303D3A995042",
"status": 403
},
"tempo_prometheus_route": {
"classification": "http_response",
"serial": "2F934D2031A9168BD54E5D27194F5F9B97D10516",
"status": 403
},
"wrong_uri": {
"classification": "tls_certificate_rejected",
"detail": "SSLV3_ALERT_BAD_CERTIFICATE"
}
},
"name": "mtls_and_telemetry_acl",
"passed": true,
"seconds": 5.619
},
{
"classification": "passed",
"details": {
"absent": {
"classification": "tls_certificate_rejected"
},
"offered_mechanisms": {
"classification": "amqp_mechanisms",
"mechanisms": [
"EXTERNAL"
]
},
"relay_consume": {
"classification": "amqp_rejected",
"code": 403
},
"relay_publish": {
"classification": "amqp_allowed",
"mechanisms": [
"EXTERNAL"
]
},
"relay_topology": {
"classification": "amqp_rejected",
"code": 403
},
"worker_consume": {
"classification": "amqp_allowed",
"mechanisms": [
"EXTERNAL"
]
},
"worker_publish": {
"classification": "amqp_rejected",
"code": 403
},
"worker_topology": {
"classification": "amqp_rejected",
"code": 403
},
"wrong_dns": {
"classification": "amqp_rejected",
"code": 403
}
},
"name": "broker_external_acl",
"passed": true,
"seconds": 3.914
},
{
"classification": "passed",
"details": {
"checks": {
"foreign_issue": 403,
"foreign_kv": 403,
"own_kv": 200,
"policy_admin": 403
},
"classification": "passed"
},
"name": "bao_api_policy",
"passed": true,
"seconds": 0.437
},
{
"classification": "passed",
"details": {
"grpc_18333": {
"absent": {
"classification": "tls_certificate_rejected"
},
"api": {
"classification": "tls_certificate_rejected"
},
"operator": {
"classification": "tls_certificate_rejected"
},
"s3": {
"alpn": "h2",
"classification": "tls_channel_established"
},
"worker": {
"classification": "tls_certificate_rejected"
}
},
"limitations": [
"Checks mutual-TLS HTTP/2 channel admission, not a Seaweed administrative gRPC method."
]
},
"name": "seaweed_auxiliary_mtls",
"passed": true,
"seconds": 1.945
},
{
"classification": "passed",
"details": {
"classification": "passed",
"foreign_key": "NOPERM",
"ping": "PONG",
"tls_cache_auth": "allowed"
},
"name": "redis_tls_cache_acl",
"passed": true,
"seconds": 0.412
},
{
"classification": "passed",
"details": {
"api_ddl": "42501",
"api_read_attachments": "allowed",
"api_read_messages": "allowed",
"api_read_sessions": "allowed",
"api_read_users": "allowed",
"relay_ddl": "42501",
"relay_denied_messages_delete": "42501",
"relay_denied_messages_insert": "42501",
"relay_denied_messages_select": "42501",
"relay_denied_messages_update": "42501",
"relay_denied_sessions_delete": "42501",
"relay_denied_sessions_insert": "42501",
"relay_denied_sessions_select": "42501",
"relay_denied_sessions_update": "42501",
"relay_denied_users_delete": "42501",
"relay_denied_users_insert": "42501",
"relay_denied_users_select": "42501",
"relay_denied_users_update": "42501",
"relay_read_attachment_jobs": "allowed",
"relay_read_outbox_messages": "allowed",
"worker_ddl": "42501",
"worker_denied_messages_delete": "42501",
"worker_denied_messages_insert": "42501",
"worker_denied_messages_select": "42501",
"worker_denied_messages_update": "42501",
"worker_denied_sessions_delete": "42501",
"worker_denied_sessions_insert": "42501",
"worker_denied_sessions_select": "42501",
"worker_denied_sessions_update": "42501",
"worker_denied_users_delete": "42501",
"worker_denied_users_insert": "42501",
"worker_denied_users_select": "42501",
"worker_denied_users_update": "42501",
"worker_read_attachment_jobs": "allowed",
"worker_read_attachments": "allowed",
"worker_read_outbox_messages": "allowed"
},
"name": "database_privileges",
"passed": true,
"seconds": 2.329
},
{
"classification": "passed",
"details": {
"checks": {
"api_copy_foreign_bucket_dest": 403,
"api_copy_foreign_bucket_source": 403,
"api_copy_foreign_dest": 403,
"api_copy_foreign_source": 403,
"api_copy_owned": 200,
"api_copy_owned_readback": 200,
"api_final_copy_denied": 403,
"api_final_delete_denied": 403,
"api_final_get": 200,
"api_final_put_denied": 403,
"api_foreign_DELETE": 403,
"api_foreign_GET": 403,
"api_foreign_PUT": 403,
"api_foreign_bucket_DELETE": 403,
"api_foreign_bucket_GET": 403,
"api_foreign_bucket_PUT": 403,
"api_foreign_bucket_list": 403,
"api_foreign_list": 403,
"api_staging_delete": 204,
"api_staging_delete_readback": 404,
"api_staging_get": 200,
"api_staging_list_denied": 403,
"api_staging_put": 200,
"api_staging_put_readback": 200,
"foreign_bucket_create": 200,
"seed_final": 200,
"seed_foreign": 200,
"seed_foreign_bucket": 200,
"seed_staging": 200,
"seed_worker_staging_orphan": 200,
"worker_copy_foreign_bucket_dest": 403,
"worker_copy_foreign_bucket_source": 403,
"worker_copy_foreign_dest": 403,
"worker_copy_foreign_source": 403,
"worker_copy_owned": 200,
"worker_copy_owned_readback": 200,
"worker_final_get": 200,
"worker_final_put": 200,
"worker_final_put_readback": 200,
"worker_foreign_DELETE": 403,
"worker_foreign_GET": 403,
"worker_foreign_PUT": 403,
"worker_foreign_bucket_DELETE": 403,
"worker_foreign_bucket_GET": 403,
"worker_foreign_bucket_PUT": 403,
"worker_foreign_bucket_list": 403,
"worker_foreign_list": 200,
"worker_foreign_metadata_observed": true,
"worker_managed_list": 200,
"worker_orphan_delete": 204,
"worker_orphan_delete_readback": 404,
"worker_staging_cleanup": 204,
"worker_staging_cleanup_readback": 404,
"worker_staging_get": 200
},
"classification": "passed",
"limitations": [
"Seaweed Write grants PUT together with DELETE; cleanup is not delete-only.",
"Worker bucket-level LIST can disclose foreign-prefix metadata within the managed bucket."
]
},
"name": "s3_prefix_acl",
"passed": true,
"seconds": 0.733
},
{
"classification": "passed",
"details": {
"postgres": {
"classification": "rejected",
"detail": "hostssl_required",
"ssl_answer": "S"
},
"redis": {
"classification": "rejected",
"detail": "plaintext_reset"
},
"redis_tls_port": {
"classification": "passed",
"port": "0"
},
"s3": {
"classification": "rejected",
"detail": "https_listener_rejected_http"
},
"s3_foreign_ca": {
"classification": "ca_rejected",
"detail": "verify_code=19"
}
},
"name": "plaintext_refusal",
"passed": true,
"seconds": 1.92
},
{
"classification": "passed",
"details": {
"foreign_chat": 404,
"image_pixel_bound": "rejected",
"invalid_image": 415,
"logout": 401,
"oversize_body": 413,
"persisted_expiration": 401,
"x_user_id": "no_impersonation"
},
"name": "http_acl_logout_expiry_bounds",
"passed": true,
"seconds": 0.214
},
{
"classification": "passed",
"details": {
"attachment_id": "01a1c531-83ba-7adc-96f9-631390aaf0db",
"message_id": "01a1c531-8789-7a2b-ab28-2cdcd2e49aa9",
"status": "ready"
},
"name": "real_async_pipeline",
"passed": true,
"seconds": 0.992
},
{
"classification": "passed",
"details": {
"instances": [
"b5de44cc1680",
"c534d1225a79"
],
"retry_after": [
59,
59,
59,
59,
59
],
"statuses": [
401,
401,
401,
401,
401,
401,
401,
429,
429,
429,
429,
429
]
},
"name": "shared_rate_limit",
"passed": true,
"seconds": 0.196
},
{
"classification": "passed",
"details": {
"containers_scanned": [
"5e3ba57943d6",
"0b631f460215",
"5b0de6ed0103",
"15dd9970ddd4",
"cd7d6970581b",
"11798cd9ae8c",
"b5de44cc1680",
"11f3801cb11f",
"274ce8478fdd",
"c534d1225a79",
"a0c8dd6b20a3",
"7984632bd709",
"158d63b7ac3c",
"f0227fea8781",
"62a070cbf1c7",
"21bab268e79a",
"01c1b15ae56e",
"1da94197b83d",
"c10b6dd1a9cb",
"9bc2d57bbc8a",
"41065fa7a807",
"92a23aef5975",
"1df4bf079b3c"
],
"limitations": [
"Scans retained container logs and Loki streams with service_name; Tempo attributes and historic deleted logs are not text-scanned."
],
"loki_scans": 1,
"sensitive_values_scanned": 24
},
"name": "credential_log_sentinels",
"passed": true,
"seconds": 0.929
},
{
"classification": "passed",
"details": {
"applications": {
"api": [
{
"id": "b5de44cc1680",
"readonly": true,
"running_uid_nonzero": true
},
{
"id": "c534d1225a79",
"readonly": true,
"running_uid_nonzero": true
}
],
"relay": [
{
"id": "274ce8478fdd",
"readonly": true,
"running_uid_nonzero": true
}
],
"worker": [
{
"id": "11f3801cb11f",
"readonly": true,
"running_uid_nonzero": true
}
]
},
"namespace_pairs": {
"broker-admin-tls": "broker",
"collector-tls": "otel-collector",
"grafana-tls": "grafana",
"loki-tls": "loki",
"prometheus-tls": "prometheus",
"s3": "seaweedfs",
"tempo-tls": "tempo"
},
"private_ports": {
"api-replica:8084": "connection_refused",
"broker:15672": "connection_refused",
"broker:15692": "connection_refused",
"broker:5672": "connection_refused",
"grafana:13000": "connection_refused",
"loki:13100": "connection_refused",
"loki:7946": "connection_refused",
"loki:9096": "connection_refused",
"otel-collector:13133": "connection_refused",
"otel-collector:14318": "connection_refused",
"otel-collector:18888": "connection_refused",
"otel-collector:18889": "connection_refused",
"otel-collector:4317": "connection_refused",
"prometheus:19090": "connection_refused",
"relay:8082": "connection_refused",
"seaweedfs:18080": "connection_refused",
"seaweedfs:18888": "connection_refused",
"seaweedfs:19333": "connection_refused",
"seaweedfs:8080": "connection_refused",
"seaweedfs:8181": "connection_refused",
"seaweedfs:8888": "connection_refused",
"seaweedfs:9101": "connection_refused",
"seaweedfs:9333": "connection_refused",
"tempo:13200": "connection_refused",
"tempo:14317": "connection_refused",
"tempo:7946": "connection_refused",
"tempo:9095": "connection_refused",
"worker:8081": "connection_refused"
}
},
"name": "runtime_container_network_isolation",
"passed": true,
"seconds": 2.188
}
],
"study": "lab7-security",
"timestamp": "2026-11-10T11:22:03.202717+00:00"
}
-23
View File
@@ -1,23 +0,0 @@
{
"command": "python3 student-tests/replica_failover.py --action-script scripts/stop-one.sh --base-url https://localhost:8443 --ca-file secrets/lab7/pki/operator/current/ca.crt",
"replicas": [
{
"stopped": "6dc424bc61ca",
"successful_writes": 91,
"failed_attempts": 0,
"first_recovery_seconds": 1.786,
"survivor": "78e96f0ca9d3",
"messages_in_history": 91
},
{
"stopped": "78e96f0ca9d3",
"successful_writes": 100,
"failed_attempts": 0,
"first_recovery_seconds": 0.889,
"survivor": "6dc424bc61ca",
"messages_in_history": 191
}
],
"both_restored": true,
"duplicates_or_loss_observed": false
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-89
View File
@@ -1,89 +0,0 @@
{
"commands": [
{
"built_with": "go1.27.3",
"command": "make lint",
"golangci_lint": "2.15.0",
"result": "0 issues"
},
{
"command": "make unit-test",
"flags": [
"-race",
"-shuffle=on",
"-count=1",
"-timeout=5m"
],
"result": "reported package tests passed"
},
{
"command": "make build",
"image": "mtusi-messenger:lab7",
"image_manifest": "sha256:6445f3422b2d1b393e2e5b28f1f90e3b12d4a417a27991b2ff8bb01780926f2d",
"result": "linux/arm64 image built"
},
{
"command": "make check validate PYTHON=.venv/bin/python",
"result": "offline contract/Python syntax and OpenAPI3.1/JSON Schema validation passed"
},
{
"command": "make test test-security",
"result": "public API scenario passed; trusted HTTPS passed; untrusted CA rejected"
},
{
"command": "make test-lab7",
"evidence": "security.json",
"result": "all 13 live security groups passed"
},
{
"command": "make test-attachments",
"result": "negative attachment checks passed"
},
{
"command": "make test-presign",
"result": "direct HTTPS PUT, queued completion, foreign404, checksum409, oversized403/409, repeated complete idempotent"
},
{
"command": "make test-queue",
"result": "worker/broker downtime, outbox recovery, stack restart and reprocess precedence scenarios passed"
},
{
"command": "make test-idempotency",
"result": "12 parallel replay workers across2replicas create one message; conflicting bodies accept1 and reject11"
},
{
"command": "make test-observability",
"result": "signals, trace/log correlation, labels, Grafana, rules and privacy sentinels passed"
},
{
"command": "make test-persistence ACTION_SCRIPT=scripts/restart.sh",
"evidence": "restart-scope.json",
"result": "confirmed message, complete attachment bytes and existing session preserved",
"seconds": 43.59
},
{
"command": "make test-failover ACTION_SCRIPT=scripts/stop-one.sh",
"evidence": "failover-scope.json",
"failed_attempts": 0,
"first_recovery_seconds": 0.815,
"result": "confirmed data and existing session preserved",
"successful_writes": 92
},
{
"command": "make integration-test",
"evidence": "integration.txt",
"result": "PostgreSQL16.982s and Redis1.239s existing tagged integration suites passed over verified local TLS"
},
{
"command": "python3 scripts/lab7_scan.py",
"evidence": "scans/summary.json",
"result": "all13image scanner exits0; source symbol/package-only findings0, required-module-only GO-2026-5932"
},
{
"command": "targeted missing established S3 readiness object",
"evidence": "readiness.json",
"result": "404; bounded2.000884750s failure; no reseed; original marker and full bytes restored"
}
],
"scope": "Authorized local synthetic stand; no disabled certificate checks."
}
+4 -4
View File
@@ -1,6 +1,6 @@
module mtusi-messenger module mtusi-messenger
go 1.27.3 go 1.27.0
require ( require (
github.com/aws/aws-sdk-go-v2 v1.47.3 github.com/aws/aws-sdk-go-v2 v1.47.3
@@ -32,7 +32,7 @@ require (
go.opentelemetry.io/otel/trace v1.47.0 go.opentelemetry.io/otel/trace v1.47.0
go.uber.org/zap v1.28.0 go.uber.org/zap v1.28.0
go.uber.org/zap/exp v0.3.0 go.uber.org/zap/exp v0.3.0
golang.org/x/crypto v0.58.0 golang.org/x/crypto v0.57.0
golang.org/x/image v0.47.0 golang.org/x/image v0.47.0
golang.org/x/sync v0.24.0 golang.org/x/sync v0.24.0
) )
@@ -134,9 +134,9 @@ require (
go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa // indirect golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa // indirect
golang.org/x/mod v0.41.0 // indirect golang.org/x/mod v0.41.0 // indirect
golang.org/x/net v0.62.0 // indirect golang.org/x/net v0.59.0 // indirect
golang.org/x/sys v0.49.0 // indirect golang.org/x/sys v0.49.0 // indirect
golang.org/x/term v0.47.0 // indirect golang.org/x/term v0.46.0 // indirect
golang.org/x/text v0.43.0 // indirect golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.51.0 // indirect golang.org/x/tools v0.51.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
-6
View File
@@ -315,8 +315,6 @@ go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa h1:QSyA8ishJCyT21kER9KwNt0b7BM3iRK4x9QXhjN5Fdk= golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa h1:QSyA8ishJCyT21kER9KwNt0b7BM3iRK4x9QXhjN5Fdk=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa/go.mod h1:zeBbvyFKDaLwa7CH/zI8KXt7gTl14SF7sO08Pl5jBCM= golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa/go.mod h1:zeBbvyFKDaLwa7CH/zI8KXt7gTl14SF7sO08Pl5jBCM=
golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo= golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
@@ -328,8 +326,6 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
@@ -341,8 +337,6 @@ golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
+17 -88
View File
@@ -1,89 +1,18 @@
# Инфраструктура lab7 # Инфраструктура lab6
## Телеметрия и границы ролей - `otel/collector.yaml` — OTLP receivers, memory_limiter (140 MiB), batch,
bounded Loki/Tempo exporter queues (`sizer: bytes`), Prometheus exporter
`telemetry-gateway/*.cfg` — штатные HAProxy 3.2 gateways в network namespace `:8889`, self-metrics `:8888`, health `:13133`.
соответствующего backend. Только gateway принимает соединения из Docker-сети; - `prometheus/` — scrape config (collector, collector-self, HAProxy, RabbitMQ),
native HTTP, admin, metrics, OTLP и вспомогательный gRPC/gossip bind — loopback. 7d/2GB retention, SLO recording rules and alerts.
Внутренние listeners требуют проверенный client certificate; роль определяется - `loki/loki.yaml` — filesystem, schema v13, 168h retention, OTLP mapping with
точным **CN**, не URI SAN и не переданным HTTP header. Неизвестная CN, даже от only `service.name`/`deployment.environment.name` as index labels.
того же CA, и неразрешённые method/path получают отказ по умолчанию. - `tempo/tempo.yaml` — local storage, OTLP, 72h block retention.
- `grafana/` — provisioned datasources (Prometheus/Loki/Tempo), dashboard
| TLS endpoint | Разрешённая роль и операция | Native loopback | provider and JSON dashboards; admin password only in gitignored
| --- | --- | --- | `secrets/grafana.env`.
| `otel-collector:4318` | `api`/`worker`/`relay`: POST `/v1/traces`, `/v1/metrics`, `/v1/logs` | `14318` | - `rabbitmq/rabbitmq.conf` — per-object Prometheus metrics so `queue` is a
| `otel-collector:8888`, `:8889` | `prometheus`/`operator`: GET `/metrics` | `18888`, `18889` | real label for depth/age panels.
| `otel-collector:13134` | `prometheus`/`operator`: GET `/` (health) | `13133` | - `runbooks/` — DB availability, queue lag, API errors, telemetry backend down.
| `prometheus:9090` | `grafana`: query/labels/series/metadata; `prometheus`: GET metrics/health; `operator`: отдельный query/status allowlist | `19090` | - cAdvisor не используется: контейнерные CPU/RAM приложения снимаются из
| `loki:3100` | `collector`: POST `/otlp/v1/logs` или `/loki/api/v1/push`; `grafana`: query/labels/series/Explore; `prometheus`: GET metrics/ready; `operator`: отдельный read allowlist | `13100` | cgroup v2, брокер — из `rabbitmq_prometheus`; Docker socket не монтируется.
| `tempo:3200` | `grafana`: GET trace/search/tag/TraceQL-metrics/echo; `prometheus`: GET metrics/ready; `operator`: отдельный read allowlist | `13200` |
| `tempo:4437` | только `collector`: OTLP gRPC | `14317` |
| `grafana:3000` | browser HTTPS, без client certificate; штатная аутентификация Grafana | `13000` |
Полные allowlists — в gateway configs. Grafana не получает push/delete/admin,
Collector не получает query API, scrape identity не получает data queries.
Loki/Tempo gateway перезаписывает `X-Scope-OrgID` в `fake`: внешний tenant header
не является полномочием; существующий single-tenant store сохраняется.
Prometheus не включает lifecycle/admin API; даже `operator` не получает
reload/quit/remote-write через gateway. Prometheus buildinfo GET доступен Grafana
для проверки datasource/version; остальные status endpoints — только operator.
У каждого владельца монтируется только его identity readonly в `/run/identity`:
`current/tls.pem`, `tls.crt`, `tls.key`, `ca.crt`, `ca.crl`. Gateways используют
CA/CRL verification, TLS >=1.2, session tickets/cache выключены. Они загружают
сертификаты/CRLs при старте: atomic replacement `current` требует bounded
reload/restart gateway и закрытия старых соединений; обновление файлов само по
себе не доказывает применение CRL/CA rollover. Штатные Collector/Prometheus/
Grafana clients проверяют CA и hostname, отправляют только собственный leaf.
Их native TLS config не объявляется самостоятельной CRL проверкой; lifecycle
должен обновлять trust consumers и разрывать прежние соединения.
Go использует `TLS_VERSION_FILE=/run/identity/current-version`: один bounded
regular-file read выбирает immutable `versions/<name>` сразу для leaf/key/CA/CRL.
Это не native `current` symlink; unreadable/malformed selectors fail closed.
Publisher делает staging selector runtime-readable до atomic rename. `up`
пересоздаёт native gateways даже при reused owners; `revoke` reloads/drains
HAProxy CRL consumers. Offline root CRLs обновляются до последних24h validity.
## Native запуск и сохранённые pipelines
- Prometheus: `--web.listen-address=127.0.0.1:19090`, без
`--web.enable-lifecycle`/`--web.enable-admin-api`; прежние retention flags,
scrape-job names, recording rules и alert tests сохраняются. Все шесть
scrape targets HTTPS/mTLS с identity `prometheus`, broker теперь `:15693`.
- Grafana: `GF_SERVER_HTTP_ADDR=127.0.0.1`, `GF_SERVER_HTTP_PORT=13000`,
`GF_SERVER_PROTOCOL=http`, `GF_SERVER_ROOT_URL=https://localhost:3000/`;
anonymous/auth-proxy login выключены, admin password — только private runtime
file. Backend не публикуется, browser использует TLS gateway.
- Collector: все три OTLP pipelines сохранены; memory limiter 140 MiB, batch
5 с/1024, exporter queues 10 MiB с retry <=30 с. Loki export — HTTPS `/otlp`
(OTLP добавляет `/v1/logs`), Tempo — GRPCS `:4437`; native Collector gRPC OTLP
listener отсутствует. Loopback health не зависит от доступности gateway.
- Loki: filesystem/schema v13, retention 168h, index labels только
`service.name`/`deployment.environment.name`; internal gRPC `127.0.0.1:9096`.
- Tempo: local storage, retention 72h; internal gRPC `127.0.0.1:9095`, gossip
loopback, advertised self-dial addresses loopback. Grafana использует
synchronous trace/search APIs, без внешнего query-gRPC listener.
- Datasource UIDs, dashboards, trace-to-log/derived-field links сохранены.
Tracked `grafana/provisioning/datasources/datasources.yaml` — **template**:
`__LAB7_CA_CERT__`, `__LAB7_CLIENT_CERT__`, `__LAB7_CLIENT_KEY__` заменяются
operator bootstrap только на material роли `grafana`. PEM хранится в
`secureJsonData`, datasource `editable: false`. В Grafana монтируется
сгенерированный private file вне Git, не этот template и не общий directory
с чужими ключами. Для YAML block scalars каждая PEM строка получает тот же
отступ; JSON сериализация как YAML также допустима. Rotation/CA rollover
требует повторного render и restart/reprovision Grafana.
- cAdvisor/Docker socket не используются; CPU/RAM приложения — cgroup v2,
брокерные queue labels — `rabbitmq_prometheus`. Runbooks находятся в `runbooks/`.
Это описание configuration boundaries, не заявление о пройденной проверке.
Совместимость pinned images, все dashboards, wrong-CN/verb/path negatives,
fresh/resumed revocation и отсутствие plaintext bypass проверяются отдельно
интеграционным acceptance driver после сборки всего стенда.
Синтаксис и поля: [HAProxy](https://github.com/haproxy/haproxy/blob/v3.2.0/doc/configuration.txt),
[Collector TLS](https://github.com/open-telemetry/opentelemetry-collector/blob/v0.164.0/config/configtls/README.md),
[Prometheus TLS](https://prometheus.io/docs/prometheus/latest/configuration/#tls_config),
[Grafana provisioning](https://github.com/grafana/grafana/blob/v13.2.4/docs/sources/administration/provisioning/index.md),
[Loki](https://github.com/grafana/loki/blob/v3.6.7/docs/sources/shared/configuration.md),
[Tempo 2.9](https://github.com/grafana/tempo/blob/v2.9.0/docs/sources/tempo/configuration/_index.md).
@@ -4,59 +4,29 @@ datasources:
uid: prometheus uid: prometheus
type: prometheus type: prometheus
access: proxy access: proxy
url: https://prometheus:9090 url: http://prometheus:9090
isDefault: true isDefault: true
editable: false editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tlsSkipVerify: false
serverName: prometheus
secureJsonData:
tlsCACert: |
__LAB7_CA_CERT__
tlsClientCert: |
__LAB7_CLIENT_CERT__
tlsClientKey: |
__LAB7_CLIENT_KEY__
- name: Loki - name: Loki
uid: loki uid: loki
type: loki type: loki
access: proxy access: proxy
url: https://loki:3100 url: http://loki:3100
editable: false editable: false
jsonData: jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tlsSkipVerify: false
serverName: loki
derivedFields: derivedFields:
- datasourceUid: tempo - datasourceUid: tempo
matcherType: label matcherType: label
matcherRegex: trace_id matcherRegex: trace_id
url: "$${__value.raw}" url: "$${__value.raw}"
urlDisplayLabel: Open trace urlDisplayLabel: Open trace
secureJsonData:
tlsCACert: |
__LAB7_CA_CERT__
tlsClientCert: |
__LAB7_CLIENT_CERT__
tlsClientKey: |
__LAB7_CLIENT_KEY__
- name: Tempo - name: Tempo
uid: tempo uid: tempo
type: tempo type: tempo
access: proxy access: proxy
url: https://tempo:3200 url: http://tempo:3200
editable: false editable: false
jsonData: jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tlsSkipVerify: false
serverName: tempo
streamingEnabled:
search: false
metrics: false
tracesToLogsV2: tracesToLogsV2:
datasourceUid: loki datasourceUid: loki
filterByTraceID: true filterByTraceID: true
@@ -64,10 +34,3 @@ datasources:
tags: tags:
- key: service.name - key: service.name
value: service_name value: service_name
secureJsonData:
tlsCACert: |
__LAB7_CA_CERT__
tlsClientCert: |
__LAB7_CLIENT_CERT__
tlsClientKey: |
__LAB7_CLIENT_KEY__
+8 -17
View File
@@ -1,4 +1,4 @@
# Lab7 TLS ingress and mTLS backend; only the authenticated LB URI reaches API. # Load balancer for the lab3 stand (HAProxy, container `lb`).
# #
# Почему активные проверки, а не пассивные: nginx OSS умел только пассивные, и # Почему активные проверки, а не пассивные: nginx OSS умел только пассивные, и
# реплика, которая осталась доступной по сети, но потеряла БД, продолжала получать # реплика, которая осталась доступной по сети, но потеряла БД, продолжала получать
@@ -14,8 +14,6 @@
global global
log stdout format raw local0 log stdout format raw local0
maxconn 2048 maxconn 2048
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
tune.ssl.cachesize 0
defaults defaults
mode http mode http
@@ -63,7 +61,7 @@ backend api_backend
# Слотов больше, чем типовых реплик (1/2/4 в треке 1): свободный слот нужен # Слотов больше, чем типовых реплик (1/2/4 в треке 1): свободный слот нужен
# ещё и сценарию scripts/lb_readiness_check.sh, который поднимает рядом # ещё и сценарию scripts/lb_readiness_check.sh, который поднимает рядом
# «неготовую» реплику. # «неготовую» реплику.
server-template api 8 api-replica:8080 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required verifyhost api-replica sni str(api-replica) check-sni api-replica no-ssl-reuse server-template api 8 api-replica:8080
backend api_health backend api_health
balance leastconn balance leastconn
@@ -73,24 +71,16 @@ backend api_health
http-check send meth GET uri /health/ready http-check send meth GET uri /health/ready
http-check expect status 200 http-check expect status 200
default-server check inter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none default-server check inter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
server-template api 8 api-replica:8080 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required verifyhost api-replica sni str(api-replica) check-sni api-replica no-ssl-reuse server-template api 8 api-replica:8080
frontend https_front frontend http_front
bind *:8443 ssl crt /run/identity/current/tls.pem bind *:80
http-request set-header X-Forwarded-For %[src]
http-request del-header Forwarded
http-request del-header X-User-Id
http-response set-header Strict-Transport-Security "max-age=31536000"
use_backend api_health if { path_beg /health/ } use_backend api_health if { path_beg /health/ }
default_backend api_backend default_backend api_backend
frontend stats_front frontend stats_front
# Только для оператора и доказательств: видно, какие реплики UP/DOWN и почему. # Только для оператора и доказательств: видно, какие реплики UP/DOWN и почему.
bind *:8404 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required bind *:8404
acl known_role ssl_c_s_dn(CN) -m str operator prometheus
acl monitor ssl_c_s_dn(CN) -m str prometheus
http-request deny deny_status 403 unless known_role
http-request deny deny_status 403 if monitor !{ path /metrics }
# Built-in Prometheus exporter (HAProxy built with USE_PROMEX). The edge # Built-in Prometheus exporter (HAProxy built with USE_PROMEX). The edge
# SLI uses backend api_backend; /health/* is routed to api_health and is not # SLI uses backend api_backend; /health/* is routed to api_health and is not
# part of the availability numerator or denominator. # part of the availability numerator or denominator.
@@ -98,4 +88,5 @@ frontend stats_front
stats enable stats enable
stats uri /stats stats uri /stats
stats refresh 2s stats refresh 2s
http-request return status 200 content-type text/plain string ok if { path /healthz } monitor-uri /healthz
no log
+1 -8
View File
@@ -1,13 +1,10 @@
auth_enabled: false auth_enabled: false
server: server:
http_listen_address: 127.0.0.1 http_listen_port: 3100
http_listen_port: 13100
grpc_listen_address: 127.0.0.1
grpc_listen_port: 9096 grpc_listen_port: 9096
common: common:
instance_addr: 127.0.0.1
path_prefix: /loki path_prefix: /loki
storage: storage:
filesystem: filesystem:
@@ -18,10 +15,6 @@ common:
kvstore: kvstore:
store: inmemory store: inmemory
# Any optional gossip traffic remains inside this service namespace.
memberlist:
bind_addr: [127.0.0.1]
schema_config: schema_config:
configs: configs:
- from: 2024-01-01 - from: 2024-01-01
+4 -129
View File
@@ -1,132 +1,7 @@
# OpenBao: bootstrap, policies и PKI lifecycle # OpenBao — реализовать конфигурацию и политики
Pinned OpenBao2.7.2 runs as UID100:1000, **not dev-mode**. NativeHTTPS8200, Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Raftvolume `/openbao/file`, auditvolume `/openbao/audit`; clusterlistener8201
is loopback. `server.hcl` declares TLS1.2+, clientCA and persistentHMAC audit
with `log_raw=false`. Browser/operator endpoint is loopbackHTTPS, not publicadmin.
## Запуск и custody Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
```sh Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
cp .env.example .env
make prepare
make up
make test test-security test-lab7
```
`make up` builds the application, preparesrolefiles, runsvolumeownershipjob,
startsBao, performs firstinit (3shares, threshold2), operatorunseal and scoped
provisioning, createsDB/S3roles/bucket, runsmigrations, startsapps andwaits for
CA/hostname-verifiedHTTPS **and full64KiBS3bodyreadiness**. RunningAPI restart does
not requireunseal. AfterBao restart:
```sh
make bao-unseal
# Or complete namespace-aware storage/application restart:
python3 scripts/securityctl.py restart
```
Offline rootCA/privatekey and `operator-unseal.json` are outsidecheckout:
`~/.local/share/mtusi-lab7/<COMPOSE_PROJECT_NAME>` (0700directory,0600files),
optionally overridden by `LAB7_OPERATOR_STATE`. They are never mounted into
containers. Operatorhost/Dockeraccess is trusted. Protect and back up this state;
losingunsealshares cannot be repaired by readingBao'sencryptedRaftvolume.
Initialroot token is used only for provisioning. After verifyingseparate
operatorcert-auth, bootstraprevokesit, confirms403 and removesit fromstate.
App/worker/relay receive only ownleaf+ownconfidentialKVconfiguration, notroot,
unsealshares, sharedBAO_TOKEN or a staticbootstrapsecret.
## Identity и policies
`securityctl.py` applies KVv2 at `secret/`, `cert/` auth and `pki/`intermediate.
Operator signs anintermediateCSR withoffline root; itsprivatekey remains inside
BaoRaft, not at thehost. Serviceauth binds bothCN and URI`spiffe://mtusi/<role>`.
| Role | ReadableKV | Issuance | Othercapabilities |
| --- | --- | --- | --- |
| api | secret/data/api | pki/issue/api | tokenlookup/renew/revoke-self |
| worker | secret/data/worker | pki/issue/worker | tokenlookup/renew/revoke-self |
| relay | secret/data/relay | pki/issue/relay | tokenlookup/renew/revoke-self |
| Othernative service | None | Itsownpki/issue/<role> | tokenlookup/renew/revoke-self |
| operator | ManagedKVandPKI | Managedroles/issuers | Restrictedlab7policies/certauth/seal/auditinspection; no permanentroot token |
Servicepolicy cannot readforeignKV, issueforeignrole or writepolicy. Live
`make test-lab7` returns ownKV200 andforeignKV/issuer/policyadmin403. KVbackend
passwords/keys remain static until explicitrotation; tokenTTL is not theirTTL.
Cert-auth tokenTTL60s/max300s. Go admission is bounded independently by
actualtokenlease, KVfreshness60s and currentleafNotAfter, with a1s safetymargin.
Renewal/reauth must succeed beforedeadlines; sealed/unavailableBao cannot widen
a cachedlease. A firstcancellation fixes one30s shutdownbudget for allcleanup.
## Leaf publication и renewal
```sh
make pki-issue ROLE=api CERT_TTL=1h
make pki-renew ROLE=api CERT_TTL=1h
make renew-watch ROLE=api CERT_TTL=1h
```
NormalleafTTL1h/max24h. Watcher uses ownservicecert-auth and renews at half of
remaininglifetime. Allcertificate/key/CA/CRL files are prepared in immutable
`pki/<role>/versions/<name>` with runtime-readableownership. Nativeconsumers
use `current`; Go uses one atomicregular `current-version` selector. TLSfile
settings still namecurrentbasenames; `TLS_VERSION_FILE` identifies theselector.
Go cannot mixfiles or fail because a hot-swap traversed thesymlink. Invalid,
missing, stale or revokedmaterial remains fail-closed; no insecure/cachefallback.
Go hotloadsleaf/CRL; CAtrustchanges restartprocesses. NativeHAProxy, PostgreSQL,
S3, RabbitMQ, Collector/Grafana clients use explicitreload/recreate paths. A shared
namespaceconsumer is recreated against actualowner afterownerrestart. `up`
also reappliesnativegateways whenownercontainers are reused.
## Отзыв, staticsecret и CArollover
```sh
# Issue/reload the replacement before revoking itsoldserial:
python3 scripts/securityctl.py revoke lb --serial OLD_SERIAL
python3 scripts/securityctl.py rotate-secret worker
python3 scripts/securityctl.py ca-rollover --phase prepare
python3 scripts/securityctl.py ca-rollover --phase issue
python3 scripts/securityctl.py ca-rollover --phase retire
python3 scripts/securityctl.py audit-summary
```
Revocation publishesissuerCRLs toallroles/Baoauth, then reloads anddrains native
HAProxy consumers. Go validates CRLissuer/signature/ThisUpdate/NextUpdate/serial
for everyissuer, includingroot-issuedintermediateCRL. Offline rootCRLs refresh
before their final24h. This does not claim revocation of RabbitMQprincipal from
CRL alone: compromise requires user/connection closure and token/credential/auth
role disable as documented inthreatmodel.
WorkerS3rotation changesonlyitskey, updatesownKV, restartsS3+worker withoutimage
build andchecksnewqueuedattachmentprocessing. Oldkey must return403.
CAprepare retainsold/newCA+CRLtrust; issue switchesissuer andallmanagedleaves;
retire removesoldCA/issuer/authCRLs. Nativeconsumers reload/drain at eachphase.
No statement of zero-downtimeCArollover: errors/recovery are measured underload.
## Recovery и безопасная остановка
```sh
python3 scripts/securityctl.py recover openbao
python3 scripts/securityctl.py recover api
make up
make down
```
ExpiredBao/operatortransport can be replaced byofflineoperatorleaf for verified
restart/unseal, then a restrictedBao-issuedleaf. Never disableCAverification.
`make down` preservesRaft/applicationvolumes andoperatorstate. Intentional deletion
of **your syntheticstand data**: `docker compose --env-file .env down --volumes`;
it does not deleteofflineoperatorstate, which must be managed separately and
never reused accidentally with unrelatedvolumes.
`make test-pki` executes3freshisolatedprojects with20s APIleaves, renewal/expiry,
oldleafrevoke, workerkeyrotation, CAprepare/issue/retire, telemetry/nativeTLS checks
and retaineddata. Cleanup is restricted to itsgeneratedproject/volumes/operator
state; existinglab6volumes are not removed. Fullresults/limitations belong in
[REPORT](../../REPORT.md), [trustmatrix](../../contracts/trust-matrix.md) and
`evidence/lab7/track2.json`.
-28
View File
@@ -1,28 +0,0 @@
ui = true
api_addr = "https://openbao:8200"
cluster_addr = "https://127.0.0.1:8201"
storage "raft" {
path = "/openbao/file"
node_id = "mtusi-lab7"
performance_multiplier = 1
}
listener "tcp" {
address = "0.0.0.0:8200"
cluster_address = "127.0.0.1:8201"
tls_cert_file = "/run/identity/current/tls.crt"
tls_key_file = "/run/identity/current/tls.key"
tls_client_ca_file = "/run/identity/current/ca.crt"
tls_min_version = "tls12"
tls_disable_client_certs = false
tls_require_client_cert = true
}
audit "file" "file" {
description = "Persistent protected lab7 operator and service audit"
options {
file_path = "/openbao/audit/audit.log"
log_raw = "false"
}
}
+10 -21
View File
@@ -1,24 +1,13 @@
# OTel Collector # OTel Collector
`collector.yaml` сохраняет traces/metrics/logs pipelines. API/worker/relay шлют `collector.yaml` — единственный OTLP-приёмник стенда. API/worker/relay шлют
OTLP HTTP через mTLS gateway `otel-collector:4318`: только authenticated CN traces/metrics/logs по HTTP `:4318`; Collector экспортирует:
`api`, `worker`, `relay` и POST `/v1/traces`, `/v1/metrics`, `/v1/logs`. - метрики — pull-exporter Prometheus `:8889` (Prometheus scrape);
Native receiver — `127.0.0.1:14318`; отдельного gRPC receiver нет. - логи — OTLP HTTP в Loki `/otlp`;
- трассы — OTLP gRPC в Tempo `:4317`.
Collector экспортирует: `memory_limiter` ограничивает 140 MiB, batch — 5 с/1024, очереди Loki/Tempo
- метрики — loopback pull-exporter `18889`, через mTLS gateway `:8889`; ограничены 10 MiB (`sizer: bytes`) и retry не дольше 30 с. Self-metrics
- логи — HTTPS/mTLS в `https://loki:3100/otlp` (итоговый `/otlp/v1/logs`); Collector отдаются на `:8888` отдельным scrape-job. OTLP-порты не публикуются
- трассы — GRPCS/mTLS в `tempo:4437`, где допускается только CN `collector`. на host; Collector подключён к `default` и `observability`, backend'ы — только
к `observability`. TLS/auth относятся к lab7.
Exporters используют own identity `current/{ca.crt,tls.crt,tls.key}` в readonly
`/run/identity`. Проверка CA/hostname не отключается. Native self-metrics —
`127.0.0.1:18888`, health — `127.0.0.1:13133`; mTLS gateways — `:8888`
(GET `/metrics`) и `:13134` (GET `/`), только CN `prometheus`/`operator`.
Native plaintext endpoints не публикуются и недоступны соседним namespaces.
`memory_limiter` — 140 MiB, batch — 5 с/1024. Loki/Tempo очереди ограничены
10 MiB (`sizer: bytes`), retry не дольше 30 с; отказ телеметрии не должен
блокировать business readiness. Gateway ACL/TLS config находятся в
`../telemetry-gateway/collector.cfg`; namespace mounts/restarts и lifecycle
trust consumers выполняет operator orchestration. Конфигурация не заменяет
live проверки доставки трёх signals, wrong-CN rejection и revocation.
+10 -16
View File
@@ -1,8 +1,10 @@
receivers: receivers:
otlp: otlp:
protocols: protocols:
grpc:
endpoint: 0.0.0.0:4317
http: http:
endpoint: 127.0.0.1:14318 endpoint: 0.0.0.0:4318
processors: processors:
memory_limiter: memory_limiter:
@@ -18,7 +20,7 @@ processors:
exporters: exporters:
# Pull-based: no sending_queue/retry for this exporter. # Pull-based: no sending_queue/retry for this exporter.
prometheus: prometheus:
endpoint: 127.0.0.1:18889 endpoint: 0.0.0.0:8889
translation_strategy: UnderscoreEscapingWithSuffixes translation_strategy: UnderscoreEscapingWithSuffixes
resource_constant_labels: resource_constant_labels:
included: included:
@@ -27,12 +29,7 @@ exporters:
- deployment.environment.name - deployment.environment.name
- service.version - service.version
otlp_http/loki: otlp_http/loki:
endpoint: https://loki:3100/otlp endpoint: http://loki:3100/otlp
tls:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: "1.2"
sending_queue: sending_queue:
enabled: true enabled: true
sizer: bytes sizer: bytes
@@ -45,12 +42,9 @@ exporters:
max_elapsed_time: 30s max_elapsed_time: 30s
timeout: 5s timeout: 5s
otlp_grpc/tempo: otlp_grpc/tempo:
endpoint: tempo:4437 endpoint: tempo:4317
tls: tls:
ca_file: /run/identity/current/ca.crt insecure: true
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: "1.2"
sending_queue: sending_queue:
enabled: true enabled: true
sizer: bytes sizer: bytes
@@ -65,7 +59,7 @@ exporters:
extensions: extensions:
health_check: health_check:
endpoint: 127.0.0.1:13133 endpoint: 0.0.0.0:13133
service: service:
extensions: [health_check] extensions: [health_check]
@@ -75,8 +69,8 @@ service:
- pull: - pull:
exporter: exporter:
prometheus: prometheus:
host: 127.0.0.1 host: 0.0.0.0
port: 18888 port: 8888
pipelines: pipelines:
traces: traces:
receivers: [otlp] receivers: [otlp]
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
set -eu
# PostgreSQL requires its private key to be owned by postgres and mode 0600.
# The role mount remains read-only; this copy is in the container's tmpfs.
umask 077
cp /run/identity/current/tls.key /tmp/postgres.key
chmod 600 /tmp/postgres.key
exec /usr/local/bin/docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_cert_file=/run/identity/current/tls.crt \
-c ssl_key_file=/tmp/postgres.key \
-c ssl_ca_file=/run/identity/current/ca.crt \
-c hba_file=/etc/postgresql/pg_hba.conf \
-c password_encryption=scram-sha-256 \
-c log_statement=none
-7
View File
@@ -1,7 +0,0 @@
# Only the operator inside this container can use the local Unix socket.
# No PostgreSQL socket directory is mounted into application containers.
local all all trust
hostnossl all all 0.0.0.0/0 reject
hostnossl all all ::/0 reject
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
+1 -37
View File
@@ -7,58 +7,22 @@ rule_files:
scrape_configs: scrape_configs:
- job_name: otel-collector - job_name: otel-collector
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs: static_configs:
- targets: ["otel-collector:8889"] - targets: ["otel-collector:8889"]
- job_name: otel-collector-self - job_name: otel-collector-self
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs: static_configs:
- targets: ["otel-collector:8888"] - targets: ["otel-collector:8888"]
- job_name: haproxy - job_name: haproxy
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
metrics_path: /metrics metrics_path: /metrics
static_configs: static_configs:
- targets: ["lb:8404"] - targets: ["lb:8404"]
- job_name: rabbitmq - job_name: rabbitmq
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs: static_configs:
- targets: ["broker:15693"] - targets: ["broker:15692"]
- job_name: loki - job_name: loki
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
static_configs: static_configs:
- targets: ["loki:3100"] - targets: ["loki:3100"]
- job_name: tempo - job_name: tempo
scheme: https
tls_config:
ca_file: /run/identity/current/ca.crt
cert_file: /run/identity/current/tls.crt
key_file: /run/identity/current/tls.key
min_version: TLS12
metrics_path: /metrics metrics_path: /metrics
static_configs: static_configs:
- targets: ["tempo:3200"] - targets: ["tempo:3200"]
-31
View File
@@ -1,31 +0,0 @@
global
log stdout format raw local0
maxconn 256
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
timeout connect 3s
timeout client 10s
timeout server 10s
frontend operator_management
bind *:15671 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl operator ssl_c_s_dn(CN) -m str operator
http-request deny deny_status 403 unless operator
default_backend management_loopback
backend management_loopback
server management 127.0.0.1:15672
frontend prometheus_scrape
bind *:15693 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl monitor ssl_c_s_dn(CN) -m str prometheus operator
http-request deny deny_status 403 unless monitor
http-request deny deny_status 403 unless { method GET } { path /metrics }
default_backend metrics_loopback
backend metrics_loopback
server metrics 127.0.0.1:15692
-1
View File
@@ -1 +0,0 @@
[rabbitmq_management,rabbitmq_prometheus,rabbitmq_auth_mechanism_ssl].
+2 -23
View File
@@ -1,24 +1,3 @@
# Native AMQP TLS, no plaintext or password-mechanism fallback. # Per-queue Prometheus series: the default exporter aggregates queues, but the
listeners.tcp = none # lab dashboard and oldest/queue-depth alert need the queue label.
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/identity/current/ca.crt
ssl_options.certfile = /run/identity/current/tls.crt
ssl_options.keyfile = /run/identity/current/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
auth_mechanisms.1 = EXTERNAL
ssl_cert_login_from = subject_alternative_name
ssl_cert_login_san_type = dns
ssl_cert_login_san_index = 0
definitions.import_backend = local_filesystem
definitions.local.path = /run/backend/definitions.json
# Admin/scrape transports never leave this container's shared loopback boundary.
management.tcp.ip = 127.0.0.1
management.tcp.port = 15672
prometheus.tcp.ip = 127.0.0.1
prometheus.tcp.port = 15692
prometheus.return_per_object_metrics = true prometheus.return_per_object_metrics = true
-15
View File
@@ -1,15 +0,0 @@
bind 0.0.0.0
port 0
tls-port 6379
tls-cert-file /run/identity/current/tls.crt
tls-key-file /run/identity/current/tls.key
tls-ca-cert-file /run/identity/current/ca.crt
tls-auth-clients no
tls-protocols "TLSv1.2 TLSv1.3"
aclfile /run/backend/users.acl
dir /data
appendonly yes
appendfsync everysec
save 60 1
maxmemory 64mb
maxmemory-policy allkeys-lru
+21 -70
View File
@@ -1,76 +1,27 @@
# SeaweedFS identities and recovery # SeaweedFS identities
The pinned SeaweedFS 4.51 image runs as one logical `s3` role: the `infra/s3/s3.json` is mounted read-only into the `seaweedfs` container and is
`seaweedfs` container owns the network namespace and persistent volume; the single source of truth for S3 credentials and permissions.
the `s3` container shares that namespace and serves native HTTPS.
Do not downgrade to 3.80: its COPY authorization allowed foreign-source reads.
Owned COPY plus forbidden foreign-source/destination COPY checks remain required.
`infra/s3/s3.json` declares permissions, not credentials. `securityctl.py` - `admin` is used only by the one-shot `s3-init` service (bucket creation and
renders operator-local credentials into the read-only `/run/backend/s3.json` probing). It is never given to the API and must not be placed in `.env`:
mount of `s3`. Only `s3-init` and the host operator use the operator identity the API service loads `.env` as an environment file. Compose supplies the
as clients; application processes receive only their own credentials. synthetic admin values to `s3-init` directly.
- `app` is used by the API and by presigned uploads. It can read/write only
`messenger-attachments/attachments/*` and `messenger-attachments/staging/*`,
and list the bucket for the orphan sweeper.
- `operator` creates the application bucket and maintains the recovery sentinel. The credentials are synthetic values for the local stand. `.env.example`
- `api` reads attachment/staging objects and writes staging objects only. carries the same values for the API and `scripts/check_s3_creds.py` fails the
- `worker` reads/writes attachment/staging objects and lists the application offline check if they drift. Replace them in `.env` for any non-local run.
bucket. Bucket-level LIST can disclose foreign-prefix metadata; Write also
permits DELETE within the allowed prefixes.
## Listener isolation Verify manually:
| Listener | Binding and policy | ```sh
| --- | --- | # anonymous requests are denied
| S3 HTTPS 8333 | Native TLS; SigV4 credentials and prefix ACLs. Host publication is loopback-only. | docker compose exec -T seaweedfs \
| S3 auxiliary gRPC 18333 | Shared namespace; mTLS trusts the role CA and permits only CN `s3`. | wget -qO- http://127.0.0.1:8333/messenger-attachments/attachments/missing
| Master HTTP 9333, filer HTTP 8888, volume HTTP 8080 | Namespace loopback only; not published. |
| Master gRPC 19333, filer gRPC 18888, volume gRPC 18080 | Namespace loopback only, with the same CN `s3` mTLS restriction. |
| Iceberg HTTP 8181, Lance HTTP 9101 | Disabled by `-port.iceberg=0` and `-port.lance=0`; absence must be probed, not excluded from isolation checks. |
The three internal gRPC Unix sockets stay in the owner's private `/tmp`. # the app identity cannot write outside its prefixes
The S3 HTTP Unix socket stays in the S3 container's private `/tmp`. docker compose run --rm s3-init # probes this and exits non-zero on violation
No additional PKI role, client allowance, or certificate SAN is needed. ```
Auxiliary 18333 is not an HTTP readiness port: test TLS rejection for
`api`, `worker`, and `operator`, and successful mTLS only for `s3`.
Flags were obtained from the pinned binary with `weed s3 -help` and
`weed server -help`. The configured filer address uses SeaweedFS's explicit
HTTP/gRPC form, `127.0.0.1:8888.18888`, matching the master discovery registry.
The shipped [address parser](https://github.com/seaweedfs/seaweedfs/blob/ffa87c25f/weed/pb/server_address.go)
supports this form. The
[discovery implementation](https://github.com/seaweedfs/seaweedfs/blob/ffa87c25f/weed/wdclient/filer_client.go)
compares raw address spellings and refreshes every five minutes; removing
`127.0.0.1:8888` when discovering its explicit-gRPC equivalent does not mean
that no filer remains.
## Persistent body readiness
The filer's `/healthz` and the public API's DB/OpenBao health cannot prove that
previously stored volume bytes are readable. In the observed restart, S3
started before master leadership and volume topology had recovered.
`Controller.wait_s3()` uses the operator CA, verifies `localhost`, presents
the operator leaf, and signs requests for the published HTTPS S3 endpoint.
It creates exactly one random `operator-readiness/<key>` object in the
configured application bucket on first initialization. Its 64 KiB body forces
volume-backed storage rather than a metadata-only/HEAD probe. Expected bytes
and establishment state live in private `LAB7_OPERATOR_STATE/s3-readiness.json`.
The application identities cannot read, overwrite, or delete this prefix.
After establishment, readiness performs GET and full byte comparison only:
it never rewrites a missing object or reseeds a volume. Missing/unavailable
storage is retried within the readiness deadline; changed bytes or permanent
authorization errors fail the operation. Network operations use five-second
timeouts and body reads are size-capped and deadline-checked.
`wait_ready()` requires this body check before public HTTPS health succeeds.
Store restart first checks the old sentinel, restarts owners, recreates
shared-namespace consumers, checks old bytes again, then restarts applications.
This preserves the existing volumes and does not retry or alter public tests.
Required targeted verification after applying configuration: retain an uploaded
attachment, perform the operator restart hook, read its complete body once,
then compare it byte-for-byte. Also exercise a new staging upload/async COPY,
the existing COPY ACL matrix, auxiliary listener isolation, and the failure
case where an established readiness object is unavailable. Do not remove the
private readiness state to make a persistence check pass.
+8 -10
View File
@@ -1,19 +1,17 @@
{ {
"identities": [ "identities": [
{ {
"name": "operator", "name": "admin",
"credentials": [
{"accessKey": "lab4admin", "secretKey": "lab4admin-secret"}
],
"actions": ["Admin", "Read", "Write", "List", "Tagging"] "actions": ["Admin", "Read", "Write", "List", "Tagging"]
}, },
{ {
"name": "api", "name": "app",
"actions": [ "credentials": [
"Read:messenger-attachments/attachments/*", {"accessKey": "lab4app", "secretKey": "lab4app-secret"}
"Read:messenger-attachments/staging/*", ],
"Write:messenger-attachments/staging/*"
]
},
{
"name": "worker",
"actions": [ "actions": [
"Read:messenger-attachments/attachments/*", "Read:messenger-attachments/attachments/*",
"Write:messenger-attachments/attachments/*", "Write:messenger-attachments/attachments/*",
-35
View File
@@ -1,35 +0,0 @@
# One logical s3 role: HTTP 9333/8888/8080 and gRPC 19333/18888/18080
# stay on namespace loopback. S3 HTTPS 8333 is published only on host loopback.
# Auxiliary gRPC 18333 requires mTLS CN s3; Iceberg 8181 and Lance 9101
# are disabled by the standalone S3 command, not hidden by test exclusions.
[grpc]
ca = "/run/identity/current/ca.crt"
[grpc.master]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.volume]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.filer]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.s3]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
allowed_commonNames = "s3"
[grpc.client]
cert = "/run/identity/current/tls.crt"
key = "/run/identity/current/tls.key"
[access]
ui = false
[filer.expose_directory_metadata]
enabled = false
-69
View File
@@ -1,69 +0,0 @@
# HAProxy 3.2; shares only the Collector network namespace.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend collector_ingest
bind :4318 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
# The authenticated certificate CN, never an HTTP header, is the role.
acl writer ssl_c_s_dn(CN) -m str api worker relay
acl write_method method POST
acl write_path path -m str /v1/traces /v1/metrics /v1/logs
http-request allow if writer write_method write_path
http-request deny deny_status 403
default_backend collector_otlp
frontend collector_metrics
bind :8888 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl reader ssl_c_s_dn(CN) -m str prometheus operator
acl read_method method GET
acl metrics_path path -m str /metrics
http-request allow if reader read_method metrics_path
http-request deny deny_status 403
default_backend collector_self_metrics
frontend application_metrics
bind :8889 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl reader ssl_c_s_dn(CN) -m str prometheus operator
acl read_method method GET
acl metrics_path path -m str /metrics
http-request allow if reader read_method metrics_path
http-request deny deny_status 403
default_backend collector_application_metrics
frontend collector_health
# 13133 is already the private receiver; the TLS gateway uses 13134.
bind :13134 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl reader ssl_c_s_dn(CN) -m str prometheus operator
acl read_method method GET
acl health_path path -m str /
http-request allow if reader read_method health_path
http-request deny deny_status 403
default_backend collector_private_health
backend collector_otlp
server local 127.0.0.1:14318
backend collector_self_metrics
server local 127.0.0.1:18888
backend collector_application_metrics
server local 127.0.0.1:18889
backend collector_private_health
server local 127.0.0.1:13133
-36
View File
@@ -1,36 +0,0 @@
# HAProxy 3.2 public browser ingress; Grafana enforces its normal user auth.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
timeout tunnel 30s
frontend grafana_browser_https
# Browsers verify the server certificate; no client certificate is needed.
bind :3000 ssl crt /run/identity/current/tls.pem
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-request set-header X-Forwarded-Port 3000
# No auth-proxy identity may be supplied by a browser.
http-request del-header X-WEBAUTH-USER
http-request del-header X-WEBAUTH-EMAIL
http-request del-header X-WEBAUTH-NAME
http-response set-header Strict-Transport-Security "max-age=31536000"
default_backend grafana_private
backend grafana_private
server local 127.0.0.1:13000
-56
View File
@@ -1,56 +0,0 @@
# HAProxy 3.2; Loki HTTP and gRPC remain on loopback.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend loki_https
bind :3100 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl collector ssl_c_s_dn(CN) -m str collector
acl grafana ssl_c_s_dn(CN) -m str grafana
acl prometheus ssl_c_s_dn(CN) -m str prometheus
acl operator ssl_c_s_dn(CN) -m str operator
acl read_method method GET
acl write_method method POST
acl query_method method GET POST
acl ingest_path path -m str /otlp/v1/logs /loki/api/v1/push
acl query_path path -m str /loki/api/v1/query /loki/api/v1/query_range /loki/api/v1/labels /loki/api/v1/series
acl label_values path -m reg ^/loki/api/v1/label/[A-Za-z_][A-Za-z0-9_]*/values$
acl explore_path path -m str /loki/api/v1/index/stats /loki/api/v1/index/volume /loki/api/v1/index/volume_range /loki/api/v1/patterns /loki/api/v1/detected_fields /loki/api/v1/detected_labels
acl field_values path -m reg ^/loki/api/v1/detected_field/[A-Za-z_][A-Za-z0-9_]*/values$
acl health_path path -m str /metrics /ready
acl status_path path -m str /loki/api/v1/status/buildinfo /config /services /ring
# Preserve the existing single-tenant store; a client cannot select a tenant.
http-request set-header X-Scope-OrgID fake
http-request allow if collector write_method ingest_path
http-request allow if grafana query_method query_path
http-request allow if grafana read_method label_values
http-request allow if grafana read_method explore_path
http-request allow if grafana read_method field_values
http-request allow if prometheus read_method health_path
http-request allow if operator query_method query_path
http-request allow if operator read_method label_values
http-request allow if operator read_method explore_path
http-request allow if operator read_method field_values
http-request allow if operator read_method health_path
http-request allow if operator read_method status_path
# Collector cannot query; Grafana cannot push, delete or administer.
http-request deny deny_status 403
default_backend loki_private
backend loki_private
server local 127.0.0.1:13100
-46
View File
@@ -1,46 +0,0 @@
# HAProxy 3.2; Prometheus must listen only on 127.0.0.1:19090.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend prometheus_https
bind :9090 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl grafana ssl_c_s_dn(CN) -m str grafana
acl prometheus ssl_c_s_dn(CN) -m str prometheus
acl operator ssl_c_s_dn(CN) -m str operator
acl read_method method GET
acl query_method method GET POST
acl query_path path -m str /api/v1/query /api/v1/query_range /api/v1/labels /api/v1/series /api/v1/metadata
acl label_values path -m reg ^/api/v1/label/[A-Za-z_][A-Za-z0-9_]*/values$
acl buildinfo_path path -m str /api/v1/status/buildinfo
acl health_path path -m str /metrics /-/healthy /-/ready
acl status_path path -m str /api/v1/status/buildinfo /api/v1/status/runtimeinfo /api/v1/status/flags /api/v1/status/config /api/v1/status/tsdb /api/v1/targets /api/v1/rules /api/v1/alerts
http-request allow if grafana query_method query_path
http-request allow if grafana read_method label_values
http-request allow if grafana read_method buildinfo_path
http-request allow if prometheus read_method health_path
http-request allow if operator query_method query_path
http-request allow if operator read_method label_values
http-request allow if operator read_method health_path
http-request allow if operator read_method status_path
# No role gets reload, quit, admin, federation, remote-write or OTLP writes.
http-request deny deny_status 403
default_backend prometheus_private
backend prometheus_private
server local 127.0.0.1:19090
-66
View File
@@ -1,66 +0,0 @@
# HAProxy 3.2; only the collector principal can use the OTLP gRPC gateway.
global
log stdout format raw local0
maxconn 512
hard-stop-after 30s
tune.ssl.cachesize 0
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults tempo_http_defaults
mode http
log global
log-format "%ST %Tt %b"
option dontlognull
option http-server-close
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 5s
timeout http-keep-alive 2s
frontend tempo_https
bind :3200 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required
acl grafana ssl_c_s_dn(CN) -m str grafana
acl prometheus ssl_c_s_dn(CN) -m str prometheus
acl operator ssl_c_s_dn(CN) -m str operator
acl read_method method GET
acl query_path path -m str /api/search /api/search/tags /api/v2/search/tags /api/metrics/query /api/metrics/query_range /api/echo
acl trace_path path -m reg ^/api/(v2/)?traces/[0-9a-fA-F]{1,32}$
acl tag_values path -m reg ^/api/(v2/)?search/tag/[A-Za-z0-9_.:-]+/values$
acl health_path path -m str /metrics /ready
acl status_path path -m str /status /api/status/buildinfo
http-request set-header X-Scope-OrgID fake
http-request allow if grafana read_method query_path
http-request allow if grafana read_method trace_path
http-request allow if grafana read_method tag_values
http-request allow if prometheus read_method health_path
http-request allow if operator read_method query_path
http-request allow if operator read_method trace_path
http-request allow if operator read_method tag_values
http-request allow if operator read_method health_path
http-request allow if operator read_method status_path
# The HTTP listener has no collector write, admin or alternate gRPC route.
http-request deny deny_status 403
default_backend tempo_private_http
backend tempo_private_http
server local 127.0.0.1:13200
# Separate defaults prevent inheriting HTTP options or HTTP log fields in TCP.
defaults tempo_grpc_defaults
mode tcp
log global
log-format "%Tt %b"
option dontlognull
timeout connect 2s
timeout client 30s
timeout server 30s
frontend tempo_otlp_tls
bind :4437 ssl crt /run/identity/current/tls.pem ca-file /run/identity/current/ca.crt crl-file /run/identity/current/ca.crl verify required alpn h2
acl collector ssl_c_s_dn(CN) -m str collector
tcp-request content reject unless collector
default_backend tempo_private_otlp
backend tempo_private_otlp
server local 127.0.0.1:14317
+4 -27
View File
@@ -1,38 +1,15 @@
server: server:
http_listen_address: 127.0.0.1 http_listen_port: 3200
http_listen_port: 13200
grpc_listen_address: 127.0.0.1
grpc_listen_port: 9095 grpc_listen_port: 9095
memberlist:
bind_addr: [127.0.0.1]
distributor: distributor:
ring:
instance_addr: 127.0.0.1
receivers: receivers:
otlp: otlp:
protocols: protocols:
grpc: grpc:
endpoint: 127.0.0.1:14317 endpoint: 0.0.0.0:4317
http:
ingester: endpoint: 0.0.0.0:4318
lifecycler:
address: 127.0.0.1
metrics_generator:
ring:
instance_addr: 127.0.0.1
querier:
frontend_worker:
frontend_address: 127.0.0.1:9095
query_frontend:
search:
default_result_limit: 20
max_result_limit: 1000
max_duration: 24h
storage: storage:
trace: trace:
+125 -70
View File
@@ -1,27 +1,26 @@
// Package broker provides confirmed publishing and consumption over certificate- // Package broker owns the RabbitMQ topology, confirmed publishing and the
// authenticated AMQP. The operator owns topology; PostgreSQL owns business state. // consumer loop. Business state never lives here: PostgreSQL is the source of
// truth for jobs and the outbox.
package broker package broker
import ( import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"net/url"
"sync" "sync"
"time" "time"
amqp "github.com/rabbitmq/amqp091-go" amqp "github.com/rabbitmq/amqp091-go"
"mtusi-messenger/internal/domain" "mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/tlsconfig"
) )
type Config struct { type Config struct {
URL string URL string
Role string
Producer bool
Exchange string Exchange string
DLX string
Queue string Queue string
DLQ string
ConnectTimeout time.Duration ConnectTimeout time.Duration
ConfirmTimeout time.Duration ConfirmTimeout time.Duration
Heartbeat time.Duration Heartbeat time.Duration
@@ -34,85 +33,135 @@ type Client struct {
conn *amqp.Connection conn *amqp.Connection
publisher *amqp.Channel publisher *amqp.Channel
returns chan amqp.Return mu sync.Mutex
closeOnce sync.Once returns chan amqp.Return
closeErr error closed chan *amqp.Error
} }
// Dial connects using EXTERNAL only. Relay gets a confirm-mode publisher; // Dial connects, declares the durable topology idempotently and opens a
// worker opens consumer channels only when Consume is called. // confirm-mode publisher channel.
func Dial(cfg Config) (*Client, error) { func Dial(cfg Config) (*Client, error) {
endpoint, err := url.Parse(cfg.URL) if cfg.URL == "" {
if err != nil || endpoint.Scheme != "amqps" || endpoint.Hostname() == "" || endpoint.User != nil { return nil, errors.New("broker url is empty")
return nil, errors.New("broker: url must be amqps without credentials")
}
if endpoint.RawQuery != "" || endpoint.Fragment != "" {
return nil, errors.New("broker: url query and fragment are not permitted")
}
switch cfg.Role {
case "relay":
if !cfg.Producer || cfg.Exchange == "" {
return nil, errors.New("broker: relay requires producer mode and an exchange")
}
case "worker":
if cfg.Producer || cfg.Queue == "" {
return nil, errors.New("broker: worker requires consumer mode and a queue")
}
default:
return nil, errors.New("broker: role must be relay or worker")
}
if cfg.ConnectTimeout <= 0 || cfg.ConnectTimeout > 5*time.Second {
return nil, errors.New("broker: connect timeout must be positive and at most 5s")
}
clientTLS, err := tlsconfig.NewClientFromEnv(endpoint.Hostname())
if err != nil {
return nil, fmt.Errorf("configure broker tls: %w", err)
} }
conn, err := amqp.DialConfig(cfg.URL, amqp.Config{ conn, err := amqp.DialConfig(cfg.URL, amqp.Config{
Heartbeat: cfg.Heartbeat, Heartbeat: cfg.Heartbeat,
Dial: amqp.DefaultDial(cfg.ConnectTimeout), Dial: amqp.DefaultDial(cfg.ConnectTimeout),
TLSClientConfig: clientTLS,
SASL: []amqp.Authentication{&amqp.ExternalAuth{}},
Properties: amqp.Table{ Properties: amqp.Table{
"connection_name": "messenger-" + cfg.Role, "connection_name": "messenger-relay",
}, },
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("dial broker: %w", err) return nil, fmt.Errorf("dial broker: %w", err)
} }
client := &Client{cfg: cfg, conn: conn}
if !cfg.Producer { channel, err := conn.Channel()
return client, nil if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("open topology channel: %w", err)
} }
if err := declareTopology(channel, cfg); err != nil {
_ = channel.Close()
_ = conn.Close()
return nil, err
}
if err := channel.Close(); err != nil {
_ = conn.Close()
return nil, fmt.Errorf("close topology channel: %w", err)
}
publisher, err := conn.Channel() publisher, err := conn.Channel()
if err != nil { if err != nil {
return nil, errors.Join( _ = conn.Close()
fmt.Errorf("open publisher channel: %w", err),
client.Close(), return nil, fmt.Errorf("open publisher channel: %w", err)
)
} }
client.publisher = publisher
client.returns = make(chan amqp.Return, 16) client := &Client{
cfg: cfg,
conn: conn,
publisher: publisher,
returns: make(chan amqp.Return, 16),
closed: conn.NotifyClose(make(chan *amqp.Error, 1)),
}
if err := publisher.Confirm(false); err != nil { if err := publisher.Confirm(false); err != nil {
return nil, errors.Join( _ = client.Close()
fmt.Errorf("enable publisher confirms: %w", err),
client.Close(), return nil, fmt.Errorf("enable publisher confirms: %w", err)
)
} }
publisher.NotifyReturn(client.returns) publisher.NotifyReturn(client.returns)
return client, nil return client, nil
} }
func declareTopology(channel *amqp.Channel, cfg Config) error {
if err := channel.ExchangeDeclare(cfg.Exchange, "direct", true, false, false, false, nil); err != nil {
return fmt.Errorf("declare exchange: %w", err)
}
if err := channel.ExchangeDeclare(cfg.DLX, "direct", true, false, false, false, nil); err != nil {
return fmt.Errorf("declare dlx: %w", err)
}
queue, err := channel.QueueDeclare(cfg.Queue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-delivery-limit": int32(100),
"x-delayed-retry-type": "all",
"x-delayed-retry-min": int32(5000),
"x-delayed-retry-max": int32(60000),
"x-dead-letter-exchange": cfg.DLX,
"x-dead-letter-routing-key": cfg.DLQ,
"x-dead-letter-strategy": "at-least-once",
"x-overflow": "reject-publish",
"x-max-length": int32(100000),
"x-consumer-timeout": int32(300000),
})
if err != nil {
return fmt.Errorf("declare job queue: %w", err)
}
if queue.Name != cfg.Queue {
return fmt.Errorf("broker returned queue %q, want %q", queue.Name, cfg.Queue)
}
if err := channel.QueueBind(cfg.Queue, cfg.Queue, cfg.Exchange, false, nil); err != nil {
return fmt.Errorf("bind job queue: %w", err)
}
if _, err := channel.QueueDeclare(cfg.DLQ, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-max-length": int32(100000),
"x-overflow": "reject-publish",
"x-message-ttl": int32(7 * 24 * 60 * 60 * 1000),
}); err != nil {
return fmt.Errorf("declare dlq: %w", err)
}
if err := channel.QueueBind(cfg.DLQ, cfg.DLQ, cfg.DLX, false, nil); err != nil {
return fmt.Errorf("bind dlq: %w", err)
}
return nil
}
func (c *Client) Connected() bool { func (c *Client) Connected() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.conn != nil && !c.conn.IsClosed() return c.conn != nil && !c.conn.IsClosed()
} }
// PublishConfirmed returns only after the broker acknowledged the persistent // PublishConfirmed returns only after the broker acknowledged the persistent
// message. A duplicate publication after a crash is normal and harmless. // message. A duplicate publication after a crash is normal and harmless.
func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error { func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error {
if c.cfg.Role != "relay" || !c.cfg.Producer || c.publisher == nil {
return errors.New("broker: publication is restricted to relay")
}
payload, err := message.MarshalPayload() payload, err := message.MarshalPayload()
if err != nil { if err != nil {
return fmt.Errorf("marshal job message: %w", err) return fmt.Errorf("marshal job message: %w", err)
@@ -153,8 +202,9 @@ func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, messag
return errors.New("broker nacked the job message") return errors.New("broker nacked the job message")
} }
// mandatory=true: an unroutable message is returned even if confirmed. // mandatory=true: an unroutable message is returned even though the
// The operator must provision bindings before relay startup. // confirm may still be positive. The topology is declared before publish,
// so this is a safety net rather than a normal path.
select { select {
case returned := <-c.returns: case returned := <-c.returns:
if returned.MessageId == message.JobID.String() { if returned.MessageId == message.JobID.String() {
@@ -179,9 +229,6 @@ type Handler func(ctx context.Context, delivery amqp.Delivery) Outcome
// Consume blocks until the context is cancelled or the consumer channel fails. // Consume blocks until the context is cancelled or the consumer channel fails.
// Each call uses its own channel so worker slots do not share prefetch state. // Each call uses its own channel so worker slots do not share prefetch state.
func (c *Client) Consume(ctx context.Context, handler Handler) error { func (c *Client) Consume(ctx context.Context, handler Handler) error {
if c.cfg.Role != "worker" || c.cfg.Producer {
return errors.New("broker: consumption is restricted to worker")
}
channel, err := c.conn.Channel() channel, err := c.conn.Channel()
if err != nil { if err != nil {
return fmt.Errorf("open consumer channel: %w", err) return fmt.Errorf("open consumer channel: %w", err)
@@ -254,12 +301,20 @@ func safeHandle(ctx context.Context, handler Handler, delivery amqp.Delivery) (o
} }
func (c *Client) Close() error { func (c *Client) Close() error {
c.closeOnce.Do(func() { c.mu.Lock()
// Closing the connection first interrupts consumers and publication. defer c.mu.Unlock()
// Keep pointers immutable while those operations unwind concurrently.
if c.conn != nil && !c.conn.IsClosed() { if c.publisher != nil {
c.closeErr = c.conn.CloseDeadline(time.Now().Add(time.Second)) _ = c.publisher.Close()
} c.publisher = nil
}) }
return c.closeErr
if c.conn != nil {
err := c.conn.Close()
c.conn = nil
return err
}
return nil
} }
+12 -59
View File
@@ -17,8 +17,6 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
"mtusi-messenger/internal/platform/secretfile"
"mtusi-messenger/internal/platform/tlsconfig"
) )
const ( const (
@@ -56,7 +54,9 @@ type Broker struct {
ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"` ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"`
Heartbeat time.Duration `mapstructure:"heartbeat"` Heartbeat time.Duration `mapstructure:"heartbeat"`
Exchange string `mapstructure:"exchange" validate:"required"` Exchange string `mapstructure:"exchange" validate:"required"`
DLX string `mapstructure:"dlx" validate:"required"`
Queue string `mapstructure:"queue" validate:"required"` Queue string `mapstructure:"queue" validate:"required"`
DLQ string `mapstructure:"dlq" validate:"required"`
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"` Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"`
} }
@@ -142,7 +142,6 @@ type Redis struct {
Enabled bool `mapstructure:"enabled"` Enabled bool `mapstructure:"enabled"`
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"` Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"` Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"` Password string `mapstructure:"password"`
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"` DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"` MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
@@ -181,7 +180,7 @@ type Postgres struct {
Database string `mapstructure:"database" validate:"omitempty,min=1"` Database string `mapstructure:"database" validate:"omitempty,min=1"`
User string `mapstructure:"user" validate:"omitempty,min=1"` User string `mapstructure:"user" validate:"omitempty,min=1"`
Password string `mapstructure:"password"` Password string `mapstructure:"password"`
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,eq=verify-full"` SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"` MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"` MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"` MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
@@ -204,11 +203,7 @@ func (p Postgres) DSN() string {
} }
query := url.Values{} query := url.Values{}
files := tlsconfig.FilesFromEnv() query.Set("sslmode", p.SSLMode)
query.Set("sslmode", "verify-full")
query.Set("sslrootcert", files.CA)
query.Set("sslcert", files.Cert)
query.Set("sslkey", files.Key)
u.RawQuery = query.Encode() u.RawQuery = query.Encode()
return u.String() return u.String()
@@ -222,8 +217,8 @@ var defaults = map[string]any{
"server.read_timeout": "60s", "server.read_timeout": "60s",
"server.shutdown_timeout": "10s", "server.shutdown_timeout": "10s",
"server.max_body_bytes": 262144, "server.max_body_bytes": 262144,
"s3.endpoint": "https://localhost:8333", "s3.endpoint": "http://localhost:8333",
"s3.public_endpoint": "https://localhost:8333", "s3.public_endpoint": "http://localhost:8333",
"s3.region": "us-east-1", "s3.region": "us-east-1",
"s3.bucket": "messenger-attachments", "s3.bucket": "messenger-attachments",
"s3.access_key_id": "", "s3.access_key_id": "",
@@ -239,17 +234,9 @@ var defaults = map[string]any{
"log.format": "json", "log.format": "json",
"session.ttl_seconds": 3600, "session.ttl_seconds": 3600,
"idempotency.ttl_seconds": 86400, "idempotency.ttl_seconds": 86400,
"postgres.host": "",
"postgres.port": 0,
"postgres.database": "",
"postgres.user": "",
"postgres.password": "",
"postgres.ssl_mode": "verify-full",
"redis.enabled": false, "redis.enabled": false,
"redis.host": "localhost", "redis.host": "localhost",
"redis.port": 6379, "redis.port": 6379,
"redis.username": "",
"redis.password": "",
"redis.db": 0, "redis.db": 0,
"redis.max_retries": -1, "redis.max_retries": -1,
"redis.dial_timeout": "300ms", "redis.dial_timeout": "300ms",
@@ -266,13 +253,15 @@ var defaults = map[string]any{
"broker.confirm_timeout": "5s", "broker.confirm_timeout": "5s",
"broker.heartbeat": "10s", "broker.heartbeat": "10s",
"broker.exchange": "attachments.jobs", "broker.exchange": "attachments.jobs",
"broker.dlx": "attachments.dlx",
"broker.queue": "attachment.process.v1", "broker.queue": "attachment.process.v1",
"broker.dlq": "attachment.process.dead",
"broker.prefetch": 1, "broker.prefetch": 1,
"worker.concurrency": 1, "worker.concurrency": 1,
"worker.prefetch": 1, "worker.prefetch": 1,
"worker.shutdown_timeout": "30s", "worker.shutdown_timeout": "30s",
"worker.health_addr": "127.0.0.1:8081", "worker.health_addr": ":8081",
"relay.health_addr": "127.0.0.1:8082", "relay.health_addr": ":8082",
"outbox.poll_interval": "1s", "outbox.poll_interval": "1s",
"outbox.claim_ttl": "30s", "outbox.claim_ttl": "30s",
"outbox.batch": 20, "outbox.batch": 20,
@@ -293,20 +282,6 @@ var defaults = map[string]any{
} }
func Load() (Config, error) { func Load() (Config, error) {
return load("")
}
// LoadOperator reads the migration credential from an operator-only mounted file.
// Application credentials are acquired by Bao before Load instead.
func LoadOperator() (Config, error) {
path := os.Getenv("POSTGRES_PASSWORD_FILE")
if path == "" {
return Config{}, errors.New("operator config: postgres_password_file is required")
}
return load(path)
}
func load(operatorPasswordFile string) (Config, error) {
v := viper.New() v := viper.New()
if err := configureSource(v); err != nil { if err := configureSource(v); err != nil {
@@ -333,17 +308,6 @@ func load(operatorPasswordFile string) (Config, error) {
return Config{}, fmt.Errorf("bind env %q: %w", env, err) return Config{}, fmt.Errorf("bind env %q: %w", env, err)
} }
} }
if operatorPasswordFile != "" {
password, err := secretfile.Read(operatorPasswordFile)
if err != nil {
return Config{}, fmt.Errorf("read operator database password: %w", err)
}
value := strings.TrimRight(string(password), "\r\n")
if value == "" {
return Config{}, errors.New("operator database password is empty")
}
v.Set("postgres.password", value)
}
var cfg Config var cfg Config
if err := v.Unmarshal(&cfg); err != nil { if err := v.Unmarshal(&cfg); err != nil {
@@ -386,20 +350,9 @@ func (c Config) validateDependencies() error {
return errors.New("validate config: staging.failed_retention must be >= staging.orphan_grace") return errors.New("validate config: staging.failed_retention must be >= staging.orphan_grace")
} }
for _, endpoint := range []string{c.S3.Endpoint, c.S3.PublicEndpoint} {
if endpoint == "" {
continue
}
u, err := url.Parse(endpoint)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
return errors.New("validate config: s3 endpoints must be https urls without credentials")
}
}
if c.Broker.URL != "" { if c.Broker.URL != "" {
u, err := url.Parse(c.Broker.URL) if _, err := url.Parse(c.Broker.URL); err != nil {
if err != nil || u.Scheme != "amqps" || u.Hostname() == "" || u.User != nil { return fmt.Errorf("validate config: broker.url: %w", err)
return errors.New("validate config: broker.url must be an amqps url without credentials")
} }
} }
+18 -71
View File
@@ -1,7 +1,6 @@
package config_test package config_test
import ( import (
"net/url"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -15,6 +14,19 @@ import (
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
) )
func TestDefaults(t *testing.T) {
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "0.0.0.0", cfg.Server.Host)
assert.Equal(t, 8080, cfg.Server.Port)
assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "info", cfg.Log.Level)
assert.Equal(t, "json", cfg.Log.Format)
assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter")
}
func TestEnvOverridesDefaults(t *testing.T) { func TestEnvOverridesDefaults(t *testing.T) {
t.Setenv("SERVER_HOST", "127.0.0.1") t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("SERVER_PORT", "9090") t.Setenv("SERVER_PORT", "9090")
@@ -35,30 +47,16 @@ func TestEnvOverridesDefaults(t *testing.T) {
} }
func TestDsnEncodesCredentials(t *testing.T) { func TestDsnEncodesCredentials(t *testing.T) {
t.Setenv("TLS_CA_FILE", "/identity/ca.crt")
t.Setenv("TLS_CERT_FILE", "/identity/tls.crt")
t.Setenv("TLS_KEY_FILE", "/identity/tls.key")
cfg := config.Postgres{ cfg := config.Postgres{
Host: "db", Host: "db",
Port: 5432, Port: 5432,
Database: "app", Database: "app",
User: "user", User: "user",
Password: "p@ss:w/rd", Password: "p@ss:w/rd",
SSLMode: "verify-full", SSLMode: "disable",
} }
dsn, err := url.Parse(cfg.DSN()) assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN())
require.NoError(t, err)
assert.Equal(t, "user", dsn.User.Username())
password, ok := dsn.User.Password()
require.True(t, ok)
assert.Equal(t, "p@ss:w/rd", password)
assert.Equal(t, "db:5432", dsn.Host)
assert.Equal(t, "/app", dsn.Path)
assert.Equal(t, "verify-full", dsn.Query().Get("sslmode"))
assert.Equal(t, "/identity/ca.crt", dsn.Query().Get("sslrootcert"))
assert.Equal(t, "/identity/tls.crt", dsn.Query().Get("sslcert"))
assert.Equal(t, "/identity/tls.key", dsn.Query().Get("sslkey"))
} }
func writeConfig(t *testing.T, body string) string { func writeConfig(t *testing.T, body string) string {
@@ -87,7 +85,7 @@ postgres:
database: app database: app
user: app user: app
password: secret password: secret
ssl_mode: verify-full ssl_mode: disable
max_conns: 7 max_conns: 7
min_conns: 2 min_conns: 2
max_conn_lifetime: 2h max_conn_lifetime: 2h
@@ -130,7 +128,7 @@ postgres:
database: app database: app
user: app user: app
password: file password: file
ssl_mode: verify-full ssl_mode: disable
`) `)
t.Setenv("APP_CONFIG", path) t.Setenv("APP_CONFIG", path)
@@ -190,15 +188,12 @@ postgres:
port: 5432 port: 5432
database: messenger database: messenger
user: messenger user: messenger
ssl_mode: verify-full ssl_mode: disable
max_conns: 10 max_conns: 10
`) `)
tests := map[string]map[string]string{ tests := map[string]map[string]string{
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"}, "неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
"plaintext ssl mode": {"POSTGRES_SSL_MODE": "disable"},
"unverified ssl mode": {"POSTGRES_SSL_MODE": "require"},
"hostname not verified": {"POSTGRES_SSL_MODE": "verify-ca"},
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"}, "отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
} }
@@ -305,8 +300,6 @@ func TestRedisEnvOverrides(t *testing.T) {
t.Setenv("REDIS_ENABLED", "true") t.Setenv("REDIS_ENABLED", "true")
t.Setenv("REDIS_HOST", "cache") t.Setenv("REDIS_HOST", "cache")
t.Setenv("REDIS_PORT", "6380") t.Setenv("REDIS_PORT", "6380")
t.Setenv("REDIS_USERNAME", "api-cache")
t.Setenv("REDIS_PASSWORD", "cache-secret")
t.Setenv("CACHE_ENABLED", "true") t.Setenv("CACHE_ENABLED", "true")
t.Setenv("CACHE_CHAT_LIST_TTL", "1m") t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("CACHE_LOCK_TTL", "7s") t.Setenv("CACHE_LOCK_TTL", "7s")
@@ -318,8 +311,6 @@ func TestRedisEnvOverrides(t *testing.T) {
assert.True(t, cfg.Redis.Enabled) assert.True(t, cfg.Redis.Enabled)
assert.Equal(t, "cache", cfg.Redis.Host) assert.Equal(t, "cache", cfg.Redis.Host)
assert.Equal(t, 6380, cfg.Redis.Port) assert.Equal(t, 6380, cfg.Redis.Port)
assert.Equal(t, "api-cache", cfg.Redis.Username)
assert.Equal(t, "cache-secret", cfg.Redis.Password)
assert.True(t, cfg.Cache.Enabled) assert.True(t, cfg.Cache.Enabled)
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL) assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL) assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
@@ -350,47 +341,3 @@ func TestCacheRequiresRedis(t *testing.T) {
_, err := config.Load() _, err := config.Load()
require.ErrorContains(t, err, "cache.enabled requires redis.enabled") require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
} }
func TestRejectsInsecureDependencyEndpoints(t *testing.T) {
for key, value := range map[string]string{
"S3_ENDPOINT": "http://seaweedfs:8333",
"S3_PUBLIC_ENDPOINT": "http://localhost:8333",
"BROKER_URL": "amqp://broker:5672/",
} {
t.Run(key, func(t *testing.T) {
t.Setenv(key, value)
_, err := config.Load()
require.Error(t, err)
})
}
}
func TestLoadOperatorUsesOnlyMountedDatabaseCredential(t *testing.T) {
path := filepath.Join(t.TempDir(), "password")
require.NoError(t, os.WriteFile(path, []byte("operator-secret\n"), 0o600))
t.Setenv("POSTGRES_PASSWORD_FILE", path)
t.Setenv("POSTGRES_PASSWORD", "application-secret")
t.Setenv("S3_ACCESS_KEY_ID", "")
t.Setenv("S3_SECRET_ACCESS_KEY", "")
t.Setenv("REDIS_PASSWORD", "")
cfg, err := config.LoadOperator()
require.NoError(t, err)
assert.Equal(t, "operator-secret", cfg.Postgres.Password)
assert.Empty(t, cfg.S3.AccessKeyID)
assert.Empty(t, cfg.S3.SecretAccessKey)
assert.Empty(t, cfg.Redis.Password)
}
func TestLoadOperatorRequiresReadableNonemptyPasswordFile(t *testing.T) {
t.Setenv("POSTGRES_PASSWORD_FILE", "")
_, err := config.LoadOperator()
require.Error(t, err)
t.Setenv("POSTGRES_PASSWORD_FILE", filepath.Join(t.TempDir(), "missing"))
_, err = config.LoadOperator()
require.Error(t, err)
path := filepath.Join(t.TempDir(), "empty")
require.NoError(t, os.WriteFile(path, []byte("\n"), 0o600))
t.Setenv("POSTGRES_PASSWORD_FILE", path)
_, err = config.LoadOperator()
require.Error(t, err)
}
-182
View File
@@ -1,182 +0,0 @@
package bao
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
)
const maxReplyBytes = 1 << 20
type authReply struct {
Auth struct {
Token string `json:"client_token"`
TTL int64 `json:"lease_duration"`
Renewable bool `json:"renewable"`
} `json:"auth"`
}
type kvReply struct {
Data struct {
Data map[string]json.RawMessage `json:"data"`
} `json:"data"`
}
func (m *Manager) request(ctx context.Context, method, path string, body any, result any) error {
var payload []byte
var err error
if body != nil {
payload, err = json.Marshal(body)
if err != nil {
return errors.New("encode bao request failed")
}
}
requestCtx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
request, err := http.NewRequestWithContext(requestCtx, method, m.address+"/v1/"+path, bytes.NewReader(payload))
if err != nil {
return errors.New("create bao request failed")
}
request.Header.Set("Content-Type", "application/json")
m.mu.Lock()
token := m.token
m.mu.Unlock()
if token != "" && path != "auth/cert/login" {
request.Header.Set("X-Vault-Token", token)
}
response, err := m.client.Do(request)
if err != nil {
// URL errors and response bodies are deliberately not propagated: they
// may contain service-generated tokens or confidential request details.
return errors.New("bao https request failed")
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return errors.New("bao request was not authorized or server is unavailable")
}
data, err := io.ReadAll(io.LimitReader(response.Body, maxReplyBytes+1))
if err != nil {
return errors.New("read bao response failed")
}
if len(data) > maxReplyBytes {
return errors.New("bao response exceeds size limit")
}
decoder := json.NewDecoder(bytes.NewReader(data))
if err := decoder.Decode(result); err != nil {
return errors.New("decode bao response failed")
}
var trailing any
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
return errors.New("bao response contains trailing data")
}
return nil
}
func leaseDuration(reply authReply) (time.Duration, error) {
if reply.Auth.Token == "" || reply.Auth.TTL <= 0 || reply.Auth.TTL > 300 {
return 0, errors.New("bao token lease is invalid")
}
// Never let an unexpectedly relaxed server default widen normal admission.
ttl := time.Duration(reply.Auth.TTL) * time.Second
if ttl > 60*time.Second {
ttl = 60 * time.Second
}
return ttl, nil
}
func (m *Manager) authenticate(ctx context.Context) error {
started := m.now()
var reply authReply
if err := m.request(ctx, http.MethodPost, "auth/cert/login", map[string]string{"name": m.role}, &reply); err != nil {
return err
}
ttl, err := leaseDuration(reply)
if err != nil {
return err
}
if !m.now().Before(started.Add(ttl).Add(-time.Second)) {
return errors.New("bao token expired during authentication")
}
m.mu.Lock()
m.token = reply.Auth.Token
m.isRenewable = reply.Auth.Renewable
m.leases.tokenExpires = started.Add(ttl)
m.renewAt = started.Add(ttl / 2)
m.maxUntil = started.Add(maxTokenLifetime)
m.mu.Unlock()
return nil
}
func (m *Manager) renew(ctx context.Context) error {
started := m.now()
m.mu.Lock()
canRenew := m.isRenewable && started.Add(60*time.Second).Before(m.maxUntil)
maxUntil := m.maxUntil
m.mu.Unlock()
if !canRenew {
return m.authenticate(ctx)
}
var reply authReply
if err := m.request(ctx, http.MethodPost, "auth/token/renew-self", map[string]string{"increment": "60s"}, &reply); err != nil {
return err
}
ttl, err := leaseDuration(reply)
if err != nil {
return err
}
expires := started.Add(ttl)
if expires.After(maxUntil) {
expires = maxUntil
}
if !m.now().Before(expires.Add(-time.Second)) {
return errors.New("bao token expired during renewal")
}
m.mu.Lock()
m.token = reply.Auth.Token
m.isRenewable = reply.Auth.Renewable
m.leases.tokenExpires = expires
m.renewAt = started.Add(expires.Sub(started) / 2)
m.mu.Unlock()
return nil
}
func (m *Manager) readSettings(ctx context.Context) (map[string]string, error) {
started := m.now()
var reply kvReply
if err := m.request(ctx, http.MethodGet, m.path, nil, &reply); err != nil {
return nil, err
}
settings := make(map[string]string, len(confidentialKeys))
for _, key := range confidentialKeys {
raw, exists := reply.Data.Data[key]
if !exists {
continue
}
var value string
if err := json.Unmarshal(raw, &value); err != nil || value == "" {
return nil, errors.New("bao confidential configuration value is invalid")
}
settings[key] = value
}
required := []string{"POSTGRES_PASSWORD"}
if m.role == "api" || m.role == "worker" {
required = append(required, "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY")
}
if m.role == "api" {
required = append(required, "REDIS_PASSWORD")
}
for _, key := range required {
if settings[key] == "" {
return nil, errors.New("bao own-role confidential configuration is incomplete")
}
}
m.mu.Lock()
m.leases.kvExpires = started.Add(freshness)
m.refreshAt = started.Add(freshness / 3)
m.mu.Unlock()
return settings, nil
}
-345
View File
@@ -1,345 +0,0 @@
// Package bao acquires only an application's own confidential configuration
// and bounds its admission by independent token, authorization and leaf leases.
package bao
import (
"context"
"crypto/x509"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"sync"
"time"
"mtusi-messenger/internal/platform/tlsconfig"
)
const (
requestTimeout = 5 * time.Second
freshness = 60 * time.Second
maxTokenLifetime = 300 * time.Second
shutdownTimeout = 30 * time.Second
)
var ErrExpired = errors.New("bao: authorization lease expired")
var confidentialKeys = []string{
"POSTGRES_PASSWORD", "REDIS_PASSWORD", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY",
}
type leases struct {
tokenExpires time.Time
kvExpires time.Time
leafExpires time.Time
}
func (l leases) deadline() time.Time {
deadline := l.tokenExpires
if l.kvExpires.Before(deadline) {
deadline = l.kvExpires
}
if l.leafExpires.Before(deadline) {
deadline = l.leafExpires
}
return deadline.Add(-time.Second)
}
type Manager struct {
cancel context.CancelCauseFunc
loader *tlsconfig.Loader
client *http.Client
transport *http.Transport
address string
role string
path string
mu sync.Mutex
leases leases
token string
isRenewable bool
renewAt time.Time
maxUntil time.Time
refreshAt time.Time
version string
settings map[string]string
shutdownDeadline time.Time
workers int
done chan struct{}
now func() time.Time
}
// Start requires cert authentication even when legacy secret environment values
// exist. Neither a sealed server nor an unavailable server can bootstrap an app.
func Start(ctx context.Context, expectedRole string) (context.Context, *Manager, error) {
for _, key := range confidentialKeys {
if err := os.Unsetenv(key); err != nil {
return nil, nil, errors.New("clear legacy confidential configuration failed")
}
}
address, role, path, err := environment(expectedRole)
if err != nil {
return nil, nil, err
}
loader, err := tlsconfig.New(tlsconfig.FilesFromEnv())
if err != nil {
return nil, nil, fmt.Errorf("load bao tls identity: %w", err)
}
leaf, err := loader.Leaf()
if err != nil {
return nil, nil, err
}
if !hasRole(leaf, role) {
return nil, nil, errors.New("bao certificate does not match application role")
}
endpoint, err := url.Parse(address)
if err != nil {
return nil, nil, errors.New("invalid bao address")
}
transport := &http.Transport{
TLSClientConfig: loader.Client(endpoint.Hostname()),
DisableKeepAlives: true,
TLSHandshakeTimeout: requestTimeout,
ResponseHeaderTimeout: requestTimeout,
}
managedCtx, cancel := context.WithCancelCause(context.WithoutCancel(ctx))
manager := &Manager{
cancel: cancel, loader: loader,
transport: transport,
client: &http.Client{
Transport: transport, Timeout: requestTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return errors.New("bao redirects are forbidden")
},
},
address: address, role: role, path: path, now: time.Now,
}
manager.version, err = loader.Version()
if err != nil {
return nil, nil, err
}
manager.leases.leafExpires = leaf.NotAfter
if err := manager.authenticate(ctx); err != nil {
manager.Stop()
transport.CloseIdleConnections()
return nil, nil, err
}
settings, err := manager.readSettings(ctx)
if err != nil {
manager.Stop()
transport.CloseIdleConnections()
return nil, nil, err
}
manager.settings = settings
if !manager.now().Before(manager.leases.deadline()) {
manager.stop(ErrExpired)
return nil, nil, ErrExpired
}
if err := ctx.Err(); err != nil {
manager.stop(err)
return nil, nil, err
}
for key, value := range settings {
if err := os.Setenv(key, value); err != nil {
manager.Stop()
return nil, nil, errors.New("inject confidential configuration failed")
}
}
manager.workers = 2
manager.done = make(chan struct{})
go manager.watchdog(managedCtx, ctx)
go manager.refresh(managedCtx)
return managedCtx, manager, nil
}
func environment(expectedRole string) (string, string, string, error) {
if expectedRole != "api" && expectedRole != "worker" && expectedRole != "relay" {
return "", "", "", errors.New("bao application role is unsupported")
}
role := os.Getenv("BAO_ROLE")
path := os.Getenv("BAO_KV_PATH")
address := os.Getenv("BAO_ADDR")
if role != expectedRole || path != "secret/data/"+role {
return "", "", "", errors.New("bao role and kv path must match application identity")
}
endpoint, err := url.Parse(address)
if err != nil || endpoint.Scheme != "https" || endpoint.Hostname() == "" {
return "", "", "", errors.New("bao native https address is required")
}
if endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {
return "", "", "", errors.New("bao address cannot contain credentials or parameters")
}
if endpoint.Path != "" && endpoint.Path != "/" {
return "", "", "", errors.New("bao address must name the server root")
}
endpoint.Path = ""
return endpoint.String(), role, path, nil
}
func hasRole(leaf *x509.Certificate, role string) bool {
for _, uri := range leaf.URIs {
if uri.String() == "spiffe://mtusi/"+role {
return true
}
}
return false
}
func (m *Manager) stop(cause error) {
m.mu.Lock()
defer m.mu.Unlock()
if !m.shutdownDeadline.IsZero() {
return
}
m.shutdownDeadline = m.now().Add(shutdownTimeout)
m.cancel(cause)
}
func (m *Manager) Stop() { m.stop(context.Canceled) }
// ShutdownContext always uses the first cancellation's deadline, never a new
// thirty-second budget after consumer/sweeper waits have already elapsed.
func (m *Manager) ShutdownContext(parent context.Context) (context.Context, context.CancelFunc) {
m.Stop()
m.mu.Lock()
deadline := m.shutdownDeadline
m.mu.Unlock()
return context.WithDeadline(context.WithoutCancel(parent), deadline)
}
func (m *Manager) Close(parent context.Context) error {
m.Stop()
m.transport.CloseIdleConnections()
ctx, cancel := m.ShutdownContext(parent)
defer cancel()
select {
case <-m.done:
return nil
case <-ctx.Done():
return errors.New("bao shutdown exceeded deadline")
}
}
func (m *Manager) workerFinished() {
m.mu.Lock()
defer m.mu.Unlock()
m.workers--
if m.workers == 0 {
close(m.done)
}
}
func (m *Manager) watchdog(ctx, parent context.Context) {
defer m.workerFinished()
timer := time.NewTimer(0)
defer timer.Stop()
for {
select {
case <-parent.Done():
m.stop(parent.Err())
return
case <-ctx.Done():
return
case <-timer.C:
leaf, err := m.loader.Leaf()
if !m.observeLeaf(leaf, err) {
return
}
m.mu.Lock()
remaining := m.leases.deadline().Sub(m.now())
m.mu.Unlock()
if remaining > time.Second {
remaining = time.Second
}
if remaining < 0 {
remaining = 0
}
timer.Reset(remaining)
}
}
}
func (m *Manager) observeLeaf(leaf *x509.Certificate, loadError error) bool {
if loadError != nil || leaf == nil || !hasRole(leaf, m.role) {
m.stop(ErrExpired)
return false
}
m.mu.Lock()
m.leases.leafExpires = leaf.NotAfter
deadline := m.leases.deadline()
m.mu.Unlock()
if !m.now().Before(deadline) {
m.stop(ErrExpired)
return false
}
return true
}
func (m *Manager) refresh(ctx context.Context) {
defer m.workerFinished()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
m.refreshOnce(ctx)
}
}
}
func (m *Manager) refreshOnce(ctx context.Context) {
version, err := m.loader.Version()
if err != nil {
return
}
m.mu.Lock()
changed := version != m.version
now := m.now()
renewDue := !now.Before(m.renewAt)
refreshDue := !now.Before(m.refreshAt)
m.mu.Unlock()
if changed {
m.transport.CloseIdleConnections()
if err := m.authenticate(ctx); err != nil {
return
}
m.mu.Lock()
m.version = version
m.mu.Unlock()
refreshDue = true
} else if renewDue {
if err := m.renew(ctx); err != nil {
return
}
refreshDue = true
}
if !refreshDue {
return
}
settings, err := m.readSettings(ctx)
if err != nil {
return
}
m.mu.Lock()
unchanged := sameSettings(m.settings, settings)
m.mu.Unlock()
if !unchanged {
// Dependency pools hold the original credentials. A rotation restarts
// the service rather than falsely authorizing old, cached credentials.
m.stop(fmt.Errorf("bao confidential configuration changed: %w", ErrExpired))
}
}
func sameSettings(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for key, value := range a {
if b[key] != value {
return false
}
}
return true
}
-216
View File
@@ -1,216 +0,0 @@
package bao
import (
"context"
"crypto/x509"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"sync/atomic"
"testing"
"time"
)
func testManager(t *testing.T, handler http.Handler) (context.Context, *Manager, *time.Time) {
t.Helper()
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
now := time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC)
ctx, cancel := context.WithCancelCause(t.Context())
t.Cleanup(func() { cancel(context.Canceled) })
return ctx, &Manager{
cancel: cancel, client: server.Client(), address: server.URL,
role: "relay", path: "secret/data/relay", now: func() time.Time { return now },
settings: map[string]string{},
}, &now
}
func TestAuthorizationLeasesAreIndependent(t *testing.T) {
start := time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC)
lease := leases{
tokenExpires: start.Add(60 * time.Second),
kvExpires: start.Add(40 * time.Second),
leafExpires: start.Add(20 * time.Second),
}
if got := lease.deadline(); !got.Equal(start.Add(19 * time.Second)) {
t.Fatalf("leaf deadline = %v", got)
}
lease.tokenExpires = start.Add(300 * time.Second)
lease.kvExpires = start.Add(60 * time.Second)
if got := lease.deadline(); !got.Equal(start.Add(19 * time.Second)) {
t.Fatal("token/kv refresh extended the leaf deadline")
}
lease.leafExpires = start.Add(90 * time.Second)
if got := lease.deadline(); !got.Equal(start.Add(59 * time.Second)) {
t.Fatal("leaf refresh extended kv authorization freshness")
}
}
func TestTokenRenewalHalfTTLAndReauthenticationBeforeMaxTTL(t *testing.T) {
var logins, renewals atomic.Int64
ctx, manager, now := testManager(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/auth/cert/login":
logins.Add(1)
case "/v1/auth/token/renew-self":
renewals.Add(1)
if r.Header.Get("X-Vault-Token") != "test-token" {
t.Error("renew-self missing token")
}
default:
t.Errorf("unexpected request %s", r.URL.Path)
}
fmt.Fprint(w, `{"auth":{"client_token":"test-token","lease_duration":60,"renewable":true}}`)
}))
start := *now
if err := manager.authenticate(ctx); err != nil {
t.Fatal(err)
}
if !manager.renewAt.Equal(start.Add(30 * time.Second)) {
t.Fatal("not scheduled at half ttl")
}
*now = start.Add(30 * time.Second)
if err := manager.renew(ctx); err != nil {
t.Fatal(err)
}
if logins.Load() != 1 || renewals.Load() != 1 {
t.Fatalf("login=%d renew=%d", logins.Load(), renewals.Load())
}
if !manager.maxUntil.Equal(start.Add(300 * time.Second)) {
t.Fatal("renewal extended max lifetime")
}
*now = start.Add(240 * time.Second)
if err := manager.renew(ctx); err != nil {
t.Fatal(err)
}
if logins.Load() != 2 {
t.Fatal("max lifetime did not force reauthentication")
}
}
func TestFailedTokenAndKVOperationsDoNotExtendDeadlines(t *testing.T) {
var isUnavailable atomic.Bool
ctx, manager, now := testManager(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isUnavailable.Load() {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, "secret-sentinel-test-token")
return
}
if r.URL.Path == "/v1/secret/data/relay" {
fmt.Fprint(w, `{"data":{"data":{"POSTGRES_PASSWORD":"secret-sentinel","SERVER_PORT":"1"}}}`)
return
}
fmt.Fprint(w, `{"auth":{"client_token":"test-token","lease_duration":60,"renewable":true}}`)
}))
if err := manager.authenticate(ctx); err != nil {
t.Fatal(err)
}
settings, err := manager.readSettings(ctx)
if err != nil {
t.Fatal(err)
}
if len(settings) != 1 || settings["SERVER_PORT"] != "" {
t.Fatal("nonconfidential key was injected")
}
before := manager.leases
isUnavailable.Store(true)
*now = now.Add(30 * time.Second)
if err := manager.renew(ctx); err == nil || strings.Contains(err.Error(), "sentinel") {
t.Fatalf("failed renew error = %v", err)
}
if _, err := manager.readSettings(ctx); err == nil || strings.Contains(err.Error(), "sentinel") {
t.Fatalf("failed kv error = %v", err)
}
if manager.leases != before {
t.Fatal("failure extended authorization deadlines")
}
}
func TestCurrentLeafObservationResetsOnlyActualLeafDeadline(t *testing.T) {
ctx, manager, now := testManager(t, http.NotFoundHandler())
start := *now
manager.leases = leases{
tokenExpires: start.Add(time.Minute), kvExpires: start.Add(time.Minute),
leafExpires: start.Add(20 * time.Second),
}
uri, err := url.Parse("spiffe://mtusi/relay")
if err != nil {
t.Fatal(err)
}
leaf := &x509.Certificate{NotAfter: start.Add(40 * time.Second), URIs: []*url.URL{uri}}
*now = start.Add(19 * time.Second)
if !manager.observeLeaf(leaf, nil) {
t.Fatal("valid rotated short leaf was rejected")
}
if !manager.leases.leafExpires.Equal(leaf.NotAfter) {
t.Fatal("retained initial leaf deadline")
}
*now = start.Add(39 * time.Second)
if manager.observeLeaf(leaf, nil) {
t.Fatal("expired safety-margin admission remains open")
}
if !errors.Is(context.Cause(ctx), ErrExpired) {
t.Fatal("expiry did not cancel services")
}
deadline := manager.shutdownDeadline
*now = now.Add(10 * time.Second)
shutdownCtx, cancel := manager.ShutdownContext(ctx)
defer cancel()
actual, ok := shutdownCtx.Deadline()
if !ok || !actual.Equal(deadline) {
t.Fatal("shutdown gained a second full budget after waiting")
}
}
func TestAuthorizationFailureClosesAdmissionImmediately(t *testing.T) {
ctx, manager, now := testManager(t, http.NotFoundHandler())
manager.leases = leases{
tokenExpires: now.Add(time.Minute), kvExpires: now.Add(time.Minute),
leafExpires: now.Add(time.Minute),
}
if manager.observeLeaf(nil, errors.New("revoked leaf")) {
t.Fatal("failed identity remains admitted")
}
if ctx.Err() == nil {
t.Fatal("identity failure did not cancel service context")
}
}
func TestResponseSizeAndMalformedLeaseAreRejected(t *testing.T) {
ctx, manager, _ := testManager(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, strings.Repeat("x", maxReplyBytes+1))
}))
if _, err := manager.readSettings(ctx); err == nil {
t.Fatal("oversized response accepted")
}
for _, ttl := range []int64{0, -1, 301} {
var reply authReply
reply.Auth.Token = "test-token"
reply.Auth.TTL = ttl
if _, err := leaseDuration(reply); err == nil {
t.Fatalf("invalid ttl %d accepted", ttl)
}
}
}
func TestConfiguredBaoNeverBootstrapsFromLegacySecrets(t *testing.T) {
t.Setenv("BAO_ADDR", "https://openbao:8200")
t.Setenv("BAO_ROLE", "relay")
t.Setenv("BAO_KV_PATH", "secret/data/relay")
t.Setenv("POSTGRES_PASSWORD", "legacy-password")
t.Setenv("TLS_CA_FILE", "/missing/current/ca.crt")
t.Setenv("TLS_CERT_FILE", "/missing/current/tls.crt")
t.Setenv("TLS_KEY_FILE", "/missing/current/tls.key")
t.Setenv("TLS_CRL_FILE", "/missing/current/ca.crl")
t.Setenv("TLS_VERSION_FILE", "/missing/current-version")
if _, _, err := Start(t.Context(), "relay"); err == nil {
t.Fatal("missing identity accepted")
}
if os.Getenv("POSTGRES_PASSWORD") != "" {
t.Fatal("legacy secret remains usable after failed acquisition")
}
}
+4 -17
View File
@@ -9,14 +9,11 @@ import (
"time" "time"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"mtusi-messenger/internal/platform/tlsconfig"
) )
type RedisConfig struct { type RedisConfig struct {
Host string Host string
Port int Port int
Username string
Password string Password string
DB int DB int
MaxRetries int MaxRetries int
@@ -30,22 +27,13 @@ type RedisCache struct {
client *redis.Client client *redis.Client
} }
func NewRedis(ctx context.Context, cfg RedisConfig) (*RedisCache, error) { func NewRedis(cfg RedisConfig) (*RedisCache, error) {
if cfg.Username == "" || cfg.Password == "" { client := redis.NewClient(newClientOptions(cfg))
return nil, errors.New("redis: username and password are required")
}
clientTLS, err := tlsconfig.NewClientFromEnv(cfg.Host)
if err != nil {
return nil, fmt.Errorf("configure redis tls: %w", err)
}
opts := newClientOptions(cfg)
opts.TLSConfig = clientTLS
client := redis.NewClient(opts)
pingCtx, cancel := context.WithTimeout(ctx, cfg.DialTimeout) ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
defer cancel() defer cancel()
if err := client.Ping(pingCtx).Err(); err != nil { if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close() _ = client.Close()
return nil, fmt.Errorf("ping redis: %w", err) return nil, fmt.Errorf("ping redis: %w", err)
@@ -57,7 +45,6 @@ func NewRedis(ctx context.Context, cfg RedisConfig) (*RedisCache, error) {
func newClientOptions(cfg RedisConfig) *redis.Options { func newClientOptions(cfg RedisConfig) *redis.Options {
return &redis.Options{ return &redis.Options{
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)), Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
Username: cfg.Username,
Password: cfg.Password, Password: cfg.Password,
DB: cfg.DB, DB: cfg.DB,
MaxRetries: cfg.MaxRetries, MaxRetries: cfg.MaxRetries,
+20 -45
View File
@@ -7,7 +7,6 @@ import (
"io" "io"
"net" "net"
"net/http" "net/http"
"net/url"
"strings" "strings"
"time" "time"
@@ -18,7 +17,6 @@ import (
"github.com/aws/smithy-go" "github.com/aws/smithy-go"
"mtusi-messenger/internal/domain" "mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/tlsconfig"
) )
// Config is the S3 connection subset. Limits belong to the attachment service. // Config is the S3 connection subset. Limits belong to the attachment service.
@@ -36,11 +34,10 @@ type Config struct {
// S3 is an object store backed by an S3-compatible server (SeaweedFS in the // S3 is an object store backed by an S3-compatible server (SeaweedFS in the
// lab stand, MinIO/AWS in other deployments). // lab stand, MinIO/AWS in other deployments).
type S3 struct { type S3 struct {
bucket string bucket string
internal *s3.Client internal *s3.Client
public *s3.Client public *s3.Client
timeout time.Duration timeout time.Duration
transport *http.Transport
} }
var _ Store = (*S3)(nil) var _ Store = (*S3)(nil)
@@ -58,38 +55,20 @@ func New(cfg Config) (*S3, error) {
cfg.PublicEndpoint = cfg.Endpoint cfg.PublicEndpoint = cfg.Endpoint
} }
for _, endpoint := range []string{cfg.Endpoint, cfg.PublicEndpoint} {
u, err := url.Parse(endpoint)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
return nil, errors.New("object store: endpoints must be https urls without credentials")
}
if u.RawQuery != "" || u.Fragment != "" {
return nil, errors.New("object store: endpoints must not contain a query or fragment")
}
}
clientTLS, err := tlsconfig.NewClientFromEnv("")
if err != nil {
return nil, fmt.Errorf("configure object store tls: %w", err)
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSClientConfig: clientTLS,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 90 * time.Second,
}
httpClient := &http.Client{ httpClient := &http.Client{
Transport: transport, Transport: &http.Transport{
CheckRedirect: func(*http.Request, []*http.Request) error { Proxy: http.ProxyFromEnvironment,
return errors.New("object store: redirects are not permitted") DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 90 * time.Second,
}, },
// Downloads stream through the response body; an overall timeout // Downloads stream through the response body; an overall client
// would abort them. // timeout would abort them.
} }
newClient := func(endpoint string) *s3.Client { newClient := func(endpoint string) *s3.Client {
@@ -103,19 +82,15 @@ func New(cfg Config) (*S3, error) {
} }
st := &S3{ st := &S3{
bucket: cfg.Bucket, bucket: cfg.Bucket,
internal: newClient(cfg.Endpoint), internal: newClient(cfg.Endpoint),
public: newClient(cfg.PublicEndpoint), public: newClient(cfg.PublicEndpoint),
timeout: cfg.Timeout, timeout: cfg.Timeout,
transport: transport,
} }
return st, nil return st, nil
} }
// Close releases idle connections owned by the S3 clients.
func (s *S3) Close() { s.transport.CloseIdleConnections() }
func (s *S3) Ping(ctx context.Context) error { func (s *S3) Ping(ctx context.Context) error {
// HeadBucket needs bucket-level permissions that the application identity // HeadBucket needs bucket-level permissions that the application identity
// intentionally does not have. A HeadObject on a sentinel staging key is // intentionally does not have. A HeadObject on a sentinel staging key is
+21 -166
View File
@@ -4,194 +4,49 @@ import (
"crypto/rand" "crypto/rand"
"crypto/subtle" "crypto/subtle"
"encoding/base64" "encoding/base64"
"errors"
"fmt"
"strconv"
"strings" "strings"
"golang.org/x/crypto/argon2" "golang.org/x/crypto/argon2"
) )
const ( const (
argonTime = 2 argonTime = 1
argonMemory = 19456 argonMemory = 64 * 1024
argonThreads = 1 argonThreads = 4
argonKeyLen = 32 argonKeyLen = 32
argonSaltLen = 16 argonSaltLen = 16
maxEncodedLen = 512
) )
var ErrBusy = errors.New("password: derivation capacity exhausted")
// All entry points share the same nonblocking, per-process derivation budget.
// Legacy PHC strings can ask for 64 MiB per derivation; they get a separate
// single slot so two upgrades cannot exceed the API memory limit.
var (
derivations = make(chan struct{}, 2)
legacyDerivations = make(chan struct{}, 1)
)
type Verification struct {
Match bool
NeedsRehash bool
}
type parameters struct {
memory uint32
time uint32
threads uint8
isLegacy bool
salt [argonSaltLen]byte
hash [argonKeyLen]byte
}
func Hash(plain string) (string, error) { func Hash(plain string) (string, error) {
if !acquire() { salt := make([]byte, argonSaltLen)
return "", ErrBusy if _, err := rand.Read(salt); err != nil {
return "", err
} }
defer release()
var salt [argonSaltLen]byte hash := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
if _, err := rand.Read(salt[:]); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
hash := argon2.IDKey([]byte(plain), salt[:], argonTime, argonMemory, argonThreads, argonKeyLen)
return "$argon2id$v=19$m=19456,t=2,p=1$" + return "argon2id$" +
base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(salt) + "$" +
base64.RawStdEncoding.EncodeToString(hash), nil base64.RawStdEncoding.EncodeToString(hash), nil
} }
func Verify(plain, encoded string) (Verification, error) { func Verify(plain, encoded string) bool {
p, ok := parse(encoded) parts := strings.Split(encoded, "$")
if !ok { if len(parts) != 3 || parts[0] != "argon2id" {
return Verification{}, nil
}
if p.memory > argonMemory {
if !acquireLegacy() {
return Verification{}, ErrBusy
}
defer releaseLegacy()
} else {
if !acquire() {
return Verification{}, ErrBusy
}
defer release()
}
actual := argon2.IDKey([]byte(plain), p.salt[:], p.time, p.memory, p.threads, argonKeyLen)
if subtle.ConstantTimeCompare(actual, p.hash[:]) != 1 {
return Verification{}, nil
}
obsolete := p.memory != argonMemory || p.time != argonTime || p.threads != argonThreads
return Verification{Match: true, NeedsRehash: p.isLegacy || obsolete}, nil
}
// DummyVerify spends the same derivation budget as Verify for a caller that
// cannot prove a match, so an unknown username is not cheaper than a known one.
func DummyVerify(plain string) error {
if !acquire() {
return ErrBusy
}
defer release()
var salt [argonSaltLen]byte
_ = argon2.IDKey([]byte(plain), salt[:], argonTime, argonMemory, argonThreads, argonKeyLen)
return nil
}
func acquire() bool {
select {
case derivations <- struct{}{}:
return true
default:
return false return false
} }
}
func release() { salt, err := base64.RawStdEncoding.DecodeString(parts[1])
<-derivations if err != nil {
}
func acquireLegacy() bool {
select {
case legacyDerivations <- struct{}{}:
return true
default:
return false return false
} }
}
func releaseLegacy() { expected, err := base64.RawStdEncoding.DecodeString(parts[2])
<-legacyDerivations if err != nil || len(salt) != argonSaltLen || len(expected) != argonKeyLen {
} return false
func parse(encoded string) (parameters, bool) {
if len(encoded) > maxEncodedLen {
return parameters{}, false
}
var p parameters
var payload string
switch {
case strings.HasPrefix(encoded, "argon2id$"):
p.memory, p.time, p.threads, p.isLegacy = 64*1024, 1, 4, true
payload = strings.TrimPrefix(encoded, "argon2id$")
case strings.HasPrefix(encoded, "$argon2id$v=19$"):
body := strings.TrimPrefix(encoded, "$argon2id$v=19$")
costs, rest, hasPayload := strings.Cut(body, "$")
memoryPart, restCosts, hasMemory := strings.Cut(costs, ",")
timePart, threadsPart, hasTime := strings.Cut(restCosts, ",")
complete := hasPayload && hasMemory && hasTime
if !complete {
return parameters{}, false
}
memory, okMemory := cost(memoryPart, "m=", 64*1024)
iterations, okTime := cost(timePart, "t=", 4)
threads, okThreads := cost(threadsPart, "p=", 4)
validCosts := okMemory && okTime && okThreads
if !validCosts || threads > 4 || memory < 8*threads {
return parameters{}, false
}
p.memory, p.time, p.threads = memory, iterations, uint8(threads)
payload = rest
default:
return parameters{}, false
}
salt, hash, hasHash := strings.Cut(payload, "$")
if !hasHash {
return parameters{}, false
} }
if len(salt) != 22 || len(hash) != 43 { actual := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return parameters{}, false
}
encoding := base64.RawStdEncoding.Strict()
if n, err := encoding.Decode(p.salt[:], []byte(salt)); err != nil || n != argonSaltLen {
return parameters{}, false
}
if n, err := encoding.Decode(p.hash[:], []byte(hash)); err != nil || n != argonKeyLen {
return parameters{}, false
}
return p, true
}
func cost(encoded, prefix string, maximum uint32) (uint32, bool) { return subtle.ConstantTimeCompare(actual, expected) == 1
if !strings.HasPrefix(encoded, prefix) {
return 0, false
}
value := strings.TrimPrefix(encoded, prefix)
if len(value) == 0 || value[0] == '0' {
return 0, false
}
for _, digit := range value {
if digit < '0' || digit > '9' {
return 0, false
}
}
n, err := strconv.ParseUint(value, 10, 32)
if err != nil || n == 0 || n > uint64(maximum) {
return 0, false
}
return uint32(n), true
} }
+5 -14
View File
@@ -12,14 +12,8 @@ import (
func TestHashVerifyRoundTrip(t *testing.T) { func TestHashVerifyRoundTrip(t *testing.T) {
encoded, err := password.Hash("very-secret-password") encoded, err := password.Hash("very-secret-password")
require.NoError(t, err) require.NoError(t, err)
verified, err := password.Verify("very-secret-password", encoded) require.True(t, password.Verify("very-secret-password", encoded))
require.NoError(t, err) require.False(t, password.Verify("wrong-password-value", encoded))
require.True(t, verified.Match)
require.False(t, verified.NeedsRehash)
verified, err = password.Verify("wrong-password-value", encoded)
require.NoError(t, err)
require.False(t, verified.Match)
require.False(t, verified.NeedsRehash)
} }
func TestHashIsSalted(t *testing.T) { func TestHashIsSalted(t *testing.T) {
@@ -33,10 +27,7 @@ func TestHashIsSalted(t *testing.T) {
} }
func TestVerifyRejectsMalformedHash(t *testing.T) { func TestVerifyRejectsMalformedHash(t *testing.T) {
for _, encoded := range []string{"", "plain-text", strings.Repeat("x", 64)} { require.False(t, password.Verify("very-secret-password", ""))
verified, err := password.Verify("very-secret-password", encoded) require.False(t, password.Verify("very-secret-password", "plain-text"))
require.NoError(t, err) require.False(t, password.Verify("very-secret-password", strings.Repeat("x", 64)))
require.False(t, verified.Match)
require.False(t, verified.NeedsRehash)
}
} }
@@ -1,84 +0,0 @@
package password
import (
"encoding/base64"
"strings"
"testing"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/argon2"
)
func TestVerifyRejectsMalformedAndCostlyPHCBeforeDerivation(t *testing.T) {
salt := base64.RawStdEncoding.EncodeToString(make([]byte, argonSaltLen))
hash := base64.RawStdEncoding.EncodeToString(make([]byte, argonKeyLen))
prefix := "$argon2id$v=19$"
suffix := "$" + salt + "$" + hash
invalid := []string{
strings.Repeat("x", 513),
prefix + "m=65537,t=2,p=1" + suffix,
prefix + "m=19456,t=5,p=1" + suffix,
prefix + "m=19456,t=2,p=5" + suffix,
prefix + "m=7,t=2,p=1" + suffix,
prefix + "m=31,t=2,p=4" + suffix,
prefix + "m=0,t=2,p=1" + suffix,
prefix + "m=19456,t=0,p=1" + suffix,
prefix + "m=19456,t=2,p=0" + suffix,
prefix + "m=-1,t=2,p=1" + suffix,
prefix + "m=+19456,t=2,p=1" + suffix,
prefix + "m=019456,t=2,p=1" + suffix,
prefix + "m=4294967296,t=2,p=1" + suffix,
prefix + "m=19456,t=2,p=1,x=1" + suffix,
prefix + "m=19456,t=2,t=1" + suffix,
"$argon2id$v=16$m=19456,t=2,p=1" + suffix,
prefix + "m=19456,t=2,p=1$" + salt + "$" + hash[:42] + "!",
prefix + "m=19456,t=2,p=1$" + salt + "=$" + hash,
"argon2id$" + salt + "$" + hash + "$extra",
}
// Exhausting the budget proves these inputs never reach Argon2: a valid
// encoding returns ErrBusy here, while malformed encodings are denied.
require.True(t, acquire())
defer release()
require.True(t, acquire())
defer release()
for _, encoded := range invalid {
got, err := Verify("password", encoded)
require.NoError(t, err)
require.False(t, got.Match)
require.False(t, got.NeedsRehash)
}
}
func TestDerivationBudgetIsNonblockingAndShared(t *testing.T) {
encoded, err := Hash("secret-password")
require.NoError(t, err)
require.True(t, acquire())
defer release()
require.True(t, acquire())
defer release()
require.False(t, acquire())
_, err = Hash("secret-password")
require.ErrorIs(t, err, ErrBusy)
_, err = Verify("secret-password", encoded)
require.ErrorIs(t, err, ErrBusy)
}
func TestLegacyAndObsoletePHCRequireOnlySuccessfulRehash(t *testing.T) {
var salt [argonSaltLen]byte
legacy := argon2.IDKey([]byte("secret-password"), salt[:], 1, 64*1024, 4, argonKeyLen)
legacyEncoded := "argon2id$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
base64.RawStdEncoding.EncodeToString(legacy)
obsolete := argon2.IDKey([]byte("secret-password"), salt[:], 1, 32, 1, argonKeyLen)
obsoleteEncoded := "$argon2id$v=19$m=32,t=1,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
base64.RawStdEncoding.EncodeToString(obsolete)
for _, encoded := range []string{legacyEncoded, obsoleteEncoded} {
got, err := Verify("wrong-password", encoded)
require.NoError(t, err)
require.False(t, got.Match)
require.False(t, got.NeedsRehash)
got, err = Verify("secret-password", encoded)
require.NoError(t, err)
require.True(t, got.Match)
require.True(t, got.NeedsRehash)
}
}

Some files were not shown because too many files have changed in this diff Show More