ЛР7: HTTPS/mTLS, шлюзы идентичности, OpenBao и защищённые зависимости

This commit is contained in:
Ivan Melnikov
2026-12-06 17:19:12 +03:00
parent 7d5fd459d6
commit 52e49fa02f
58 changed files with 4637 additions and 273 deletions
+110 -31
View File
@@ -1,41 +1,120 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0
APP_PORT=8080
# Lab7 local teaching stand. Copy to .env with `make env`.
# This file contains NO secret values: every credential, leaf key and CA lives
# in the ignored .local-secrets/ directory and is mounted read-only through
# compose secrets. The public entrypoint is HTTPS on loopback only.
#
# Mapping of the skeleton's logical names to this implementation:
# DATABASE_URL_FILE -> OpenBao secret/lab7/{api,worker}.database_url
# CACHE_URL_FILE -> OpenBao cache_url (Valkey session store over TLS)
# BROKER_URL_FILE -> OpenBao broker_url (Valkey Streams over mTLS)
# S3_*_FILE -> OpenBao s3_access_key / s3_secret_key
# TLS_* -> per-service leaf files mounted from .local-secrets/pki
# BAO_* -> AppRole files and service CA, never a root token
COMPOSE_PROJECT_NAME=mtusi-lab7-melnikov
APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
LOG_LEVEL=info
APP_VERSION=1.0.0
# Public HTTPS ingress. Only the load balancer publishes a port; the API
# replicas listen on the internal network and require mTLS from the LB.
LB_PORT=8447
PUBLIC_BASE_URL=https://localhost:8447
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
S3_ENDPOINT=https://s3:9000
API_CPU_LIMIT=0.5
API_MEM_LIMIT=192M
GOMEMLIMIT=160MiB
WORKER_CPU_LIMIT=0.5
WORKER_MEM_LIMIT=320M
WORKER_GOMEMLIMIT=224MiB
WORKER_CONCURRENCY=1
JOB_TIMEOUT_SECONDS=60
JOB_LEASE_SECONDS=90
# Stateful services. They keep writable data volumes; harden with
# no-new-privileges and explicit resource limits instead of read_only.
POSTGRES_CPU_LIMIT=0.5
POSTGRES_MEM_LIMIT=320M
VALKEY_CPU_LIMIT=0.1
VALKEY_MEM_LIMIT=72M
BROKER_CPU_LIMIT=0.2
BROKER_MEM_LIMIT=112M
S3_CPU_LIMIT=0.4
S3_MEM_LIMIT=384M
OPENBAO_CPU_LIMIT=0.3
OPENBAO_MEM_LIMIT=144M
COLLECTOR_CPU_LIMIT=0.4
COLLECTOR_MEM_LIMIT=192M
COLLECTOR_GOMEMLIMIT=120MiB
PROMETHEUS_CPU_LIMIT=0.3
PROMETHEUS_MEM_LIMIT=224M
LOKI_CPU_LIMIT=0.3
LOKI_MEM_LIMIT=192M
TEMPO_CPU_LIMIT=0.3
TEMPO_MEM_LIMIT=288M
TEMPO_GOMEMLIMIT=220MiB
GRAFANA_CPU_LIMIT=0.3
GRAFANA_MEM_LIMIT=176M
LB_CPU_LIMIT=0.2
LB_MEM_LIMIT=64M
GATEWAY_CPU_LIMIT=0.2
GATEWAY_MEM_LIMIT=40M
# Business settings (unchanged contract from labs 5/6).
SESSION_TTL_SECONDS=3600
DB_MAX_CONNS=8
DB_MIN_CONNS=1
DB_CONNECT_TIMEOUT_SECONDS=3
DB_STATEMENT_TIMEOUT_SECONDS=3
DB_QUERY_TIMEOUT_SECONDS=3
CACHE_POOL_SIZE=8
CACHE_TIMEOUT_SECONDS=2
SHUTDOWN_TIMEOUT_SECONDS=6
SHUTDOWN_DRAIN_SECONDS=3
STARTUP_TIMEOUT_SECONDS=30
S3_REGION=us-east-1
S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
S3_TIMEOUT_SECONDS=10
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2
UPLOAD_DECODE_CONCURRENCY=1
S3_PUT_CONCURRENCY=1
MAX_BODY_BYTES=1048576
IDEMPOTENCY_TTL_SECONDS=86400
OUTBOX_POLL_MS=200
OUTBOX_BATCH=10
JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400
OTEL_SERVICE_NAME=messenger-api
# Worker must set a distinct service.name.
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
PUBLIC_BASE_URL=https://localhost:8443
TLS_CA_FILE=/run/secrets/ca.crt
TLS_CERT_FILE=/run/secrets/service.crt
TLS_KEY_FILE=/run/secrets/service.key
BAO_ADDR=https://openbao:8200
BAO_CACERT=/run/secrets/bao-ca.crt
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
JOB_BACKOFF_BASE_SECONDS=1
JOB_BACKOFF_MAX_SECONDS=30
STAGING_RETENTION_SECONDS=3600
PIPELINE_VERSION=1
BROKER_STREAM=lab7:attachments:jobs
BROKER_GROUP=lab7-attachment-workers
# Password storage: OWASP Argon2id minimum, stored per-hash in PHC format.
ARGON2_MEMORY_KIB=19456
ARGON2_ITERATIONS=2
ARGON2_PARALLELISM=1
# Shared-across-replicas login rate limit (Valkey counters).
LOGIN_RATE_WINDOW_SECONDS=60
LOGIN_RATE_MAX_ATTEMPTS=5
LOGIN_RATE_MAX_PER_IP=20
# Telemetry stays inside the trusted network; the OTLP endpoint is the
# mTLS gateway, never a storage backend.
OTEL_SDK_DISABLED=false
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-gw:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_TRACES_SAMPLER=parentbased_always_on
OTEL_TRACES_SAMPLER_ARG=1.0
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
# Local administrative interfaces are bound to 127.0.0.1 only.
PROMETHEUS_PORT=9097
LOKI_PORT=3107
TEMPO_PORT=3207
GRAFANA_PORT=3007
OPENBAO_PORT=8207
+5
View File
@@ -30,3 +30,8 @@ coverage/
.vscode/
# Keep small, sanitized evidence summaries in evidence/ under version control.
# Inspect git diff --cached: ignore rules are not a secret scanner.
# Lab7 local operator material: CAs, leaf keys, passwords, DSNs, OpenBao
# init shares, AppRole secret-ids and rendered provisioning containing keys.
.local-secrets/
.scratch/
+81
View File
@@ -0,0 +1,81 @@
# syntax=docker/dockerfile:1
# Compile stage. Dependencies are vendored, so the build needs no module proxy
# and the same source tree produces the same binaries from a clean clone.
FROM golang:1.26.0-alpine3.23@sha256:d4c4845f5d60c6a974c6000ce58ae079328d03ab7f721a0734277e69905473e5 AS build
WORKDIR /src
# The teaching VM has 2 vCPU / 2 GiB. Serial package compilation keeps the
# peak compiler RSS bounded while the observability plane is running.
ENV CGO_ENABLED=0 \
GOTOOLCHAIN=local \
GOMAXPROCS=1 \
GOFLAGS=-mod=vendor\ -p=1
COPY go.mod go.sum ./
COPY vendor ./vendor
COPY cmd ./cmd
COPY internal ./internal
ARG VERSION=1.0.0
ARG REVISION=unknown
RUN go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.version=${VERSION} -X main.revision=${REVISION}" \
-o /out/messenger ./cmd/messenger \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.version=${VERSION} -X main.revision=${REVISION}" \
-o /out/worker ./cmd/worker \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/migrate ./cmd/migrate \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/s3bootstrap ./cmd/s3bootstrap \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/s3ctl ./cmd/s3ctl \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/jobctl ./cmd/jobctl \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/dbinit ./cmd/dbinit \
&& go build -trimpath -buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/securityprobe ./cmd/securityprobe
# Runtime stage: minimal Alpine pinned by digest. The process runs as the
# unprivileged uid 10001 and never needs a shell or package manager.
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 AS runtime
LABEL org.opencontainers.image.title="mtusi-messenger-lab7" \
org.opencontainers.image.description="MTUSI highload lab 7: HTTPS/mTLS, OpenBao and least privilege" \
org.opencontainers.image.version="1.0.0"
WORKDIR /app
COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
COPY --from=build --chown=10001:10001 /out/worker /app/worker
COPY --from=build --chown=10001:10001 /out/migrate /app/migrate
COPY --from=build --chown=10001:10001 /out/s3bootstrap /app/s3bootstrap
COPY --from=build --chown=10001:10001 /out/s3ctl /app/s3ctl
COPY --from=build --chown=10001:10001 /out/jobctl /app/jobctl
COPY --from=build --chown=10001:10001 /out/dbinit /app/dbinit
COPY --from=build --chown=10001:10001 /out/securityprobe /app/securityprobe
USER 10001:10001
EXPOSE 8443
ENV APP_HOST=0.0.0.0 \
APP_PORT=8443 \
APP_ENV=lab \
LOG_LEVEL=info \
SESSION_TTL_SECONDS=3600 \
SHUTDOWN_TIMEOUT_SECONDS=6 \
SHUTDOWN_DRAIN_SECONDS=3
# The same API binary implements -healthcheck (mTLS loopback), so the image
# needs no curl/wget.
HEALTHCHECK --interval=3s --timeout=3s --start-period=15s --retries=3 \
CMD ["/app/messenger", "-healthcheck"]
ENTRYPOINT ["/app/messenger"]
+150 -9
View File
@@ -1,13 +1,44 @@
PYTHON ?= python3
BASE_URL ?= https://localhost:8443
CA_FILE ?=
ACTION_SCRIPT ?=
GO ?= go
GOTOOLCHAIN ?= go1.26.0
export GOTOOLCHAIN
BASE_URL ?= https://localhost:8447
CA_FILE ?= $(wildcard .local-secrets/pki/edge-ca.crt)
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
ACTION_SCRIPT ?=
COMPOSE ?= ./scripts/compose.sh
COMPOSE_ARGS = --env-file .env
IMAGE ?= mtusi-messenger-lab7-melnikov:local
GIT_REVISION ?= $(shell git rev-parse HEAD 2>/dev/null || echo unknown)
export GIT_REVISION
export API_IMAGE ?= $(IMAGE)
.PHONY: help check validate test load test-persistence test-failover test-security
PROMETHEUS_URL ?= http://127.0.0.1:9097
LOKI_URL ?= http://127.0.0.1:3107
TEMPO_URL ?= http://127.0.0.1:3207
GRAFANA_URL ?= https://localhost:3007
COLLECTOR_METRICS_URL ?= http://127.0.0.1:8887
.PHONY: help check validate env up wait wait-telemetry build-image docker-config stop down purge logs ps \
test load test-security test-tls test-openbao test-ratelimit test-container test-attachment \
test-lifecycle test-track2 test-retry test-persistence test-failover test-student test-student-race \
test-hardening test-telemetry-restart test-observability test-incidents test-track1 \
py39 scan collect-evidence clean-clone openbao-unseal openbao-seal rotate-secret rotate-leaf
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "env: local CA/secrets/AppRole bootstrap (no values printed)"
@echo "up: build and start the full stand; wait: HTTPS LB readiness; wait-telemetry: stores"
@echo "check/validate: offline contract checks; test/test-security: public HTTPS checks"
@echo "test-tls: internal mTLS identity/CRL/allow-deny matrix"
@echo "test-openbao: scoped policies, AppRole TTL and denied paths"
@echo "test-ratelimit: shared login limit, 429/Retry-After and KDF budget"
@echo "test-container/test-hardening: namespaces, caps, read_only, ports, users"
@echo "test-student: Go tests + own black-box suite over HTTPS"
@echo "test-persistence ACTION_SCRIPT=scripts/restart.sh; test-failover ACTION_SCRIPT=scripts/stop-one.sh"
@echo "test-track1: worker-compromise / least-privilege experiment on the isolated stand"
@echo "py39: own Python checks on the promised minimum; scan: dependency/image scan triage"
@echo "clean-clone: build and smoke a fresh clone with empty volumes"
@echo "openbao-unseal/openbao-seal/rotate-secret/rotate-leaf: documented operator drills"
check:
$(PYTHON) scripts/check_contract.py
@@ -15,19 +46,129 @@ check:
validate:
$(PYTHON) scripts/validate_openapi.py
env:
./scripts/bootstrap-local.sh
up:
@test -f .env || (echo "Run make env first" >&2; exit 2)
@test -f .local-secrets/approle/api.secret_id || (echo "Run make env first" >&2; exit 2)
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) up -d --build
./scripts/wait-ready.sh
./scripts/wait-telemetry.sh
wait:
./scripts/wait-ready.sh
wait-telemetry:
./scripts/wait-telemetry.sh
build-image:
@test -f .env || (echo "Run make env first" >&2; exit 2)
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) build api
docker-config:
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) config --quiet
stop:
$(COMPOSE) $(COMPOSE_ARGS) stop
down:
$(COMPOSE) $(COMPOSE_ARGS) down
purge:
@echo "PURGE removes containers AND named volumes mtusi-lab7-melnikov-*: all synthetic data is lost."
$(COMPOSE) $(COMPOSE_ARGS) down -v
logs:
$(COMPOSE) $(COMPOSE_ARGS) logs --tail=120 api worker broker-gw s3-gw otel-gw openbao
ps:
$(COMPOSE) $(COMPOSE_ARGS) ps
test:
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-tls:
$(PYTHON) student-tests/tls-matrix.py --base-url "$(BASE_URL)" --ca-file "$(CA_FILE)"
test-openbao:
$(PYTHON) student-tests/openbao_policy.py
test-ratelimit:
$(PYTHON) student-tests/rate_limit.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-container test-hardening:
$(PYTHON) scripts/container-checks.py
test-student:
$(GO) test -count=1 ./...
$(PYTHON) student-tests/blackbox.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-student-race:
$(GO) test -race -count=1 ./...
test-attachment:
$(PYTHON) student-tests/attachment-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-lifecycle:
$(PYTHON) student-tests/lifecycle.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-track2:
$(PYTHON) student-tests/track2.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-retry:
$(PYTHON) student-tests/retry.py --base-url "$(BASE_URL)" --tempo-url "$(TEMPO_URL)" $(TLS_ARGS)
test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook" >&2; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook" >&2; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-observability:
$(PYTHON) student-tests/observability.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" \
--loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" --grafana-url "$(GRAFANA_URL)" $(TLS_ARGS)
test-telemetry-restart:
$(PYTHON) student-tests/observability.py --restart-backends --base-url "$(BASE_URL)" \
--prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" \
--grafana-url "$(GRAFANA_URL)" $(TLS_ARGS)
test-incidents:
$(PYTHON) student-tests/incidents.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" \
--collector-url "$(COLLECTOR_METRICS_URL)" --grafana-url "$(GRAFANA_URL)"
test-track1:
$(PYTHON) student-tests/track1.py --base-url "$(BASE_URL)" $(TLS_ARGS)
py39:
./scripts/py39-tests.sh
scan:
./scripts/scan.sh
collect-evidence:
./scripts/collect-evidence.sh
clean-clone:
./scripts/clean-clone-check.sh
openbao-unseal:
$(COMPOSE) $(COMPOSE_ARGS) run --rm --no-deps openbao-bootstrap unseal-only
openbao-seal:
./scripts/openbao-seal.sh
rotate-secret:
./scripts/rotate-worker-secret.sh
rotate-leaf:
./scripts/rotate-lb-identity.sh
+217
View File
@@ -0,0 +1,217 @@
// Command dbinit applies the lab7 PostgreSQL least-privilege roles.
//
// It runs as an operator one-shot with the database superuser DSN. API and
// worker never receive that DSN: they obtain their own role DSN from OpenBao.
// Two phases are used because the migration role needs CREATE on the schema
// before migrations and the runtime roles need table privileges afterwards.
//
// go run ./cmd/dbinit -phase roles
// go run ./cmd/dbinit -phase grants
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net/url"
"os"
"strings"
"time"
"github.com/jackc/pgx/v5"
)
var tables = []string{
"users", "chats", "chat_members", "messages", "message_attachments",
"message_idempotency", "attachments", "attachment_variants",
"attachment_jobs", "job_audit", "outbox",
}
func main() {
phase := flag.String("phase", "grants", "roles or grants")
flag.Parse()
adminURL := secret("DATABASE_ADMIN_URL")
if adminURL == "" {
fail("DATABASE_ADMIN_URL or DATABASE_ADMIN_URL_FILE is required")
}
passwords := map[string]string{
"messenger_migrate": secret("POSTGRES_MIGRATE_PASSWORD"),
"messenger_api": secret("POSTGRES_API_PASSWORD"),
"messenger_worker": secret("POSTGRES_WORKER_PASSWORD"),
}
for role, password := range passwords {
if password == "" {
fail("password for " + role + " is missing")
}
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
conn, err := pgx.Connect(ctx, adminURL)
if err != nil {
fail("connect as database operator: " + err.Error())
}
defer func() { _ = conn.Close(context.Background()) }()
switch *phase {
case "roles":
if err := applyRoles(ctx, conn, passwords); err != nil {
fail("roles phase: " + err.Error())
}
fmt.Println(`{"phase":"roles","roles":["messenger_migrate","messenger_api","messenger_worker"],"public_schema_create":"revoked"}`)
case "grants":
if err := applyGrants(ctx, conn); err != nil {
fail("grants phase: " + err.Error())
}
result, err := probeLeastPrivilege(ctx, adminURL, passwords["messenger_worker"])
if err != nil {
fail("least-privilege probe: " + err.Error())
}
encoded, _ := json.Marshal(result)
fmt.Println(string(encoded))
default:
fail("-phase must be roles or grants")
}
}
func applyRoles(ctx context.Context, conn *pgx.Conn, passwords map[string]string) error {
if _, err := conn.Exec(ctx, `DO $do$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_migrate') THEN
CREATE ROLE messenger_migrate LOGIN;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_api') THEN
CREATE ROLE messenger_api LOGIN;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_worker') THEN
CREATE ROLE messenger_worker LOGIN;
END IF;
END
$do$;`); err != nil {
return err
}
for role, password := range passwords {
// Passwords are generated locally as [A-Za-z0-9], but quote defensively
// anyway. The value is never printed.
literal := "'" + strings.ReplaceAll(password, "'", "''") + "'"
statement := fmt.Sprintf(`ALTER ROLE %s WITH LOGIN PASSWORD %s NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS`,
pgx.Identifier{role}.Sanitize(), literal)
if _, err := conn.Exec(ctx, statement); err != nil {
return fmt.Errorf("alter role %s: %w", role, err)
}
}
if _, err := conn.Exec(ctx, `REVOKE CREATE ON SCHEMA public FROM PUBLIC`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT USAGE, CREATE ON SCHEMA public TO messenger_migrate`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker`); err != nil {
return err
}
return nil
}
func applyGrants(ctx context.Context, conn *pgx.Conn) error {
// API: ordinary DML on business tables, no DDL, no schema ownership.
apiTables := strings.Join(quoted(tables), ", ")
if _, err := conn.Exec(ctx, `GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE `+apiTables+` TO messenger_api`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO messenger_api`); err != nil {
return err
}
// Worker: the pipeline state only. It cannot read users, chats, messages or
// API session material, and it cannot create or drop tables.
if _, err := conn.Exec(ctx, `GRANT SELECT, UPDATE ON TABLE attachments, attachment_jobs TO messenger_worker`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT SELECT, INSERT, UPDATE ON TABLE attachment_variants TO messenger_worker`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT INSERT ON TABLE job_audit TO messenger_worker`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT SELECT, INSERT ON TABLE outbox TO messenger_worker`); err != nil {
return err
}
if _, err := conn.Exec(ctx, `GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO messenger_worker`); err != nil {
return err
}
// Future tables created by the migration role get API privileges; worker
// grants stay explicit because they must stay narrow.
if _, err := conn.Exec(ctx, `ALTER DEFAULT PRIVILEGES FOR ROLE messenger_migrate IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO messenger_api`); err != nil {
return err
}
return nil
}
// probeLeastPrivilege proves the boundary at bootstrap: the worker role can
// read its own queue state but cannot read the users table. It never prints a
// DSN or password.
func probeLeastPrivilege(ctx context.Context, adminURL, workerPassword string) (map[string]any, error) {
parsed, err := url.Parse(adminURL)
if err != nil {
return nil, fmt.Errorf("parse operator DSN: %w", err)
}
parsed.User = url.UserPassword("messenger_worker", workerPassword)
// database/sql URL escaping is accepted by pgx.
workerDSN := parsed.String()
conn, err := pgx.Connect(ctx, workerDSN)
if err != nil {
return nil, fmt.Errorf("connect as messenger_worker: %w", err)
}
defer func() { _ = conn.Close(context.Background()) }()
var pipelineRows int
if err := conn.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs`).Scan(&pipelineRows); err != nil {
return nil, fmt.Errorf("worker cannot read its own queue table: %w", err)
}
var usersAllowed bool
var usersRows int
err = conn.QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&usersRows)
if err == nil {
usersAllowed = true
} else if !strings.Contains(strings.ToLower(err.Error()), "permission denied") {
return nil, fmt.Errorf("unexpected worker users probe error: %w", err)
}
var sessionsAllowed bool
var sessionRows int
err = conn.QueryRow(ctx, `SELECT count(*) FROM schema_migrations`).Scan(&sessionRows)
if err == nil {
sessionsAllowed = true
} else if !strings.Contains(strings.ToLower(err.Error()), "permission denied") {
return nil, fmt.Errorf("unexpected worker schema probe error: %w", err)
}
return map[string]any{
"phase": "grants",
"worker_attachment_jobs_rows": pipelineRows,
"worker_can_read_users": usersAllowed,
"worker_can_read_schema": sessionsAllowed,
}, nil
}
func quoted(values []string) []string {
result := make([]string, 0, len(values))
for _, value := range values {
result = append(result, pgx.Identifier{value}.Sanitize())
}
return result
}
// secret resolves NAME_FILE before NAME and never echoes the value.
func secret(name string) string {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err == nil {
return strings.TrimSpace(string(data))
}
return ""
}
return strings.TrimSpace(os.Getenv(name))
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "dbinit:", message)
os.Exit(1)
}
+22 -3
View File
@@ -13,12 +13,14 @@ import (
"flag"
"fmt"
"os"
"strings"
"time"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/job"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/tlsutil"
"mtusi.ru/messenger-lab7/internal/uuid"
)
@@ -113,7 +115,7 @@ func main() {
if *streamID == "" {
fail("-stream-id is required for -op withdraw")
}
transport, err := broker.Open(ctx, broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second})
transport, err := broker.Open(ctx, brokerConfig(cfg))
if err != nil {
fail("broker unavailable: " + err.Error())
}
@@ -123,7 +125,7 @@ func main() {
}
printJSON(map[string]any{"withdrawn_stream_id": *streamID})
case "stream":
transport, err := broker.Open(ctx, broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second})
transport, err := broker.Open(ctx, brokerConfig(cfg))
if err != nil {
fail("broker unavailable: " + err.Error())
}
@@ -158,7 +160,7 @@ func main() {
}
func duplicate(ctx context.Context, cfg config.Config, repository *store.Store, attachmentID, jobID string, attemptOverride int) {
transport, err := broker.Open(ctx, broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second})
transport, err := broker.Open(ctx, brokerConfig(cfg))
if err != nil {
fail("broker unavailable: " + err.Error())
}
@@ -235,3 +237,20 @@ func fail(message string) {
fmt.Fprintln(os.Stderr, "jobctl:", message)
os.Exit(1)
}
func brokerConfig(cfg config.Config) broker.Config {
serverName := strings.TrimSpace(os.Getenv("BROKER_SERVER_NAME"))
if serverName == "" {
serverName = "broker-gw"
}
tlsConfig, err := tlsutil.ClientConfig(
cfg.BrokerCAFile,
cfg.BrokerClientCert,
cfg.BrokerClientKey,
serverName,
)
if err != nil {
fail("broker TLS configuration failed: " + err.Error())
}
return broker.Config{URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 3 * time.Second, TLS: tlsConfig}
}
+114 -15
View File
@@ -5,6 +5,9 @@ package main
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"errors"
"flag"
"fmt"
@@ -20,6 +23,7 @@ import (
"time"
"mtusi.ru/messenger-lab7/internal/api"
"mtusi.ru/messenger-lab7/internal/auth"
"mtusi.ru/messenger-lab7/internal/broker"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/objectstore"
@@ -27,6 +31,7 @@ import (
"mtusi.ru/messenger-lab7/internal/session"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
"mtusi.ru/messenger-lab7/internal/tlsutil"
"mtusi.ru/messenger-lab7/internal/uuid"
)
@@ -48,7 +53,15 @@ func main() {
os.Exit(2)
}
if *healthcheck {
os.Exit(runHealthcheck(cfg))
os.Exit(runHealthcheck())
}
if !cfg.TLSEnabled {
fmt.Fprintln(os.Stderr, "configuration error: TLS must be enabled for the public API; plaintext serving is not supported")
os.Exit(2)
}
if err := auth.Configure(cfg.ArgonMemoryKiB, cfg.ArgonIterations, cfg.ArgonParallelism); err != nil {
fmt.Fprintln(os.Stderr, "configuration error:", err)
os.Exit(2)
}
ctx := context.Background()
@@ -64,6 +77,10 @@ func main() {
os.Exit(2)
}
logger := telemetryProvider.Logger()
if cfg.OpenBao != nil {
go cfg.OpenBao.RunRenewal(ctx, logger)
logger.Info("OpenBao service identity acquired", "token_ttl_seconds", int(cfg.OpenBaoTokenTTL.Seconds()))
}
shutdownTelemetry := func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
@@ -91,11 +108,17 @@ func main() {
os.Exit(1)
}
cacheTLS, err := clientTLS("session store", cfg.CacheCAFile, cfg.CacheClientCert, cfg.CacheClientKey, defaultValue(cfg.CacheServerName, "session-gw"))
if err != nil {
logger.Error("session store TLS configuration failed", "error", err)
os.Exit(2)
}
sessions, err := session.Open(cfg.CacheURL, session.Options{
PoolSize: cfg.CachePoolSize,
DialTimeout: cfg.CacheTimeout,
IOTimeout: cfg.CacheTimeout,
TTL: cfg.SessionTTL,
TLS: cacheTLS,
})
if err != nil {
logger.Error("session store configuration failed", "error", err)
@@ -103,6 +126,11 @@ func main() {
}
defer func() { _ = sessions.Close() }()
s3TLS, err := clientTLS("S3 gateway", cfg.S3CAFile, cfg.S3ClientCertFile, cfg.S3ClientKeyFile, defaultValue(cfg.S3ServerName, "s3-gw"))
if err != nil {
logger.Error("S3 TLS configuration failed", "error", err)
os.Exit(2)
}
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
@@ -110,17 +138,24 @@ func main() {
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
TLS: s3TLS,
})
if err != nil {
logger.Error("object store configuration failed", "error", err)
os.Exit(2)
}
brokerTLS, err := clientTLS("broker gateway", cfg.BrokerCAFile, cfg.BrokerClientCert, cfg.BrokerClientKey, defaultValue(cfg.BrokerServerName, "broker-gw"))
if err != nil {
logger.Error("broker TLS configuration failed", "error", err)
os.Exit(2)
}
transport, err := broker.Open(ctx, broker.Config{
URL: cfg.BrokerURL,
Stream: cfg.BrokerStream,
Group: cfg.BrokerGroup,
Timeout: 3 * time.Second,
TLS: brokerTLS,
})
if err != nil {
logger.Error("broker configuration failed", "error", err)
@@ -138,6 +173,10 @@ func main() {
JobMaxAttempts: cfg.JobMaxAttempts,
Metrics: telemetryProvider.Instruments(),
Tracer: telemetryProvider.Tracer("messenger-api"),
MaxBodyBytes: cfg.MaxBodyBytes,
RateLimit: cfg.LoginRateAttempts,
RateLimitPerIP: cfg.LoginRatePerIP,
RateLimitWindow: cfg.LoginRateWindow,
})
if err != nil {
logger.Error("application initialization failed", "error", err)
@@ -153,12 +192,18 @@ func main() {
MaxHeaderBytes: 1 << 20,
}
serverTLS, err := tlsutil.ServerConfig(cfg.TLSCertFile, cfg.TLSKeyFile, cfg.TLSClientCAFile, cfg.TLSClientCRLFile, cfg.TLSAllowedCNs)
if err != nil {
logger.Error("serve TLS configuration failed", "error", err)
os.Exit(2)
}
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
listener, err := net.Listen("tcp", address)
if err != nil {
logger.Error("listen failed", "address", address, "error", err)
os.Exit(1)
}
listener = tls.NewListener(listener, serverTLS)
// Operator-only stats listener. It is bound to container loopback by
// default and is not published by compose, so it cannot bypass the LB.
@@ -212,6 +257,8 @@ func main() {
logger.Info("server listening",
"address", listener.Addr().String(),
"tls", true,
"mtls_client_identities", strings.Join(cfg.TLSAllowedCNs, ","),
"env", cfg.Env,
"instance_id", instanceID,
"version", version,
@@ -276,19 +323,38 @@ func main() {
}
}
// instanceIdentity is stable for the lifetime of this process and unique per
// container. INSTANCE_ID overrides it; otherwise the container hostname is the
// actual process identity, which lets scripts/stop-one.sh map an X-Instance-Id
// response to exactly one Docker container. lab7 replaces this with an opaque
// alias that does not reveal a hostname.
// instanceIdentity is a stable, opaque alias for the lifetime of this process.
// It is derived from the container hostname with SHA-256 so the public
// X-Instance-Id header never discloses a hostname or IP. scripts/stop-one.sh
// applies the same derivation to map the alias back to one container.
func instanceIdentity() string {
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
return value
}
if hostname, err := os.Hostname(); err == nil && strings.TrimSpace(hostname) != "" {
return hostname
hostname, err := os.Hostname()
if err != nil || strings.TrimSpace(hostname) == "" {
return "lab7-api-" + uuid.NewRandom(6)
}
return uuid.NewRandom(8)
sum := sha256.Sum256([]byte(hostname))
return "lab7-api-" + hex.EncodeToString(sum[:6])
}
func defaultValue(value, fallback string) string {
if strings.TrimSpace(value) != "" {
return value
}
return fallback
}
func clientTLS(label, caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
if caFile == "" {
return nil, fmt.Errorf("%s CA file is required", label)
}
config, err := tlsutil.ClientConfig(caFile, certFile, keyFile, serverName)
if err != nil {
return nil, fmt.Errorf("%s: %w", label, err)
}
return config, nil
}
func newLogger(cfg config.Config) *slog.Logger {
@@ -341,12 +407,45 @@ func pruneIdempotency(ctx context.Context, repository *store.Store, logger *slog
}
}
// runHealthcheck is compiled into the same binary as the server, so the
// runtime image needs no curl, wget or shell. It always talks to loopback
// inside the container, independently of APP_HOST.
func runHealthcheck(cfg config.Config) int {
client := &http.Client{Timeout: 2 * time.Second}
url := "http://127.0.0.1:" + strconv.Itoa(cfg.Port) + "/health/live"
// runHealthcheck is compiled into the same binary as the server, so the runtime
// image needs no curl, wget or shell. It talks to container loopback over TLS,
// presenting the API's own service certificate and verifying the server against
// the service CA. It deliberately does not contact OpenBao: a sealed OpenBao
// must not restart an API process that is still serving with its in-memory
// credentials.
func runHealthcheck() int {
port := 8443
if raw := strings.TrimSpace(os.Getenv("APP_PORT")); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && parsed < 65536 {
port = parsed
}
}
clientCert := os.Getenv("HEALTHCHECK_CLIENT_CERT_FILE")
clientKey := os.Getenv("HEALTHCHECK_CLIENT_KEY_FILE")
if clientCert == "" {
clientCert = os.Getenv("TLS_CERT_FILE")
}
if clientKey == "" {
clientKey = os.Getenv("TLS_KEY_FILE")
}
tlsConfig, err := tlsutil.ClientConfig(
os.Getenv("TLS_CLIENT_CA_FILE"),
clientCert,
clientKey,
defaultValue(os.Getenv("TLS_SERVER_NAME"), "api"),
)
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck TLS configuration failed:", err)
return 1
}
client := &http.Client{
Timeout: 3 * time.Second,
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
Proxy: nil,
},
}
url := "https://127.0.0.1:" + strconv.Itoa(port) + "/health/live"
response, err := client.Get(url) //nolint:gosec // fixed loopback URL built from a validated port
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck request failed:", err)
+522
View File
@@ -0,0 +1,522 @@
// Command pkitool is the local, operator-only PKI bootstrap for lab7.
//
// It creates two offline CAs in an ignored directory (by default
// .local-secrets/pki), issues short-lived leaf certificates, records every
// serial in a ledger and produces signed CRLs. Private keys are written with
// mode 0600 and are never read by the application containers: services receive
// only leaf certificates and public CA certificates.
//
// Examples:
//
// go run ./cmd/pkitool init
// go run ./cmd/pkitool issue -ca service -name api-server -cn api -profile server -sans api
// go run ./cmd/pkitool issue -ca service -name lb-client -cn lab7-lb -profile client
// go run ./cmd/pkitool revoke -name lb-client
// go run ./cmd/pkitool crl -ca service
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
const (
caValidity = 10 * 365 * 24 * time.Hour
defaultValid = 30 * 24 * time.Hour
)
type issuedCert struct {
Serial string `json:"serial"`
CA string `json:"ca"`
CN string `json:"cn"`
Profile string `json:"profile"`
SANs []string `json:"sans"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
CertFile string `json:"cert_file"`
KeyFile string `json:"key_file"`
RevokedAt time.Time `json:"revoked_at,omitempty"`
RevokeReason string `json:"revoke_reason,omitempty"`
}
type ledger struct {
NextCRLNumber int64 `json:"next_crl_number"`
Issued []issuedCert `json:"issued"`
}
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
var err error
switch os.Args[1] {
case "init":
err = cmdInit(os.Args[2:])
case "issue":
err = cmdIssue(os.Args[2:])
case "revoke":
err = cmdRevoke(os.Args[2:])
case "crl":
err = cmdCRL(os.Args[2:])
case "fingerprint":
err = cmdFingerprint(os.Args[2:])
default:
usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "pkitool:", err)
os.Exit(1)
}
}
func usage() {
fmt.Fprint(os.Stderr, `pkitool commands:
init [-dir DIR]
issue [-dir DIR] -ca edge|service -name NAME -cn CN -profile server|client|both [-sans dns,ip:1.2.3.4] [-validity 720h]
revoke [-dir DIR] -name NAME [-reason text]
crl [-dir DIR] -ca edge|service
fingerprint -file CERT
`)
}
func cmdInit(args []string) error {
fs := flag.NewFlagSet("init", flag.ContinueOnError)
dir := fs.String("dir", ".local-secrets/pki", "PKI directory")
if err := fs.Parse(args); err != nil {
return err
}
if err := os.MkdirAll(*dir, 0o700); err != nil {
return err
}
if err := ensureCA(*dir, "edge"); err != nil {
return err
}
if err := ensureCA(*dir, "service"); err != nil {
return err
}
if _, err := loadLedger(*dir); err != nil {
return err
}
fmt.Printf("PKI ready in %s (edge CA and service CA); private keys are local only\n", *dir)
return nil
}
func ensureCA(dir, name string) error {
certPath := filepath.Join(dir, name+"-ca.crt")
keyPath := filepath.Join(dir, name+"-ca.key")
if fileExists(certPath) && fileExists(keyPath) {
return nil
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
serial, err := randomSerial()
if err != nil {
return err
}
cn := "lab7-" + name + "-ca"
now := time.Now().UTC().Truncate(time.Second)
template := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{CommonName: cn, Organization: []string{"MTUSI lab7 synthetic stand"}},
NotBefore: now.Add(-5 * time.Minute),
NotAfter: now.Add(caValidity),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLenZero: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
return err
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
if err := writePEM(certPath, "CERTIFICATE", der, 0o644); err != nil {
return err
}
if err := writePEM(keyPath, "EC PRIVATE KEY", keyDER, 0o600); err != nil {
return err
}
return nil
}
func cmdIssue(args []string) error {
fs := flag.NewFlagSet("issue", flag.ContinueOnError)
dir := fs.String("dir", ".local-secrets/pki", "PKI directory")
caName := fs.String("ca", "", "CA name: edge or service")
name := fs.String("name", "", "output file base name")
cn := fs.String("cn", "", "subject common name")
profile := fs.String("profile", "both", "server, client or both")
sans := fs.String("sans", "", "comma-separated DNS names, or ip:ADDRESS")
validity := fs.Duration("validity", defaultValid, "leaf validity")
if err := fs.Parse(args); err != nil {
return err
}
if *caName != "edge" && *caName != "service" {
return errors.New("-ca must be edge or service")
}
if *name == "" || *cn == "" {
return errors.New("-name and -cn are required")
}
if strings.ContainsAny(*name, `/\\`) {
return errors.New("-name must be a plain file name")
}
caCert, caKey, err := loadCA(*dir, *caName)
if err != nil {
return err
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
serial, err := randomSerial()
if err != nil {
return err
}
now := time.Now().UTC().Truncate(time.Second)
dnss, ips, err := parseSANs(*sans)
if err != nil {
return err
}
template := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{CommonName: *cn, Organization: []string{"MTUSI lab7 synthetic stand"}},
NotBefore: now.Add(-2 * time.Minute),
NotAfter: now.Add(*validity),
KeyUsage: x509.KeyUsageDigitalSignature,
DNSNames: dnss,
IPAddresses: ips,
}
switch *profile {
case "server":
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
case "client":
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
case "both":
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}
default:
return errors.New("-profile must be server, client or both")
}
der, err := x509.CreateCertificate(rand.Reader, template, caCert, &key.PublicKey, caKey)
if err != nil {
return err
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
certPath := filepath.Join(*dir, *name+".crt")
keyPath := filepath.Join(*dir, *name+".key")
if err := writePEM(certPath, "CERTIFICATE", der, 0o644); err != nil {
return err
}
if err := writePEM(keyPath, "EC PRIVATE KEY", keyDER, 0o600); err != nil {
return err
}
record := issuedCert{
Serial: serial.String(),
CA: *caName,
CN: *cn,
Profile: *profile,
SANs: splitSANs(*sans),
NotBefore: template.NotBefore,
NotAfter: template.NotAfter,
CertFile: filepath.Base(certPath),
KeyFile: filepath.Base(keyPath),
}
book, err := loadLedger(*dir)
if err != nil {
return err
}
book.Issued = append(book.Issued, record)
if err := saveLedger(*dir, book); err != nil {
return err
}
fmt.Printf("issued %s (serial %s, CN %s, expires %s)\n", *name, record.Serial, *cn, record.NotAfter.Format(time.RFC3339))
return nil
}
func cmdRevoke(args []string) error {
fs := flag.NewFlagSet("revoke", flag.ContinueOnError)
dir := fs.String("dir", ".local-secrets/pki", "PKI directory")
name := fs.String("name", "", "issued certificate name")
reason := fs.String("reason", "keyCompromise", "revocation reason")
if err := fs.Parse(args); err != nil {
return err
}
if *name == "" {
return errors.New("-name is required")
}
book, err := loadLedger(*dir)
if err != nil {
return err
}
found := false
for i := range book.Issued {
entry := &book.Issued[i]
if strings.TrimSuffix(filepath.Base(entry.CertFile), ".crt") != *name {
continue
}
if entry.RevokedAt.IsZero() {
entry.RevokedAt = time.Now().UTC().Truncate(time.Second)
entry.RevokeReason = *reason
}
found = true
break
}
if !found {
return fmt.Errorf("certificate %q is not in the ledger", *name)
}
return saveLedger(*dir, book)
}
func cmdCRL(args []string) error {
fs := flag.NewFlagSet("crl", flag.ContinueOnError)
dir := fs.String("dir", ".local-secrets/pki", "PKI directory")
caName := fs.String("ca", "", "CA name: edge or service")
if err := fs.Parse(args); err != nil {
return err
}
if *caName != "edge" && *caName != "service" {
return errors.New("-ca must be edge or service")
}
caCert, caKey, err := loadCA(*dir, *caName)
if err != nil {
return err
}
book, err := loadLedger(*dir)
if err != nil {
return err
}
var revoked []pkix.RevokedCertificate
for _, entry := range book.Issued {
if entry.CA != *caName || entry.RevokedAt.IsZero() {
continue
}
serial, ok := new(big.Int).SetString(entry.Serial, 10)
if !ok {
return fmt.Errorf("invalid serial in ledger: %q", entry.Serial)
}
revoked = append(revoked, pkix.RevokedCertificate{
SerialNumber: serial,
RevocationTime: entry.RevokedAt,
})
}
sort.Slice(revoked, func(i, j int) bool { return revoked[i].SerialNumber.Cmp(revoked[j].SerialNumber) < 0 })
now := time.Now().UTC().Truncate(time.Second)
number := book.NextCRLNumber
if number < 1 {
number = 1
}
book.NextCRLNumber = number + 1
template := &x509.RevocationList{
RevokedCertificateEntries: make([]x509.RevocationListEntry, 0, len(revoked)),
Number: big.NewInt(number),
ThisUpdate: now,
NextUpdate: now.Add(24 * time.Hour),
}
for _, entry := range revoked {
template.RevokedCertificateEntries = append(template.RevokedCertificateEntries, x509.RevocationListEntry{
SerialNumber: entry.SerialNumber,
RevocationTime: entry.RevocationTime,
})
}
der, err := x509.CreateRevocationList(rand.Reader, template, caCert, caKey)
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(*dir, *caName+"-ca.crl"), der, 0o644); err != nil {
return err
}
if err := writePEM(filepath.Join(*dir, *caName+"-ca.crl.pem"), "X509 CRL", der, 0o644); err != nil {
return err
}
if err := saveLedger(*dir, book); err != nil {
return err
}
fmt.Printf("CRL %s number %d: %d revoked serial(s)\n", *caName, number, len(revoked))
return nil
}
func cmdFingerprint(args []string) error {
fs := flag.NewFlagSet("fingerprint", flag.ContinueOnError)
file := fs.String("file", "", "PEM certificate")
if err := fs.Parse(args); err != nil {
return err
}
if *file == "" {
return errors.New("-file is required")
}
cert, err := readCert(*file)
if err != nil {
return err
}
sum := sha256.Sum256(cert.Raw)
fmt.Printf("%s %s\n", hex.EncodeToString(sum[:]), cert.Subject.CommonName)
return nil
}
func loadCA(dir, name string) (*x509.Certificate, *ecdsa.PrivateKey, error) {
cert, err := readCert(filepath.Join(dir, name+"-ca.crt"))
if err != nil {
return nil, nil, fmt.Errorf("load %s CA certificate (run init first): %w", name, err)
}
key, err := readKey(filepath.Join(dir, name+"-ca.key"))
if err != nil {
return nil, nil, fmt.Errorf("load %s CA private key: %w", name, err)
}
return cert, key, nil
}
func readCert(path string) (*x509.Certificate, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil || block.Type != "CERTIFICATE" {
return nil, fmt.Errorf("%s is not a PEM certificate", path)
}
return x509.ParseCertificate(block.Bytes)
}
func readKey(path string) (*ecdsa.PrivateKey, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil {
return nil, fmt.Errorf("%s is not PEM", path)
}
switch block.Type {
case "EC PRIVATE KEY":
return x509.ParseECPrivateKey(block.Bytes)
case "PRIVATE KEY":
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
key, ok := parsed.(*ecdsa.PrivateKey)
if !ok {
return nil, errors.New("not an ECDSA private key")
}
return key, nil
default:
return nil, fmt.Errorf("unsupported key type %q", block.Type)
}
}
func writePEM(path, blockType string, der []byte, mode os.FileMode) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
if err := pem.Encode(file, &pem.Block{Type: blockType, Bytes: der}); err != nil {
_ = file.Close()
return err
}
return file.Close()
}
func loadLedger(dir string) (*ledger, error) {
path := filepath.Join(dir, "ledger.json")
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return &ledger{NextCRLNumber: 1}, nil
}
if err != nil {
return nil, err
}
var book ledger
if err := json.Unmarshal(data, &book); err != nil {
return nil, fmt.Errorf("parse %s: %w", path, err)
}
if book.NextCRLNumber < 1 {
book.NextCRLNumber = 1
}
return &book, nil
}
func saveLedger(dir string, book *ledger) error {
data, err := json.MarshalIndent(book, "", " ")
if err != nil {
return err
}
temp := filepath.Join(dir, ".ledger.json.tmp")
if err := os.WriteFile(temp, append(data, '\n'), 0o600); err != nil {
return err
}
return os.Rename(temp, filepath.Join(dir, "ledger.json"))
}
func randomSerial() (*big.Int, error) {
limit := new(big.Int).Lsh(big.NewInt(1), 128)
serial, err := rand.Int(rand.Reader, limit)
if err != nil {
return nil, err
}
if serial.Sign() == 0 {
return big.NewInt(1), nil
}
return serial, nil
}
func parseSANs(raw string) ([]string, []net.IP, error) {
var dns []string
var ips []net.IP
for _, value := range splitSANs(raw) {
if strings.HasPrefix(value, "ip:") {
ip := net.ParseIP(strings.TrimPrefix(value, "ip:"))
if ip == nil {
return nil, nil, fmt.Errorf("invalid IP SAN %q", value)
}
ips = append(ips, ip)
continue
}
if value == "" || strings.ContainsAny(value, " /\\") {
return nil, nil, fmt.Errorf("invalid DNS SAN %q", value)
}
dns = append(dns, value)
}
return dns, ips, nil
}
func splitSANs(raw string) []string {
var values []string
for _, part := range strings.Split(raw, ",") {
part = strings.TrimSpace(part)
if part != "" {
values = append(values, part)
}
}
return values
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
+31 -2
View File
@@ -14,6 +14,7 @@ import (
"time"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/tlsutil"
)
func main() {
@@ -23,8 +24,8 @@ func main() {
if region == "" {
region = "us-east-1"
}
accessKey := strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY"))
secretKey := strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_KEY"))
accessKey := envOrFile("S3_ADMIN_ACCESS_KEY")
secretKey := envOrFile("S3_ADMIN_SECRET_KEY")
if endpoint == "" || bucket == "" || accessKey == "" || secretKey == "" {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_ENDPOINT, S3_BUCKET, S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_KEY are required")
os.Exit(2)
@@ -38,6 +39,20 @@ func main() {
}
timeout = time.Duration(seconds) * time.Second
}
serverName := strings.TrimSpace(os.Getenv("S3_SERVER_NAME"))
if serverName == "" {
serverName = "s3-gw"
}
s3TLS, err := tlsutil.ClientConfig(
strings.TrimSpace(os.Getenv("S3_CA_FILE")),
strings.TrimSpace(os.Getenv("S3_CLIENT_CERT_FILE")),
strings.TrimSpace(os.Getenv("S3_CLIENT_KEY_FILE")),
serverName,
)
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: TLS configuration error:", err)
os.Exit(2)
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: endpoint,
Region: region,
@@ -45,6 +60,7 @@ func main() {
AccessKey: accessKey,
SecretKey: secretKey,
Timeout: timeout,
TLS: s3TLS,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: configuration error:", err)
@@ -69,3 +85,16 @@ func main() {
encoded, _ := json.Marshal(result)
fmt.Println(string(encoded))
}
// envOrFile resolves NAME_FILE before NAME so compose can mount the value as a
// read-only secret instead of putting it in the container environment.
func envOrFile(name string) string {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
return strings.TrimSpace(os.Getenv(name))
}
+17
View File
@@ -12,10 +12,12 @@ import (
"fmt"
"io"
"os"
"strings"
"time"
"mtusi.ru/messenger-lab7/internal/config"
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/tlsutil"
)
func main() {
@@ -36,6 +38,20 @@ func main() {
if *bucketOverride != "" {
bucket = *bucketOverride
}
serverName := strings.TrimSpace(os.Getenv("S3_SERVER_NAME"))
if serverName == "" {
serverName = "s3-gw"
}
s3TLS, err := tlsutil.ClientConfig(
strings.TrimSpace(os.Getenv("S3_CA_FILE")),
strings.TrimSpace(os.Getenv("S3_CLIENT_CERT_FILE")),
strings.TrimSpace(os.Getenv("S3_CLIENT_KEY_FILE")),
serverName,
)
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: TLS configuration error:", err)
os.Exit(2)
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
@@ -43,6 +59,7 @@ func main() {
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
TLS: s3TLS,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
+286
View File
@@ -0,0 +1,286 @@
// Command securityprobe executes one synthetic operation with explicitly
// supplied service credentials. It is an evidence tool, not part of the HTTP
// API: the track-1 and trust-matrix scripts run it inside a throwaway container
// to record which S3 prefixes, database statements and broker commands a given
// identity can actually perform. It never prints a credential.
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/redis/go-redis/v9"
"mtusi.ru/messenger-lab7/internal/tlsutil"
)
type result struct {
Kind string `json:"kind"`
Op string `json:"op"`
Target string `json:"target,omitempty"`
Allowed bool `json:"allowed"`
HTTPStatus int `json:"http_status,omitempty"`
Detail string `json:"detail,omitempty"`
Error string `json:"error,omitempty"`
}
func main() {
kind := flag.String("kind", "", "s3, db or broker")
op := flag.String("op", "", "operation name")
key := flag.String("key", "", "S3 object key / broker key")
bucket := flag.String("bucket", "", "S3 bucket override")
flag.Parse()
if *kind == "" || *op == "" {
fail("-kind and -op are required")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var item result
var err error
switch *kind {
case "s3":
item, err = probeS3(ctx, *op, *key, *bucket)
case "db":
item, err = probeDB(ctx, *op)
case "broker":
item, err = probeBroker(ctx, *op, *key)
default:
fail("-kind must be s3, db or broker")
}
if err != nil {
fail(err.Error())
}
encoded, _ := json.Marshal(item)
fmt.Println(string(encoded))
}
func probeS3(ctx context.Context, op, key, bucketOverride string) (result, error) {
endpoint := strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
bucket := strings.TrimSpace(os.Getenv("S3_BUCKET"))
if bucketOverride != "" {
bucket = bucketOverride
}
access := strings.TrimSpace(os.Getenv("S3_ACCESS_KEY"))
secret := strings.TrimSpace(os.Getenv("S3_SECRET_KEY"))
if endpoint == "" || bucket == "" || access == "" || secret == "" {
return result{}, fmt.Errorf("S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY and S3_SECRET_KEY are required")
}
serverName := valueOr(os.Getenv("S3_SERVER_NAME"), "s3-gw")
tlsConfig, err := tlsutil.ClientConfig(os.Getenv("S3_CA_FILE"), os.Getenv("S3_CLIENT_CERT_FILE"), os.Getenv("S3_CLIENT_KEY_FILE"), serverName)
if err != nil {
return result{}, err
}
endpoint = strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")
client, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(access, secret, ""),
Secure: true,
Region: valueOr(os.Getenv("S3_REGION"), "us-east-1"),
BucketLookup: minio.BucketLookupPath,
Transport: &httpTransport{TLS: tlsConfig},
})
if err != nil {
return result{}, err
}
item := result{Kind: "s3", Op: op, Target: bucket + "/" + key, Allowed: true}
switch op {
case "put":
_, err = client.PutObject(ctx, bucket, key, bytes.NewReader([]byte("lab7 security probe")), 21, minio.PutObjectOptions{ContentType: "text/plain"})
case "get":
var object *minio.Object
object, err = client.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
if err == nil {
_, _ = io.CopyN(io.Discard, object, 64)
_ = object.Close()
}
case "stat":
_, err = client.StatObject(ctx, bucket, key, minio.StatObjectOptions{})
case "delete":
err = client.RemoveObject(ctx, bucket, key, minio.RemoveObjectOptions{})
case "list":
objectCh := client.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: key, MaxKeys: 5, Recursive: true})
for object := range objectCh {
if object.Err != nil {
err = object.Err
break
}
}
case "listbuckets":
var buckets []minio.BucketInfo
buckets, err = client.ListBuckets(ctx)
item.Detail = fmt.Sprintf("%d bucket(s)", len(buckets))
default:
return result{}, fmt.Errorf("unknown S3 op %q", op)
}
if err != nil {
item.Allowed = false
item.Error = err.Error()
if response := minio.ToErrorResponse(err); response.StatusCode != 0 {
item.HTTPStatus = response.StatusCode
item.Error = response.Code
}
}
return item, nil
}
// httpTransport is a tiny adapter that keeps the probe independent of
// objectstore's policy wrapper.
type httpTransport struct{ TLS *tls.Config }
func (t *httpTransport) RoundTrip(request *http.Request) (*http.Response, error) {
transport := &http.Transport{TLSClientConfig: t.TLS, Proxy: nil}
return transport.RoundTrip(request)
}
func probeDB(ctx context.Context, op string) (result, error) {
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
if path := strings.TrimSpace(os.Getenv("DATABASE_URL_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return result{}, fmt.Errorf("read DATABASE_URL_FILE: %w", err)
}
dsn = strings.TrimSpace(string(data))
}
}
if dsn == "" {
return result{}, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required")
}
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
return result{}, fmt.Errorf("database connection: %w", err)
}
defer func() { _ = conn.Close(context.Background()) }()
tx, err := conn.Begin(ctx)
if err != nil {
return result{}, err
}
defer func() { _ = tx.Rollback(context.Background()) }()
item := result{Kind: "db", Op: op, Allowed: true}
var rows int
switch op {
case "select-users":
err = tx.QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&rows)
item.Detail = fmt.Sprintf("%d user row(s)", rows)
case "select-jobs":
err = tx.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs`).Scan(&rows)
item.Detail = fmt.Sprintf("%d job row(s)", rows)
case "select-schema":
err = tx.QueryRow(ctx, `SELECT count(*) FROM schema_migrations`).Scan(&rows)
item.Detail = fmt.Sprintf("%d migration row(s)", rows)
case "delete-messages":
tag, execErr := tx.Exec(ctx, `DELETE FROM messages WHERE false`)
err = execErr
item.Detail = fmt.Sprintf("%d row(s) affected", tag.RowsAffected())
case "update-users":
tag, execErr := tx.Exec(ctx, `UPDATE users SET display_name = display_name WHERE false`)
err = execErr
item.Detail = fmt.Sprintf("%d row(s) affected", tag.RowsAffected())
case "ddl":
_, err = tx.Exec(ctx, `CREATE TEMPORARY TABLE lab7_probe_ddl (id integer) ON COMMIT DROP`)
item.Detail = "temporary DDL accepted"
default:
return result{}, fmt.Errorf("unknown DB op %q", op)
}
if err != nil {
item.Allowed = false
item.Error = err.Error()
}
return item, nil
}
func probeBroker(ctx context.Context, op, key string) (result, error) {
rawURL := strings.TrimSpace(os.Getenv("BROKER_URL"))
if rawURL == "" {
return result{}, fmt.Errorf("BROKER_URL is required")
}
if key == "" {
key = "lab7:probe:security"
}
options, err := redis.ParseURL(rawURL)
if err != nil {
return result{}, err
}
serverName := valueOr(os.Getenv("BROKER_SERVER_NAME"), "broker-gw")
tlsConfig, err := tlsutil.ClientConfig(os.Getenv("BROKER_CA_FILE"), os.Getenv("BROKER_CLIENT_CERT_FILE"), os.Getenv("BROKER_CLIENT_KEY_FILE"), serverName)
if err != nil {
return result{}, err
}
options.TLSConfig = tlsConfig
options.MaxRetries = 0
options.DialTimeout = 3 * time.Second
options.ReadTimeout = 3 * time.Second
options.WriteTimeout = 3 * time.Second
client := redis.NewClient(options)
defer func() { _ = client.Close() }()
item := result{Kind: "broker", Op: op, Target: key, Allowed: true}
switch op {
case "ping":
err = client.Ping(ctx).Err()
case "xadd":
_, err = client.XAdd(ctx, &redis.XAddArgs{Stream: key, Values: map[string]any{"probe": "1"}}).Result()
case "xreadgroup":
_, err = client.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "lab7-probe", Consumer: "probe", Streams: []string{key, ">"}, Count: 1, Block: -1,
}).Result()
if err != nil && strings.Contains(err.Error(), "NOGROUP") {
item.Detail = "command permitted (consumer group does not exist)"
err = nil
}
case "xlen":
var length int64
length, err = client.XLen(ctx, key).Result()
item.Detail = fmt.Sprintf("%d entries", length)
case "set":
err = client.Set(ctx, key, "probe", time.Minute).Err()
case "get":
_, err = client.Get(ctx, key).Result()
if err == redis.Nil {
item.Detail = "key absent"
err = nil
}
case "del":
var deleted int64
deleted, err = client.Del(ctx, key).Result()
item.Detail = fmt.Sprintf("%d key(s) deleted", deleted)
case "config":
_, err = client.ConfigGet(ctx, "maxmemory").Result()
case "flushall":
err = client.FlushAll(ctx).Err()
case "acl":
_, err = client.Do(ctx, "ACL", "WHOAMI").Result()
default:
return result{}, fmt.Errorf("unknown broker op %q", op)
}
if err != nil {
item.Allowed = false
item.Error = err.Error()
}
return item, nil
}
func valueOr(value, fallback string) string {
if strings.TrimSpace(value) != "" {
return value
}
return fallback
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "securityprobe:", message)
os.Exit(1)
}
+65 -34
View File
@@ -5,12 +5,14 @@ package main
import (
"context"
"crypto/tls"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
@@ -20,6 +22,7 @@ import (
"mtusi.ru/messenger-lab7/internal/objectstore"
"mtusi.ru/messenger-lab7/internal/store"
"mtusi.ru/messenger-lab7/internal/telemetry"
"mtusi.ru/messenger-lab7/internal/tlsutil"
"mtusi.ru/messenger-lab7/internal/uuid"
"mtusi.ru/messenger-lab7/internal/worker"
)
@@ -40,11 +43,12 @@ func main() {
os.Exit(2)
}
if *healthcheck {
os.Exit(runHealthcheck(cfg))
os.Exit(runHeartbeatHealthcheck())
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
go heartbeat(ctx)
instanceID := consumerIdentity()
telemetryProvider, err := telemetry.Setup(ctx, telemetry.Options{
@@ -58,6 +62,10 @@ func main() {
os.Exit(2)
}
logger := telemetryProvider.Logger().With("revision", revision)
if cfg.OpenBao != nil {
go cfg.OpenBao.RunRenewal(ctx, logger)
logger.Info("OpenBao worker identity acquired", "token_ttl_seconds", int(cfg.OpenBaoTokenTTL.Seconds()))
}
shutdownTelemetry := func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
@@ -87,6 +95,11 @@ func main() {
os.Exit(1)
}
s3TLS, err := clientTLS("S3 gateway", cfg.S3CAFile, cfg.S3ClientCertFile, cfg.S3ClientKeyFile, defaultValue(cfg.S3ServerName, "s3-gw"))
if err != nil {
logger.Error("S3 TLS configuration failed", "error", err)
os.Exit(2)
}
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
@@ -94,6 +107,7 @@ func main() {
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
TLS: s3TLS,
})
if err != nil {
logger.Error("object store configuration failed", "error", err)
@@ -104,6 +118,11 @@ func main() {
os.Exit(1)
}
brokerTLS, err := clientTLS("broker gateway", cfg.BrokerCAFile, cfg.BrokerClientCert, cfg.BrokerClientKey, defaultValue(cfg.BrokerServerName, "broker-gw"))
if err != nil {
logger.Error("broker TLS configuration failed", "error", err)
os.Exit(2)
}
var transport *broker.Broker
if err := waitFor(ctx, cfg.StartupTimeout, "broker", func(checkCtx context.Context) error {
opened, openErr := broker.Open(checkCtx, broker.Config{
@@ -111,6 +130,7 @@ func main() {
Stream: cfg.BrokerStream,
Group: cfg.BrokerGroup,
Timeout: 3 * time.Second,
TLS: brokerTLS,
})
if openErr != nil {
return openErr
@@ -214,47 +234,58 @@ func consumerIdentity() string {
return "worker-" + hostname + "-" + uuid.NewRandom(3)
}
func runHealthcheck(cfg config.Config) int {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
failures := 0
report := func(name string, err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "worker healthcheck:", name, "unavailable:", err)
failures++
// heartbeat updates a tmpfs file every two seconds. The container healthcheck
// reads its mtime, so a sealed OpenBao or a temporary dependency outage does not
// make Docker kill a worker that is still running: pipeline readiness is visible
// through queue progress and metrics instead.
func heartbeat(ctx context.Context) {
path := heartbeatPath()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
_ = os.WriteFile(path, []byte(time.Now().UTC().Format(time.RFC3339Nano)), 0o600)
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{MaxConns: 1, MinConns: 0, ConnectTimeout: 2 * time.Second, StatementTimeout: 3 * time.Second, QueryTimeout: 2 * time.Second})
if err != nil {
report("postgres", err)
} else {
defer repository.Close()
report("postgres", repository.Ping(ctx))
func heartbeatPath() string {
if value := strings.TrimSpace(os.Getenv("WORKER_HEARTBEAT_FILE")); value != "" {
return value
}
return filepath.Join(os.TempDir(), "worker.heartbeat")
}
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint, Region: cfg.S3Region, Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey, SecretKey: cfg.S3SecretKey, Timeout: 3 * time.Second,
})
func runHeartbeatHealthcheck() int {
info, err := os.Stat(heartbeatPath())
if err != nil {
report("s3", err)
} else {
report("s3", objects.Health(ctx))
fmt.Fprintln(os.Stderr, "worker healthcheck: heartbeat is missing")
return 1
}
transport, err := broker.Open(ctx, broker.Config{
URL: cfg.BrokerURL, Stream: cfg.BrokerStream, Group: cfg.BrokerGroup, Timeout: 2 * time.Second,
})
if err != nil {
report("broker", err)
} else {
defer func() { _ = transport.Close() }()
report("broker", transport.Ping(ctx))
}
if failures > 0 {
if time.Since(info.ModTime()) > 10*time.Second {
fmt.Fprintln(os.Stderr, "worker healthcheck: heartbeat is stale")
return 1
}
return 0
}
func defaultValue(value, fallback string) string {
if strings.TrimSpace(value) != "" {
return value
}
return fallback
}
func clientTLS(label, caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
if caFile == "" {
return nil, fmt.Errorf("%s CA file is required", label)
}
config, err := tlsutil.ClientConfig(caFile, certFile, keyFile, serverName)
if err != nil {
return nil, fmt.Errorf("%s: %w", label, err)
}
return config, nil
}
+1184
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
# mTLS broker gateway. Valkey Streams itself stays on the private dependency
# network; this proxy terminates TLS, verifies the client chain against the
# internal CA, checks the CRL and allowlists the two service identities.
# Authorization inside Valkey is a second, independent layer: the api ACL user
# may only produce and inspect, the worker user may only consume/ack/recover.
global
log stdout format raw local0
maxconn 2048
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode tcp
log global
option tcplog
option dontlognull
timeout connect 3s
timeout client 60s
timeout server 60s
frontend broker_mtls
bind :6379 ssl crt /run/secrets/broker_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
mode tcp
tcp-request inspect-delay 5s
tcp-request content accept if { ssl_c_s_dn(CN) -m str lab7-api } or { ssl_c_s_dn(CN) -m str lab7-worker }
tcp-request content reject
default_backend broker_private
backend broker_private
mode tcp
server broker broker-store:6379 check resolvers docker init-addr none
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
@@ -0,0 +1,77 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://telemetry-gw:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
httpMethod: POST
tlsAuthWithCACert: true
tlsAuth: true
serverName: telemetry-gw
secureJsonData:
tlsCACert: |
__CA_PEM__
tlsClientCert: |
__CLIENT_CERT_PEM__
tlsClientKey: |
__CLIENT_KEY_PEM__
- name: Loki
uid: loki
type: loki
access: proxy
url: https://telemetry-gw:3100
editable: false
jsonData:
tlsAuthWithCACert: true
tlsAuth: true
serverName: telemetry-gw
derivedFields:
- name: trace_id
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
secureJsonData:
tlsCACert: |
__CA_PEM__
tlsClientCert: |
__CLIENT_CERT_PEM__
tlsClientKey: |
__CLIENT_KEY_PEM__
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://telemetry-gw:3200
editable: false
jsonData:
tlsAuthWithCACert: true
tlsAuth: true
serverName: telemetry-gw
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
filterBySpanID: false
spanStartTimeShift: '-2m'
spanEndTimeShift: '2m'
tags: []
nodeGraph:
enabled: true
search:
hide: false
lokiSearch:
datasourceUid: loki
secureJsonData:
tlsCACert: |
__CA_PEM__
tlsClientCert: |
__CLIENT_CERT_PEM__
tlsClientKey: |
__CLIENT_KEY_PEM__
-7
View File
@@ -1,7 +0,0 @@
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
-64
View File
@@ -1,64 +0,0 @@
# Lab3 public entrypoint. HAProxy discovers API replicas through Docker's
# embedded DNS and actively probes /health/ready. There is no sticky session:
# every request is balanced independently, and a backend that fails two
# consecutive probes is removed within roughly two probe intervals.
#
# The stats endpoint is bound to loopback inside the container only. It is not
# published and is used by the experiment scripts through `docker exec`.
global
log stdout format raw local0
maxconn 8192
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
# Per-request access logging is intentionally disabled: at thousands of
# requests per second it moves the LB bottleneck into stdout and hides the
# component under study. Errors are still logged.
option dontlog-normal
option redispatch
retries 2
timeout connect 1s
timeout client 15s
timeout server 15s
timeout http-request 5s
timeout http-keep-alive 5s
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
frontend public
bind :8080
mode http
default_backend api
backend api
mode http
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
# One template slot per A record returned for the compose service name.
# Docker DNS adds/removes records on scale/stop; `hold valid 1s` keeps the
# backend list current instead of caching the first resolution.
server-template api 1-10 api:8080 check resolvers docker init-addr none
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 1s
stats show-legends
-7
View File
@@ -1,7 +0,0 @@
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
-22
View File
@@ -1,22 +0,0 @@
# Prometheus is the metrics store. The only application metrics source is the
# collector's Prometheus exporter; Prometheus never scrapes the API or worker
# directly. Collector self-telemetry is scraped separately so queue drops and
# refused spans are visible when a backend is unhealthy.
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: otel-collector-application
static_configs:
- targets: ["otel-collector:9464"]
- job_name: otel-collector-internal
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
static_configs:
- targets: ["127.0.0.1:9090"]
-22
View File
@@ -1,22 +0,0 @@
{
"identities": [
{
"name": "lab6-admin-bootstrap",
"credentials": [
{"accessKey": "mL6CzXp0LWD2WNoVUhRNB6uKKb276Ug9", "secretKey": "e8WQnzjk8eCujM5v4Ej6sVhOMGNdmC4g"}
],
"actions": ["Admin"]
},
{
"name": "lab6-api-bucket-scoped",
"credentials": [
{"accessKey": "SV0177Zkp0AIsWWq5faJ453mr3PKp5V3", "secretKey": "2vcFWY8iVCgETNEKWU7RCjXWlyDieshM"}
],
"actions": [
"Read:messenger-attachments",
"Write:messenger-attachments",
"List:messenger-attachments"
]
}
]
}
+63
View File
@@ -0,0 +1,63 @@
# Lab7 public ingress. The only published business port.
#
# client --TLS(edge CA, hostname localhost)--> HAProxy
# HAProxy --mTLS(service CA, client CN lab7-lb)--> each API replica
#
# The backend connection verifies the API server certificate (SAN api) and
# presents the dedicated LB client identity. API replicas publish no host port,
# so this is the only route to the business API.
global
log stdout format raw local0
maxconn 8192
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
option dontlog-normal
option redispatch
retries 2
timeout connect 2s
timeout client 20s
timeout server 20s
timeout http-request 5s
timeout http-keep-alive 5s
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
frontend public_https
bind :8447 ssl crt /run/secrets/lb_server_bundle alpn h2,http/1.1
mode http
option forwardfor
http-request set-header X-Forwarded-Proto https
http-response set-header Strict-Transport-Security "max-age=31536000"
default_backend api_mtls
backend api_mtls
mode http
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
# The LB is a TLS client with its own identity. verifyhost rejects a
# backend certificate that is signed by the CA but issued for another
# service; the API independently allowlists CN lab7-lb.
server-template api 1-10 api:8443 ssl verify required ca-file /run/secrets/service_ca crt /run/secrets/lb_client_bundle verifyhost api check resolvers docker init-addr none
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 1s
+132
View File
@@ -0,0 +1,132 @@
#!/bin/sh
# Operator-authorized OpenBao bootstrap for the lab7 stand. Runs inside a
# one-shot OpenBao container, never inside OpenBao itself and never inside the
# application. Responsibilities:
# * initialize OpenBao once (file storage) when the persistent volume is empty;
# * unseal it after a restart using the local operator share;
# * enable KV v2, write the two service policies and AppRole roles;
# * write the API/worker KV documents from a root-only local file;
# * issue AppRole role-id/secret-id files for the API and worker.
#
# The root token and unseal key are read from /operator/init.json (mode 0600 on
# an ignored host directory). They are never printed, baked into an image,
# mounted into the application containers or written to telemetry.
set -eu
MODE="${1:-bootstrap}"
INIT_FILE=/operator/init.json
ROLE_DIR=/approle
compact() {
tr -d '[:space:]'
}
json_field() {
field=$1
compact | sed -n "s/.*\"${field}\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p"
}
unseal_key() {
compact < "$INIT_FILE" | sed -n 's/.*"unseal_keys_b64"[[:space:]]*:[[:space:]]*\["\([^"]*\)".*/\1/p'
}
root_token() {
json_field root_token < "$INIT_FILE"
}
wait_server() {
attempt=0
while [ "$attempt" -lt 90 ]; do
attempt=$((attempt + 1))
status=$(bao status -format=json 2>/dev/null || true)
if [ -n "$status" ]; then
printf '%s' "$status" | compact
return 0
fi
sleep 1
done
echo "openbao did not answer on https://127.0.0.1:8200" >&2
return 1
}
echo "waiting for OpenBao API"
STATUS=$(wait_server)
if [ "$MODE" != "unseal-only" ]; then
case "$STATUS" in
*'"initialized":true'*) ;;
*)
echo "initializing OpenBao with one operator share (threshold 1)"
temp="$INIT_FILE.tmp"
bao operator init -key-shares=1 -key-threshold=1 -format=json > "$temp"
chmod 600 "$temp"
mv "$temp" "$INIT_FILE"
;;
esac
fi
if [ ! -f "$INIT_FILE" ]; then
echo "OpenBao is already initialized but $INIT_FILE is missing; restore the operator share" >&2
exit 1
fi
KEY=$(unseal_key)
ROOT=$(root_token)
if [ -z "$KEY" ] || [ -z "$ROOT" ]; then
echo "operator init file is incomplete" >&2
exit 1
fi
STATUS=$(bao status -format=json 2>/dev/null | compact || true)
case "$STATUS" in
*'"sealed":true'*)
echo "unsealing OpenBao"
bao operator unseal "$KEY" >/dev/null
;;
esac
if [ "$MODE" = "unseal-only" ]; then
echo "OpenBao unsealed"
exit 0
fi
export BAO_TOKEN="$ROOT"
echo "configuring KV v2, policies, AppRole and service secrets"
if ! bao secrets list -format=json 2>/dev/null | grep -q '"secret/"'; then
bao secrets enable -path=secret kv-v2 >/dev/null
fi
bao policy write api /policies/api.hcl >/dev/null
bao policy write worker /policies/worker.hcl >/dev/null
if ! bao auth list -format=json 2>/dev/null | grep -q '"approle/"'; then
bao auth enable approle >/dev/null
fi
bao write auth/approle/role/api \
token_policies=api token_ttl=20m token_max_ttl=1h \
token_no_default_policy=true secret_id_ttl=24h secret_id_num_uses=0 \
bind_secret_id=true >/dev/null
bao write auth/approle/role/worker \
token_policies=worker token_ttl=20m token_max_ttl=1h \
token_no_default_policy=true secret_id_ttl=24h secret_id_num_uses=0 \
bind_secret_id=true >/dev/null
bao kv put secret/lab7/api @/kv/api.json >/dev/null
bao kv put secret/lab7/worker @/kv/worker.json >/dev/null
umask 022
mkdir -p "$ROLE_DIR"
for role in api worker; do
if [ ! -s "$ROLE_DIR/$role.role_id" ] || [ ! -s "$ROLE_DIR/$role.secret_id" ]; then
bao read -field=role_id "auth/approle/role/$role/role-id" > "$ROLE_DIR/$role.role_id"
bao write -format=json -f "auth/approle/role/$role/secret-id" > "/tmp/$role.secret.json"
json_field secret_id < "/tmp/$role.secret.json" > "$ROLE_DIR/$role.secret_id"
json_field secret_id_accessor < "/tmp/$role.secret.json" > "$ROLE_DIR/$role.secret_id_accessor"
rm -f "/tmp/$role.secret.json"
chmod 644 "$ROLE_DIR/$role.role_id" "$ROLE_DIR/$role.secret_id" "$ROLE_DIR/$role.secret_id_accessor"
fi
done
echo "OpenBao bootstrap complete: sealed=false, policies api/worker, AppRole credentials present"
+25
View File
@@ -0,0 +1,25 @@
# OpenBao server configuration for the isolated lab7 teaching stand.
#
# Storage is a persistent file backend on a named volume; dev mode is never
# used. The server starts sealed after a process/container restart and is
# unsealed by the operator-authorized one-shot bootstrap, which is the only
# container that can read the local unseal share. The unseal key and root token
# are never mounted into OpenBao itself, the API or the worker.
ui = true
disable_mlock = true
api_addr = "https://openbao:8200"
default_lease_ttl = "1h"
max_lease_ttl = "4h"
storage "file" {
path = "/openbao/data"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/secrets/openbao_server_cert"
tls_key_file = "/run/secrets/openbao_server_key"
tls_min_version = "tls12"
}
log_level = "info"
+18
View File
@@ -0,0 +1,18 @@
# API service policy: read exactly one KV v2 document and renew its own token.
# The token has no default policy, cannot write secrets, cannot read the worker
# path, cannot manage policies and cannot use sys/ endpoints.
path "secret/data/lab7/api" {
capabilities = ["read"]
}
path "secret/metadata/lab7/api" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
+18
View File
@@ -0,0 +1,18 @@
# Worker service policy: read only the worker KV document and renew its token.
# It deliberately cannot read the API document (DB/API credentials), write any
# secret, manage OpenBao or use root-only endpoints.
path "secret/data/lab7/worker" {
capabilities = ["read"]
}
path "secret/metadata/lab7/worker" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
+46
View File
@@ -0,0 +1,46 @@
# mTLS OTLP gateway. Only the API and worker identities may ingest telemetry,
# and only on the three OTLP/HTTP paths. Prometheus/Loki/Tempo/Grafana are not
# reachable from application containers at all.
global
log stdout format raw local0
maxconn 2048
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
option dontlog-normal
timeout connect 3s
timeout client 30s
timeout server 30s
timeout http-request 10s
frontend otlp_mtls
bind :4318 ssl crt /run/secrets/otel_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-api } || { ssl_c_s_dn(CN) -m str lab7-worker }
http-request deny status 403 unless { method POST } { path /v1/traces } || { method POST } { path /v1/metrics } || { method POST } { path /v1/logs }
default_backend collector_private
backend collector_private
mode http
server collector otel-collector-store:4318 check resolvers docker init-addr none
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
@@ -1,8 +1,9 @@
# OpenTelemetry Collector for the lab6 stand.
#
# The collector is the only OTLP receiver. It never stores telemetry itself:
# metrics go to Prometheus (scraped from the Prometheus exporter), logs go to
# Loki's native OTLP endpoint and traces go to Tempo over OTLP/gRPC.
# The collector is the only OTLP receiver (behind the mTLS otel-gw). It never
# stores telemetry itself: metrics go to Prometheus (scraped through the
# telemetry-gw), logs go to Loki's OTLP HTTP endpoint and traces go to Tempo's
# OTLP HTTP endpoint, both over mTLS with the dedicated collector identity.
#
# Failure posture: memory_limiter caps RAM, batch reduces RPCs, and every
# exporter has a bounded sending queue with retry/backoff. When a backend is
@@ -45,10 +46,14 @@ exporters:
endpoint: 0.0.0.0:9464
resource_to_telemetry_conversion:
enabled: true
otlp/tempo:
endpoint: tempo:4317
otlphttp/tempo:
endpoint: https://telemetry-gw:4318
tls:
insecure: true
insecure: false
ca_file: /run/secrets/service_ca
cert_file: /run/secrets/collector_client_cert
key_file: /run/secrets/collector_client_key
server_name_override: telemetry-gw
timeout: 5s
retry_on_failure:
enabled: true
@@ -60,7 +65,13 @@ exporters:
num_consumers: 4
queue_size: 2048
otlphttp/loki:
endpoint: http://loki:3100/otlp
endpoint: https://telemetry-gw:3100/otlp
tls:
insecure: false
ca_file: /run/secrets/service_ca
cert_file: /run/secrets/collector_client_cert
key_file: /run/secrets/collector_client_key
server_name_override: telemetry-gw
timeout: 5s
retry_on_failure:
enabled: true
@@ -88,7 +99,7 @@ service:
traces:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
exporters: [otlp/tempo]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, resource/lab, batch]
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Copy the read-only compose secrets to a private directory with the ownership
# and modes PostgreSQL requires for a server key, then hand over to the official
# entrypoint. The key is never exposed to the API/worker containers.
set -eu
install -d -o postgres -g postgres -m 700 /var/lib/postgresql/certs
install -o postgres -g postgres -m 600 /run/secrets/postgres_server_key /var/lib/postgresql/certs/server.key
install -o postgres -g postgres -m 644 /run/secrets/postgres_server_cert /var/lib/postgresql/certs/server.crt
install -o postgres -g postgres -m 644 /run/secrets/service_ca /var/lib/postgresql/certs/ca.crt
exec docker-entrypoint.sh "$@"
+5
View File
@@ -0,0 +1,5 @@
# Lab7: TCP access is TLS-only. The local unix socket is used only by the
# container's own init/health commands.
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostnossl all all 0.0.0.0/0 reject
+34
View File
@@ -0,0 +1,34 @@
# Prometheus metrics store. Application metrics come from the Collector's
# Prometheus exporter; Prometheus never scrapes the API or worker directly.
# Scrapes traverse the telemetry-gw with the dedicated lab7-prometheus client
# identity and full server verification; there is no plaintext scrape path.
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: otel-collector-application
scheme: https
tls_config:
ca_file: /run/secrets/service_ca
cert_file: /run/secrets/prometheus_client_cert
key_file: /run/secrets/prometheus_client_key
server_name: telemetry-gw
static_configs:
- targets: ["telemetry-gw:9464"]
- job_name: otel-collector-internal
scheme: https
tls_config:
ca_file: /run/secrets/service_ca
cert_file: /run/secrets/prometheus_client_cert
key_file: /run/secrets/prometheus_client_key
server_name: telemetry-gw
static_configs:
- targets: ["telemetry-gw:8888"]
- job_name: prometheus
static_configs:
- targets: ["127.0.0.1:9090"]
+71
View File
@@ -0,0 +1,71 @@
# mTLS S3 gateway. SeaweedFS keeps a private bucket and per-service access keys,
# but its S3 implementation has no per-prefix IAM policy. This verified TLS
# proxy therefore enforces both the service identity (client certificate CN from
# the internal CA, CRL checked) and the allowed bucket prefixes for each
# identity. The last hop to SeaweedFS is plaintext on a dedicated private
# network that no application container shares.
#
# api -> PUT staging/*, GET/HEAD/DELETE attachments/*, DELETE staging/*
# worker -> GET/HEAD/DELETE staging/*, PUT attachments/*, HEAD attachments/*,
# list only with prefix=staging/ (janitor)
# bootstrap -> full access, used only by the one-shot bucket initializer
global
log stdout format raw local0
maxconn 2048
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
option dontlog-normal
timeout connect 3s
timeout client 30s
timeout server 30s
timeout http-request 10s
timeout http-keep-alive 5s
frontend s3_mtls
bind :9000 ssl crt /run/secrets/s3_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
# A CA-signed certificate with any other CN is rejected here, before a
# request reaches the bucket.
http-request deny unless { ssl_c_s_dn(CN) -m str lab7-bootstrap } || { ssl_c_s_dn(CN) -m str lab7-api } || { ssl_c_s_dn(CN) -m str lab7-worker }
# Read-only liveness probe object, used by the worker's startup check.
http-request allow if { method HEAD } { path /messenger-attachments/_health/probe }
# API: write staging, read final, delete staging. Nothing else.
http-request deny if { ssl_c_s_dn(CN) -m str lab7-api } { method PUT } !{ path_beg /messenger-attachments/staging/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-api } { method DELETE } !{ path_beg /messenger-attachments/staging/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-api } { method GET } !{ path_beg /messenger-attachments/attachments/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-api } { method HEAD } !{ path_beg /messenger-attachments/attachments/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-api } !{ method GET } !{ method HEAD } !{ method PUT } !{ method DELETE }
# Worker: read/delete staging, write/stat final, list only staging.
http-request deny if { ssl_c_s_dn(CN) -m str lab7-worker } { method PUT } !{ path_beg /messenger-attachments/attachments/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-worker } { method GET } !{ path_beg /messenger-attachments/staging/ } !{ path /messenger-attachments }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-worker } { method HEAD } !{ path_beg /messenger-attachments/staging/ } !{ path_beg /messenger-attachments/attachments/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-worker } { method DELETE } !{ path_beg /messenger-attachments/staging/ }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-worker } { method GET } { path_beg /messenger-attachments } !{ path_beg /messenger-attachments/staging/ } !{ url_param(prefix) -m beg staging }
http-request deny if { ssl_c_s_dn(CN) -m str lab7-worker } !{ method GET } !{ method HEAD } !{ method PUT } !{ method DELETE }
default_backend s3_private
backend s3_private
mode http
server s3 s3-store:8333 check resolvers docker init-addr none
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
+45
View File
@@ -0,0 +1,45 @@
# mTLS session-store gateway. The API is the only client; the gateway verifies
# the internal CA and the CN lab7-api identity and forwards over the private
# dependency network to a password/ACL-protected Valkey instance.
global
log stdout format raw local0
maxconn 2048
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode tcp
log global
option tcplog
option dontlognull
timeout connect 3s
timeout client 60s
timeout server 60s
frontend session_mtls
bind :6379 ssl crt /run/secrets/session_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
mode tcp
tcp-request inspect-delay 5s
tcp-request content accept if { ssl_c_s_dn(CN) -m str lab7-api }
tcp-request content reject
default_backend session_private
backend session_private
mode tcp
server valkey valkey-store:6379 check resolvers docker init-addr none
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
+107
View File
@@ -0,0 +1,107 @@
# mTLS telemetry-backend gateway. The storage services themselves remain on a
# private network; this proxy performs the TLS server verification point and
# identity allowlist for each channel:
#
# collector -> Tempo :4318 (OTLP/HTTP traces only)
# collector -> Loki :3100 (/otlp/v1/logs only)
# grafana -> Loki :3100 (queries)
# grafana -> Tempo :3200 (queries)
# grafana -> Prom :9090 (queries)
# prometheus-> Collector :9464/:8888 (scrape)
#
# Plaintext exists only from this proxy to a backend on the dependency network;
# no application container is attached to that network.
global
log stdout format raw local0
maxconn 4028
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
option dontlog-normal
timeout connect 3s
timeout client 30s
timeout server 60s
timeout http-request 10s
frontend tempo_otlp
bind :4318 ssl crt /run/secrets/telemetry_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-collector }
http-request deny status 403 unless { method POST } { path /v1/traces }
default_backend tempo_otlp_be
frontend loki_api
bind :3100 ssl crt /run/secrets/telemetry_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-collector } || { ssl_c_s_dn(CN) -m str lab7-grafana }
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-grafana } || { ssl_c_s_dn(CN) -m str lab7-collector } { method POST } { path_beg /otlp/ }
default_backend loki_private
frontend prometheus_api
bind :9090 ssl crt /run/secrets/telemetry_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-grafana }
default_backend prometheus_private
frontend tempo_api
bind :3200 ssl crt /run/secrets/telemetry_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-grafana }
default_backend tempo_private
frontend collector_app_metrics
bind :9464 ssl crt /run/secrets/telemetry_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-prometheus }
default_backend collector_app_metrics_be
frontend collector_internal_metrics
bind :8888 ssl crt /run/secrets/telemetry_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl alpn http/1.1
mode http
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-prometheus }
default_backend collector_internal_metrics_be
backend tempo_otlp_be
mode http
server tempo tempo-store:4318 check resolvers docker init-addr none
backend loki_private
mode http
server loki loki-store:3100 check resolvers docker init-addr none
backend prometheus_private
mode http
server prometheus prometheus-store:9090 check resolvers docker init-addr none
backend tempo_private
mode http
server tempo tempo-store:3200 check resolvers docker init-addr none
backend collector_app_metrics_be
mode http
server collector otel-collector-store:9464 check resolvers docker init-addr none
backend collector_internal_metrics_be
mode http
server collector otel-collector-store:8888 check resolvers docker init-addr none
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
+25 -2
View File
@@ -19,7 +19,7 @@ import (
"mtusi.ru/messenger-lab7/internal/telemetry"
)
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
const maxBodyBytes = 1 << 20 // default; overridden by MAX_BODY_BYTES
type healthResponse struct {
Status string `json:"status"`
@@ -60,6 +60,10 @@ type App struct {
createdMessages atomic.Uint64
replayedMessages atomic.Uint64
conflictMessages atomic.Uint64
loginRateLimit int
loginRatePerIP int
loginRateWindow time.Duration
}
// Options carries the upload limits and concurrency bound. Values are
@@ -74,6 +78,10 @@ type Options struct {
JobMaxAttempts int
Metrics *telemetry.Instruments
Tracer trace.Tracer
MaxBodyBytes int64
RateLimit int
RateLimitPerIP int
RateLimitWindow time.Duration
}
// New creates the HTTP application. The dummy Argon2id hash is generated once
@@ -101,6 +109,18 @@ func New(repository *store.Store, sessions *session.Store, objects *objectstore.
if options.JobMaxAttempts <= 0 {
options.JobMaxAttempts = 5
}
if options.MaxBodyBytes <= 0 {
options.MaxBodyBytes = maxBodyBytes
}
if options.RateLimit <= 0 {
options.RateLimit = 5
}
if options.RateLimitPerIP <= 0 {
options.RateLimitPerIP = 20
}
if options.RateLimitWindow <= 0 {
options.RateLimitWindow = time.Minute
}
if options.Tracer == nil {
options.Tracer = trace.NewNoopTracerProvider().Tracer("messenger-api")
}
@@ -112,7 +132,10 @@ func New(repository *store.Store, sessions *session.Store, objects *objectstore.
sessions: sessions,
objects: objects,
log: logger,
maxBody: maxBodyBytes,
maxBody: options.MaxBodyBytes,
loginRateLimit: options.RateLimit,
loginRatePerIP: options.RateLimitPerIP,
loginRateWindow: options.RateLimitWindow,
instanceID: instanceID,
version: version,
startedAt: time.Now(),
+96
View File
@@ -1,10 +1,17 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"log/slog"
"math"
"net"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"mtusi.ru/messenger-lab7/internal/auth"
@@ -17,10 +24,21 @@ import (
// accepts a JSON body and never reveals whether the username exists.
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
ip := clientAddress(r)
if err != nil {
if problem := a.enforceLoginLimit(w, r, "", ip); problem != nil {
a.writeError(w, r, problem)
return
}
a.writeError(w, r, unauthorizedBasic())
return
}
// The shared login budget is consumed before any Argon2id work, so a
// credential-stuffing loop cannot spend unbounded KDF CPU on every replica.
if problem := a.enforceLoginLimit(w, r, username, ip); problem != nil {
a.writeError(w, r, problem)
return
}
// Reject values that could never have been registered before touching the
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
if !usernameAllowed(username) || !validLoginPassword(password) {
@@ -60,6 +78,26 @@ func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
return
}
// A successful login is the only safe moment to upgrade an old PHC string
// (for example a legacy lower-cost parameter set). A failed upgrade is
// logged but never turns a valid login into an error.
if auth.NeedsRehash(passwordHash) {
if upgraded, hashErr := auth.Hash(password); hashErr != nil {
a.log.Log(r.Context(), slog.LevelWarn, "password hash upgrade failed", "request_id", requestIDFromContext(r.Context()), "error", hashErr)
} else {
upgradeCtx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
updateErr := a.store.UpdatePasswordHash(upgradeCtx, user.ID, upgraded)
cancel()
if updateErr != nil {
a.log.Log(r.Context(), slog.LevelWarn, "password hash upgrade was not stored", "request_id", requestIDFromContext(r.Context()), "error", updateErr)
}
}
}
// Clear only the per-account counter; the per-IP budget keeps protecting
// other accounts from the same source.
_ = a.sessions.ResetRate(r.Context(), loginCounter("id", username, ip))
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
if err != nil {
a.log.Log(r.Context(), slog.LevelError, "session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
@@ -156,3 +194,61 @@ func validLoginPassword(password string) bool {
count := utf8.RuneCountInString(password)
return count >= 12 && count <= 128
}
// clientAddress returns the source address as seen through the mTLS LB. The
// API replicas have no published port, so X-Forwarded-For is set by the only
// component that can reach them. RemoteAddr is the fallback for local probes.
func clientAddress(r *http.Request) string {
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
if first := strings.TrimSpace(strings.Split(forwarded, ",")[0]); first != "" {
return first
}
}
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host
}
return r.RemoteAddr
}
// loginCounter returns an opaque Valkey key. Usernames and source addresses
// are hashed so a cache inspection does not enumerate accounts or clients.
func loginCounter(kind, username, ip string) string {
sum := sha256.Sum256([]byte(kind + "\x00" + username + "\x00" + ip))
return "mtusi:lab7:login:" + kind + ":" + hex.EncodeToString(sum[:16])
}
// enforceLoginLimit increments the shared per-account and per-source windows
// and returns a contract-shaped 429 with Retry-After when either is exhausted.
// A rate-store failure fails closed with 503 rather than disabling the limit.
func (a *App) enforceLoginLimit(w http.ResponseWriter, r *http.Request, username, ip string) *apiError {
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
type window struct {
key string
limit int
}
windows := []window{{key: loginCounter("ip", "", ip), limit: a.loginRatePerIP}}
if username != "" {
windows = append([]window{{key: loginCounter("id", username, ip), limit: a.loginRateLimit}}, windows...)
}
var retry time.Duration
for _, item := range windows {
count, ttl, err := a.sessions.HitRate(ctx, item.key, a.loginRateWindow)
if err != nil {
a.log.Log(r.Context(), slog.LevelError, "login rate limiter unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
return statusUnavailable
}
if count > int64(item.limit) && ttl > retry {
retry = ttl
}
}
if retry <= 0 {
return nil
}
seconds := int(math.Ceil(retry.Seconds()))
if seconds < 1 {
seconds = 1
}
w.Header().Set("Retry-After", strconv.Itoa(seconds))
return &apiError{status: http.StatusTooManyRequests, code: "rate_limited", message: "too many login attempts; retry later"}
}
+67 -16
View File
@@ -1,6 +1,7 @@
// Package auth implements the lab3 credential primitives: a library password
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
// these helpers log or serialise the secret material they receive.
// Package auth implements the lab7 credential primitives: Argon2id password
// hashing with configurable, measured parameters, opaque session tokens and
// RFC 7617 Basic parsing. None of these helpers log or serialise the secret
// material they receive.
package auth
import (
@@ -10,36 +11,71 @@ import (
"errors"
"fmt"
"strings"
"sync"
"golang.org/x/crypto/argon2"
)
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
// inside the 256 MiB API container limit. The parameters are stored in every
// PHC string, so a future change remains backward compatible.
// OWASP Password Storage Cheat Sheet minimum for Argon2id: m=19 MiB, t=2, p=1.
// The parameter set is stored in every PHC string, so old hashes remain
// verifiable and can be upgraded after a successful login (NeedsRehash).
const (
argonMemory uint32 = 19 * 1024 // KiB
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
defaultArgonMemory uint32 = 19 * 1024 // KiB
defaultArgonIterations uint32 = 2
defaultArgonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
)
var (
paramsMu sync.RWMutex
argonMemory = defaultArgonMemory
argonIterations = defaultArgonIterations
argonParallelism = defaultArgonParallelism
)
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
// parameters. It is an internal error, never shown to a client.
var ErrInvalidHash = errors.New("invalid password hash")
// Hash derives an Argon2id PHC string for password. Callers must validate the
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
// Configure selects the Argon2id parameters used for new hashes. Values below
// the OWASP minimum are rejected. Existing PHC strings are never rewritten
// without a successful password verification.
func Configure(memoryKiB, iterations uint32, parallelism uint8) error {
if memoryKiB < 19*1024 || memoryKiB > 256*1024 {
return fmt.Errorf("Argon2id memory must be between 19456 and 262144 KiB")
}
if iterations < 2 || iterations > 10 {
return fmt.Errorf("Argon2id iterations must be between 2 and 10")
}
if parallelism < 1 || parallelism > 16 {
return fmt.Errorf("Argon2id parallelism must be between 1 and 16")
}
paramsMu.Lock()
defer paramsMu.Unlock()
argonMemory = memoryKiB
argonIterations = iterations
argonParallelism = parallelism
return nil
}
// Parameters returns the parameters used for new hashes.
func Parameters() (memoryKiB, iterations uint32, parallelism uint8) {
paramsMu.RLock()
defer paramsMu.RUnlock()
return argonMemory, argonIterations, argonParallelism
}
// Hash derives an Argon2id PHC string for password.
func Hash(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
memory, iterations, parallelism := Parameters()
key := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonIterations, argonParallelism,
argon2.Version, memory, iterations, parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
@@ -57,6 +93,19 @@ func Verify(password, encoded string) (match bool, err error) {
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
}
// NeedsRehash reports whether a verified hash was produced with parameters
// different from the current configuration (for example a hash written by an
// earlier lab or a lower-cost legacy setting). The caller rehashes only after a
// successful verification and stores the new PHC string.
func NeedsRehash(encoded string) bool {
params, _, _, err := parse(encoded)
if err != nil {
return false
}
memory, iterations, parallelism := Parameters()
return params.memory != memory || params.iterations != iterations || params.parallelism != parallelism
}
type params struct {
memory uint32
iterations uint32
@@ -75,6 +124,8 @@ func parse(encoded string) (params, []byte, []byte, error) {
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
return params{}, nil, nil, ErrInvalidHash
}
// 8 MiB lower bound keeps explicitly documented legacy lab hashes
// verifiable; new hashes are always at least 19 MiB.
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
return params{}, nil, nil, ErrInvalidHash
}
+11 -1
View File
@@ -11,6 +11,7 @@ package broker
import (
"context"
"crypto/tls"
"errors"
"fmt"
"strconv"
@@ -29,6 +30,9 @@ type Config struct {
Stream string
Group string
Timeout time.Duration
// TLS carries the service CA and the per-service mTLS identity presented to
// the broker gateway. Only rediss:// is accepted; plaintext is refused.
TLS *tls.Config
}
// Broker wraps the Streams commands used by the API publisher and the worker.
@@ -46,7 +50,13 @@ func Open(ctx context.Context, cfg Config) (*Broker, error) {
}
options, err := redis.ParseURL(cfg.URL)
if err != nil {
return nil, errors.New("BROKER_URL is not a valid redis:// URL")
return nil, errors.New("BROKER_URL is not a valid rediss:// URL")
}
if options.TLSConfig == nil && cfg.TLS == nil {
return nil, errors.New("BROKER_URL must use rediss:// with a configured TLS policy")
}
if cfg.TLS != nil {
options.TLSConfig = cfg.TLS
}
if options.DB != 0 {
return nil, errors.New("BROKER_URL must use database 0")
+258 -18
View File
@@ -5,12 +5,15 @@
package config
import (
"context"
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
baosecrets "mtusi.ru/messenger-lab7/internal/secrets"
)
const (
@@ -83,11 +86,59 @@ type Config struct {
FaultInject string
FaultTargetAttachmentID string
// Lab7: external serving TLS, mandatory LB client mTLS and a CRL that
// fails closed when it is missing or expired.
TLSEnabled bool
TLSCertFile string
TLSKeyFile string
TLSClientCAFile string
TLSClientCRLFile string
TLSAllowedCNs []string
TLSServerName string
MaxBodyBytes int64
ArgonMemoryKiB uint32
ArgonIterations uint32
ArgonParallelism uint8
LoginRateWindow time.Duration
LoginRateAttempts int
LoginRatePerIP int
// Dependency TLS identity material. Every declared network link verifies
// the server certificate; broker, S3 and the collector additionally present
// a distinct client identity to the mTLS gateway.
S3CAFile string
S3ClientCertFile string
S3ClientKeyFile string
S3ServerName string
BrokerCAFile string
BrokerClientCert string
BrokerClientKey string
BrokerServerName string
CacheCAFile string
CacheClientCert string
CacheClientKey string
CacheServerName string
OpenBaoAddr string
OpenBaoCACert string
OpenBaoRoleIDFile string
OpenBaoSecretIDFile string
OpenBaoSecretPath string
OpenBaoTimeout time.Duration
OpenBaoTokenTTL time.Duration
OpenBao *baosecrets.Client
}
// Load reads and validates the full API configuration. The API publishes the
// transactional outbox to the durable broker, so BROKER_URL is mandatory.
func Load() (Config, error) { return load(true, true, true) }
func Load() (Config, error) {
cfg, err := load(true, true, true)
if err != nil {
return Config{}, err
}
return withOpenBao(cfg, "secret/data/lab7/api")
}
// LoadMigrate loads only what the one-shot migration command needs.
func LoadMigrate() (Config, error) { return load(false, false, false) }
@@ -101,7 +152,13 @@ func LoadJobctl() (Config, error) { return load(false, false, true) }
// LoadWorker loads the worker configuration: PostgreSQL, S3 and the broker.
// The session store is not used by the worker.
func LoadWorker() (Config, error) { return load(false, true, true) }
func LoadWorker() (Config, error) {
cfg, err := load(false, true, true)
if err != nil {
return Config{}, err
}
return withOpenBao(cfg, "secret/data/lab7/worker")
}
// load is the shared parser. requireCache, requireS3 and requireBroker select
// which dependency blocks are mandatory for the calling command.
@@ -135,15 +192,22 @@ func load(requireCache, requireS3, requireBroker bool) (Config, error) {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
// In the deployed stand BAO_ADDR is always set and the database, cache,
// broker and S3 credentials arrive from OpenBao after AppRole login. The
// explicit environment variables remain available for unit tests and
// one-shot operator tools, but the API/worker containers never receive
// them.
useOpenBao := strings.TrimSpace(os.Getenv("BAO_ADDR")) != ""
databaseURL, err := secret("DATABASE_URL")
if err != nil {
if err != nil && !useOpenBao {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
if requireCache {
cacheURL, err := secret("CACHE_URL")
if err != nil {
if err != nil && !useOpenBao {
return Config{}, err
}
cfg.CacheURL = cacheURL
@@ -227,22 +291,25 @@ func load(requireCache, requireS3, requireBroker bool) (Config, error) {
cfg.StartupTimeout = startup
if requireS3 {
if err := loadS3(&cfg); err != nil {
if err := loadS3(&cfg, useOpenBao); err != nil {
return Config{}, err
}
}
if requireBroker {
brokerURL, err := secret("BROKER_URL")
if err != nil {
if err != nil && !useOpenBao {
return Config{}, err
}
cfg.BrokerURL = brokerURL
cfg.BrokerStream = envString("BROKER_STREAM", "lab6:attachments:jobs")
cfg.BrokerGroup = envString("BROKER_GROUP", "attachment-workers")
cfg.BrokerStream = envString("BROKER_STREAM", "lab7:attachments:jobs")
cfg.BrokerGroup = envString("BROKER_GROUP", "lab7-attachment-workers")
}
if err := loadPipeline(&cfg); err != nil {
return Config{}, err
}
if err := loadSecurity(&cfg); err != nil {
return Config{}, err
}
return cfg, nil
}
@@ -336,7 +403,7 @@ func loadPipeline(cfg *Config) error {
// loadS3 parses the private object store configuration and the image limits
// that must be enforced before any unbounded read or decode.
func loadS3(cfg *Config) error {
func loadS3(cfg *Config, useOpenBao bool) error {
endpoint, err := secret("S3_ENDPOINT")
if err != nil {
return err
@@ -347,16 +414,18 @@ func loadS3(cfg *Config) error {
if !validBucketName(cfg.S3Bucket) {
return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
}
accessKey, err := secret("S3_ACCESS_KEY")
if err != nil {
return err
if !useOpenBao {
accessKey, err := secret("S3_ACCESS_KEY")
if err != nil {
return err
}
secretKey, err := secret("S3_SECRET_KEY")
if err != nil {
return err
}
cfg.S3AccessKey = accessKey
cfg.S3SecretKey = secretKey
}
secretKey, err := secret("S3_SECRET_KEY")
if err != nil {
return err
}
cfg.S3AccessKey = accessKey
cfg.S3SecretKey = secretKey
timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120)
if err != nil {
@@ -407,6 +476,177 @@ func loadS3(cfg *Config) error {
return nil
}
// loadSecurity parses the lab7-only settings. TLS is enabled explicitly by
// compose; the server binary additionally refuses to serve plaintext, so a
// missing variable cannot silently downgrade the public endpoint.
func loadSecurity(cfg *Config) error {
enabled, err := envBool("TLS_ENABLED", false)
if err != nil {
return fmt.Errorf("TLS_ENABLED: %w", err)
}
cfg.TLSEnabled = enabled
cfg.TLSCertFile = envString("TLS_CERT_FILE", "")
cfg.TLSKeyFile = envString("TLS_KEY_FILE", "")
cfg.TLSClientCAFile = envString("TLS_CLIENT_CA_FILE", "")
cfg.TLSClientCRLFile = envString("TLS_CLIENT_CRL_FILE", "")
cfg.TLSServerName = envString("TLS_SERVER_NAME", "api")
cfg.TLSAllowedCNs = envCSV("TLS_ALLOWED_CLIENT_CN")
if enabled {
if cfg.TLSCertFile == "" || cfg.TLSKeyFile == "" || cfg.TLSClientCAFile == "" || cfg.TLSClientCRLFile == "" {
return fmt.Errorf("TLS_CERT_FILE, TLS_KEY_FILE, TLS_CLIENT_CA_FILE and TLS_CLIENT_CRL_FILE are required when TLS_ENABLED=true")
}
if len(cfg.TLSAllowedCNs) == 0 {
return fmt.Errorf("TLS_ALLOWED_CLIENT_CN is required when TLS_ENABLED=true; a trusted CA alone is not enough")
}
}
maxBody, err := envInt64("MAX_BODY_BYTES", 1<<20)
if err != nil {
return fmt.Errorf("MAX_BODY_BYTES: %w", err)
}
if maxBody < 1024 || maxBody > 10*1024*1024 {
return fmt.Errorf("MAX_BODY_BYTES: must be between 1024 and 10485760")
}
cfg.MaxBodyBytes = maxBody
memory, err := envInt("ARGON2_MEMORY_KIB", 19*1024)
if err != nil {
return fmt.Errorf("ARGON2_MEMORY_KIB: %w", err)
}
// The OWASP minimum is 19 MiB for Argon2id with t=2, p=1. Values below the
// minimum are rejected instead of silently weakening password storage.
if memory < 19*1024 || memory > 256*1024 {
return fmt.Errorf("ARGON2_MEMORY_KIB: must be between 19456 and 262144")
}
cfg.ArgonMemoryKiB = uint32(memory)
iterations, err := envInt("ARGON2_ITERATIONS", 2)
if err != nil {
return fmt.Errorf("ARGON2_ITERATIONS: %w", err)
}
if iterations < 2 || iterations > 10 {
return fmt.Errorf("ARGON2_ITERATIONS: must be between 2 and 10")
}
cfg.ArgonIterations = uint32(iterations)
parallelism, err := envInt("ARGON2_PARALLELISM", 1)
if err != nil {
return fmt.Errorf("ARGON2_PARALLELISM: %w", err)
}
if parallelism < 1 || parallelism > 16 {
return fmt.Errorf("ARGON2_PARALLELISM: must be between 1 and 16")
}
cfg.ArgonParallelism = uint8(parallelism)
if cfg.LoginRateWindow, err = envDurationSeconds("LOGIN_RATE_WINDOW_SECONDS", 60, 10, 3600); err != nil {
return err
}
if cfg.LoginRateAttempts, err = envInt("LOGIN_RATE_MAX_ATTEMPTS", 5); err != nil {
return fmt.Errorf("LOGIN_RATE_MAX_ATTEMPTS: %w", err)
}
if cfg.LoginRateAttempts < 1 || cfg.LoginRateAttempts > 100 {
return fmt.Errorf("LOGIN_RATE_MAX_ATTEMPTS: must be between 1 and 100")
}
if cfg.LoginRatePerIP, err = envInt("LOGIN_RATE_MAX_PER_IP", 20); err != nil {
return fmt.Errorf("LOGIN_RATE_MAX_PER_IP: %w", err)
}
if cfg.LoginRatePerIP < 1 || cfg.LoginRatePerIP > 1000 {
return fmt.Errorf("LOGIN_RATE_MAX_PER_IP: must be between 1 and 1000")
}
cfg.S3CAFile = envString("S3_CA_FILE", "")
cfg.S3ClientCertFile = envString("S3_CLIENT_CERT_FILE", "")
cfg.S3ClientKeyFile = envString("S3_CLIENT_KEY_FILE", "")
cfg.S3ServerName = envString("S3_SERVER_NAME", "")
cfg.BrokerCAFile = envString("BROKER_CA_FILE", "")
cfg.BrokerClientCert = envString("BROKER_CLIENT_CERT_FILE", "")
cfg.BrokerClientKey = envString("BROKER_CLIENT_KEY_FILE", "")
cfg.BrokerServerName = envString("BROKER_SERVER_NAME", "")
cfg.CacheCAFile = envString("CACHE_CA_FILE", "")
cfg.CacheClientCert = envString("CACHE_CLIENT_CERT_FILE", "")
cfg.CacheClientKey = envString("CACHE_CLIENT_KEY_FILE", "")
cfg.CacheServerName = envString("CACHE_SERVER_NAME", "")
cfg.OpenBaoAddr = envString("BAO_ADDR", "")
cfg.OpenBaoCACert = envString("BAO_CACERT", "")
cfg.OpenBaoRoleIDFile = envString("BAO_ROLE_ID_FILE", "")
cfg.OpenBaoSecretIDFile = envString("BAO_SECRET_ID_FILE", "")
cfg.OpenBaoSecretPath = envString("BAO_SECRET_PATH", "")
if cfg.OpenBaoAddr != "" {
if cfg.OpenBaoCACert == "" || cfg.OpenBaoRoleIDFile == "" || cfg.OpenBaoSecretIDFile == "" {
return fmt.Errorf("BAO_ADDR requires BAO_CACERT, BAO_ROLE_ID_FILE and BAO_SECRET_ID_FILE")
}
}
if cfg.OpenBaoTimeout, err = envDurationSeconds("BAO_TIMEOUT_SECONDS", 30, 5, 120); err != nil {
return err
}
return nil
}
// withOpenBao replaces the environment credential fallback with one scoped KV
// document fetched through AppRole. The application never sees a root token,
// an unseal share or an unbounded shared token.
func withOpenBao(cfg Config, defaultPath string) (Config, error) {
if cfg.OpenBaoAddr == "" {
return cfg, nil
}
path := cfg.OpenBaoSecretPath
if path == "" {
path = defaultPath
}
values, client, err := baosecrets.Fetch(context.Background(), baosecrets.Config{
Address: cfg.OpenBaoAddr,
CACertFile: cfg.OpenBaoCACert,
RoleIDFile: cfg.OpenBaoRoleIDFile,
SecretIDFile: cfg.OpenBaoSecretIDFile,
SecretPath: path,
Timeout: cfg.OpenBaoTimeout,
})
if err != nil {
return Config{}, fmt.Errorf("OpenBao service authentication failed: %w", err)
}
cfg.DatabaseURL = values["database_url"]
cfg.BrokerURL = values["broker_url"]
cfg.S3AccessKey = values["s3_access_key"]
cfg.S3SecretKey = values["s3_secret_key"]
if cache := values["cache_url"]; cache != "" {
cfg.CacheURL = cache
}
if cfg.DatabaseURL == "" || cfg.BrokerURL == "" || cfg.S3AccessKey == "" || cfg.S3SecretKey == "" {
return Config{}, fmt.Errorf("OpenBao document %s is missing required database/broker/S3 fields", path)
}
cfg.OpenBao = client
cfg.OpenBaoTokenTTL = client.TTL()
return cfg, nil
}
func envBool(key string, fallback bool) (bool, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.ParseBool(strings.TrimSpace(raw))
if err != nil {
return false, fmt.Errorf("expected a boolean, got %q", raw)
}
return value, nil
}
func envCSV(key string) []string {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
return nil
}
parts := strings.Split(raw, ",")
values := make([]string, 0, len(parts))
for _, part := range parts {
if value := strings.TrimSpace(part); value != "" {
values = append(values, value)
}
}
return values
}
func validBucketName(value string) bool {
if len(value) < 3 || len(value) > 63 {
return false
+11 -2
View File
@@ -6,6 +6,7 @@ package objectstore
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
@@ -36,6 +37,10 @@ type Config struct {
AccessKey string
SecretKey string
Timeout time.Duration
// TLS is mandatory for https endpoints and carries the service CA plus the
// per-service client certificate used by the mTLS S3 gateway. Plaintext S3
// endpoints are refused: there is no disabled-verification fallback.
TLS *tls.Config
}
// Store is a thin, timeout-aware wrapper around minio-go.
@@ -52,8 +57,11 @@ func Open(cfg Config) (*Store, error) {
if err != nil || parsed.Host == "" {
return nil, errors.New("S3_ENDPOINT must be an http(s) URL with a host")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, errors.New("S3_ENDPOINT scheme must be http or https")
if parsed.Scheme != "https" {
return nil, errors.New("S3_ENDPOINT must use https; plaintext S3 is not allowed")
}
if cfg.TLS == nil {
return nil, errors.New("S3_ENDPOINT is https but no TLS configuration was provided")
}
if parsed.Path != "" && parsed.Path != "/" {
return nil, errors.New("S3_ENDPOINT must not contain a path")
@@ -70,6 +78,7 @@ func Open(cfg Config) (*Store, error) {
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: time.Second,
TLSClientConfig: cfg.TLS,
}
client, err := minio.New(parsed.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
+46
View File
@@ -9,6 +9,7 @@ package session
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
@@ -40,6 +41,9 @@ type Options struct {
DialTimeout time.Duration
IOTimeout time.Duration
TTL time.Duration
// TLS carries the service CA and the API client identity. Only rediss:// is
// accepted; a redis:// URL is a configuration error, not a fallback.
TLS *tls.Config
}
// Store is a thin, timeout-aware wrapper around go-redis.
@@ -56,6 +60,12 @@ func Open(rawURL string, options Options) (*Store, error) {
if err != nil {
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
}
if parsed.TLSConfig == nil && options.TLS == nil {
return nil, errors.New("CACHE_URL must use rediss:// with a configured TLS policy")
}
if options.TLS != nil {
parsed.TLSConfig = options.TLS
}
if options.PoolSize <= 0 {
options.PoolSize = 8
}
@@ -148,4 +158,40 @@ func (s *Store) Ping(ctx context.Context) error {
// Close releases the connection pool.
func (s *Store) Close() error { return s.client.Close() }
// HitRate atomically increments a shared counter and returns the new value and
// the remaining window. The counter lives in the same Valkey instance every API
// replica uses, so the login limit is global rather than per process.
func (s *Store) HitRate(ctx context.Context, counter string, window time.Duration) (int64, time.Duration, error) {
result, err := rateScript.Run(ctx, s.client, []string{counter}, window.Milliseconds()).Slice()
if err != nil {
return 0, 0, fmt.Errorf("%w: %w", ErrUnavailable, err)
}
if len(result) != 2 {
return 0, 0, fmt.Errorf("%w: unexpected rate script response", ErrUnavailable)
}
count, _ := result[0].(int64)
ttlMillis, _ := result[1].(int64)
if ttlMillis < 0 {
ttlMillis = 0
}
return count, time.Duration(ttlMillis) * time.Millisecond, nil
}
// ResetRate clears a login counter after a successful authentication.
func (s *Store) ResetRate(ctx context.Context, counter string) error {
if err := s.client.Del(ctx, counter).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
var rateScript = redis.NewScript(`
local n = redis.call('INCR', KEYS[1])
if n == 1 then
redis.call('PEXPIRE', KEYS[1], ARGV[1])
end
local ttl = redis.call('PTTL', KEYS[1])
return {n, ttl}
`)
func key(tokenHash string) string { return keyPrefix + tokenHash }
+13
View File
@@ -421,6 +421,19 @@ type PoolStats struct {
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
// UpdatePasswordHash replaces a PHC string after a successful login whose
// stored hash used legacy or lower-cost parameters. The caller has already
// verified the password; failure to upgrade never grants or denies access.
func (s *Store) UpdatePasswordHash(ctx context.Context, userID, encoded string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `UPDATE users SET password_hash = $2 WHERE id = $1::uuid`, userID, encoded)
if err != nil {
return s.classify(err)
}
return nil
}
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
// Count is the number of calls that had to wait for a free connection; a fast
// rising value while the API CPU is below its limit points at the database or
+38 -10
View File
@@ -8,6 +8,7 @@ package telemetry
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
@@ -27,6 +28,8 @@ import (
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"mtusi.ru/messenger-lab7/internal/tlsutil"
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
@@ -35,7 +38,7 @@ import (
const (
// DefaultEndpoint is the collector's OTLP/HTTP listener inside the compose
// network. It is never the address of a storage backend.
DefaultEndpoint = "http://otel-collector:4318"
DefaultEndpoint = "https://otel-gw:4318"
// These bounds make the SDK side of the telemetry pipeline finite. When a
// queue is full the SDK drops telemetry; it never blocks the caller.
@@ -121,6 +124,13 @@ func Setup(ctx context.Context, opts Options) (*Provider, error) {
if err != nil {
return nil, err
}
if insecure {
return nil, errors.New("OTEL_EXPORTER_OTLP_ENDPOINT must use https; plaintext OTLP is not allowed")
}
otlpTLS, err := otlpClientTLS(host)
if err != nil {
return nil, err
}
res, err := resource.New(ctx,
resource.WithAttributes(
@@ -142,9 +152,7 @@ func Setup(ctx context.Context, opts Options) (*Provider, error) {
otlptracehttp.WithURLPath("/v1/traces"),
otlptracehttp.WithTimeout(5 * time.Second),
otlptracehttp.WithCompression(otlptracehttp.GzipCompression),
}
if insecure {
traceOpts = append(traceOpts, otlptracehttp.WithInsecure())
otlptracehttp.WithTLSClientConfig(otlpTLS),
}
traceExporter, err := otlptracehttp.New(ctx, traceOpts...)
if err != nil {
@@ -173,9 +181,7 @@ func Setup(ctx context.Context, opts Options) (*Provider, error) {
otlpmetrichttp.WithURLPath("/v1/metrics"),
otlpmetrichttp.WithTimeout(10 * time.Second),
otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression),
}
if insecure {
metricOpts = append(metricOpts, otlpmetrichttp.WithInsecure())
otlpmetrichttp.WithTLSClientConfig(otlpTLS),
}
metricExporter, err := otlpmetrichttp.New(ctx, metricOpts...)
if err != nil {
@@ -195,9 +201,7 @@ func Setup(ctx context.Context, opts Options) (*Provider, error) {
otlploghttp.WithURLPath("/v1/logs"),
otlploghttp.WithTimeout(5 * time.Second),
otlploghttp.WithCompression(otlploghttp.GzipCompression),
}
if insecure {
logOpts = append(logOpts, otlploghttp.WithInsecure())
otlploghttp.WithTLSClientConfig(otlpTLS),
}
logExporter, err := otlploghttp.New(ctx, logOpts...)
if err != nil {
@@ -274,6 +278,30 @@ func (p *Provider) Shutdown(ctx context.Context) error {
return errors.Join(errs...)
}
// otlpClientTLS builds the mTLS identity presented to the OTLP gateway. The
// certificate paths are passed explicitly; the exporter never disables server
// verification and never falls back to plaintext.
func otlpClientTLS(host string) (*tls.Config, error) {
caFile := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_CERTIFICATE"))
certFile := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE"))
keyFile := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_CLIENT_KEY"))
serverName := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_SERVER_NAME"))
if serverName == "" {
serverName = "otel-gw"
}
if caFile == "" {
return nil, errors.New("OTEL_EXPORTER_OTLP_CERTIFICATE is required for the mTLS OTLP gateway")
}
if (certFile == "") != (keyFile == "") {
return nil, errors.New("both OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE and OTEL_EXPORTER_OTLP_CLIENT_KEY are required")
}
config, err := tlsutil.ClientConfig(caFile, certFile, keyFile, serverName)
if err != nil {
return nil, fmt.Errorf("OTLP TLS configuration: %w", err)
}
return config, nil
}
func parseEndpoint(raw string) (host string, insecure bool, err error) {
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" {
+172
View File
@@ -0,0 +1,172 @@
// Package tlsutil centralises the lab7 TLS policy. Server certificates are
// verified against the local CA and the expected hostname; mutually
// authenticated listeners additionally reject clients whose certificate chain
// is valid but whose serial is revoked or whose service identity (CN) is not in
// an explicit allowlist. A trusted CA alone is deliberately never sufficient.
package tlsutil
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"time"
)
// ServerConfig builds the API mTLS listener configuration.
//
// crlFile is mandatory: if the operator forgets to publish a CRL, the service
// fails closed instead of silently skipping revocation checks. The CRL must be
// signed by one of the client CAs and must not be expired.
func ServerConfig(certFile, keyFile, clientCAFile, crlFile string, allowedCNs []string) (*tls.Config, error) {
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("load server certificate: %w", err)
}
pool, caCerts, err := loadCAPool(clientCAFile)
if err != nil {
return nil, err
}
revoked, err := loadCRL(crlFile, caCerts)
if err != nil {
return nil, err
}
allowed := make(map[string]struct{}, len(allowedCNs))
for _, name := range allowedCNs {
if name != "" {
allowed[name] = struct{}{}
}
}
if len(allowed) == 0 {
return nil, errors.New("mTLS client identity allowlist is empty")
}
return &tls.Config{
Certificates: []tls.Certificate{certificate},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: pool,
MinVersion: tls.VersionTLS12,
VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return errors.New("client certificate is required")
}
leaf, err := x509.ParseCertificate(rawCerts[0])
if err != nil {
return fmt.Errorf("parse client certificate: %w", err)
}
if _, ok := allowed[leaf.Subject.CommonName]; !ok {
return fmt.Errorf("client identity %q is not allowed on this listener", leaf.Subject.CommonName)
}
if serial, ok := revoked[leaf.SerialNumber.String()]; ok {
return fmt.Errorf("client certificate serial %s was revoked at %s", leaf.SerialNumber, serial.Format(time.RFC3339))
}
return nil
},
}, nil
}
// ClientConfig verifies the server certificate against a local CA and the
// expected service name. If a client certificate/key pair is supplied, it is
// presented for the mTLS gateways. There is intentionally no InsecureSkipVerify
// option.
func ClientConfig(caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
pool, _, err := loadCAPool(caFile)
if err != nil {
return nil, err
}
if serverName == "" {
return nil, errors.New("TLS server name is required")
}
config := &tls.Config{
RootCAs: pool,
ServerName: serverName,
MinVersion: tls.VersionTLS12,
}
if certFile != "" || keyFile != "" {
if certFile == "" || keyFile == "" {
return nil, errors.New("both client certificate and key are required")
}
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("load client certificate: %w", err)
}
config.Certificates = []tls.Certificate{certificate}
}
return config, nil
}
func loadCAPool(path string) (*x509.CertPool, []*x509.Certificate, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, nil, fmt.Errorf("read CA certificate: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(data) {
return nil, nil, errors.New("CA file contains no certificates")
}
certs, err := parseCertificates(data)
if err != nil {
return nil, nil, err
}
return pool, certs, nil
}
func parseCertificates(data []byte) ([]*x509.Certificate, error) {
var certs []*x509.Certificate
for {
block, rest := pem.Decode(data)
if block == nil {
break
}
data = rest
if block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parse CA certificate: %w", err)
}
certs = append(certs, cert)
}
if len(certs) == 0 {
return nil, errors.New("no certificates found")
}
return certs, nil
}
func loadCRL(path string, caCerts []*x509.Certificate) (map[string]time.Time, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read client CRL: %w", err)
}
var der []byte
if block, _ := pem.Decode(data); block != nil {
der = block.Bytes
} else {
der = data
}
crl, err := x509.ParseRevocationList(der)
if err != nil {
return nil, fmt.Errorf("parse client CRL: %w", err)
}
verified := false
for _, ca := range caCerts {
if err := crl.CheckSignatureFrom(ca); err == nil {
verified = true
break
}
}
if !verified {
return nil, errors.New("client CRL is not signed by the configured client CA")
}
now := time.Now()
if now.Before(crl.ThisUpdate.Add(-5*time.Minute)) || now.After(crl.NextUpdate) {
return nil, fmt.Errorf("client CRL is not current (next update %s)", crl.NextUpdate.Format(time.RFC3339))
}
revoked := make(map[string]time.Time, len(crl.RevokedCertificateEntries))
for _, entry := range crl.RevokedCertificateEntries {
revoked[entry.SerialNumber.String()] = entry.RevocationTime
}
return revoked, nil
}
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env bash
# Local, documented bootstrap for the lab7 teaching stand.
#
# Creates every credential and certificate OUTSIDE Git:
# .local-secrets/pki two local CAs, leaf keys/certs, ledger, CRLs
# .local-secrets/secrets synthetic passwords and S3 keys
# .local-secrets/dsn one-shot migration/admin DSNs
# .local-secrets/acl Valkey ACL files
# .local-secrets/seaweedfs private S3 identity file
# .local-secrets/kv the two KV documents OpenBao will serve
# .local-secrets/openbao operator init file (written by the one-shot)
# .local-secrets/approle AppRole role-id/secret-id, read by API/worker
#
# No value is printed. The directory is mode 0700; CA private keys are mode
# 0600 and are never mounted into a container. Leaf keys are 0644 only inside
# this owner-only directory so that the non-root uid 10001 application can read
# the read-only compose secret mounts.
set -euo pipefail
cd "$(dirname "$0")/.."
ROOT=.local-secrets
if [ ! -f .env ]; then
cp .env.example .env
chmod 600 .env
echo "wrote .env from .env.example (no secret values)"
fi
umask 022
mkdir -p "$ROOT"/{pki,secrets,dsn,acl,seaweedfs,kv,openbao,approle}
chmod 700 "$ROOT" "$ROOT"/{pki,secrets,dsn,acl,seaweedfs,kv,openbao}
chmod 755 "$ROOT/approle"
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 48 || true
}
ensure_secret() {
name=$1
path="$ROOT/secrets/$name"
if [ ! -s "$path" ]; then
value=$(random_secret)
if [ "${#value}" -ne 48 ]; then
echo "bootstrap: could not generate $name" >&2
exit 1
fi
printf '%s' "$value" > "$path"
fi
chmod 644 "$path"
}
for name in postgres_admin_password postgres_migrate_password \
postgres_api_password postgres_worker_password \
valkey_session_password valkey_operator_password broker_api_password broker_worker_password \
s3_admin_access s3_admin_secret s3_api_access s3_api_secret \
s3_worker_access s3_worker_secret grafana_admin_password; do
ensure_secret "$name"
done
# ---------------------------------------------------------------------------
# Offline PKI. pkitool only uses the Go standard library.
# ---------------------------------------------------------------------------
PKITOOL=${PKITOOL:-}
if [ -z "$PKITOOL" ]; then
GOTOOLCHAIN=${GOTOOLCHAIN:-go1.26.0} go build -o "$ROOT/pkitool" ./cmd/pkitool
PKITOOL="$ROOT/pkitool"
fi
"$PKITOOL" init -dir "$ROOT/pki" >/dev/null
issue() {
ca=$1; name=$2; cn=$3; profile=$4; sans=${5:-}; days=${6:-30}
if [ -s "$ROOT/pki/$name.crt" ] && [ -s "$ROOT/pki/$name.key" ]; then
return
fi
args=(-ca "$ca" -name "$name" -cn "$cn" -profile "$profile" -validity "$((days * 24))h")
if [ -n "$sans" ]; then
args+=(-sans "$sans")
fi
"$PKITOOL" issue -dir "$ROOT/pki" "${args[@]}" >/dev/null
}
# Internal service CA: every internal TLS server and every mutually
# authenticated client identity.
issue service api-server api server api 90
issue service lb-client lab7-lb client 30
issue service postgres-server postgres server postgres 90
issue service s3-server s3-gw server s3-gw 90
issue service broker-server broker-gw server broker-gw 90
issue service session-server session-gw server session-gw 90
issue service otel-server otel-gw server otel-gw 90
issue service telemetry-server telemetry-gw server telemetry-gw 90
issue service openbao-server openbao server openbao,localhost,ip:127.0.0.1 90
issue service api-client lab7-api client 30
issue service worker-client lab7-worker client 30
issue service bootstrap-client lab7-bootstrap client 1
issue service collector-client lab7-collector client 30
issue service prometheus-client lab7-prometheus client 30
issue service grafana-client lab7-grafana client 30
# Edge CA: certificates the operator's browser/CLI trusts for loopback.
issue edge lb-server localhost server localhost,ip:127.0.0.1 90
issue edge grafana-server localhost server localhost,ip:127.0.0.1 90
"$PKITOOL" crl -dir "$ROOT/pki" -ca service >/dev/null
"$PKITOOL" crl -dir "$ROOT/pki" -ca edge >/dev/null
# HAProxy accepts a single PEM containing the leaf certificate and key.
for name in lb-server s3-server broker-server session-server otel-server telemetry-server; do
cat "$ROOT/pki/$name.crt" "$ROOT/pki/$name.key" > "$ROOT/pki/$name.pem"
chmod 644 "$ROOT/pki/$name.pem"
done
cat "$ROOT/pki/lb-client.crt" "$ROOT/pki/lb-client.key" > "$ROOT/pki/lb-client.pem"
chmod 644 "$ROOT/pki/lb-client.pem"
# Leaf keys are readable by container uid 10001 through a read-only mount; the
# owner-only 0700 directory is the at-rest boundary. CA keys stay 0600.
find "$ROOT/pki" -name '*.key' ! -name '*-ca.key' -exec chmod 644 {} +
chmod 600 "$ROOT/pki"/*-ca.key "$ROOT/pki/ledger.json"
# ---------------------------------------------------------------------------
# Synthetic secrets consumed by the one-shot DB/S3/OpenBao bootstrap.
# ---------------------------------------------------------------------------
secret() { cat "$ROOT/secrets/$1"; }
bucket=messenger-attachments
db_user=messenger
db_name=messenger
pg_host=postgres:5432
dsn() {
local user=$1 password=$2
printf 'postgres://%s:%s@%s/%s?sslmode=verify-full&sslrootcert=/run/secrets/service_ca' \
"$user" "$password" "$pg_host" "$db_name"
}
dsn messenger "$(secret postgres_admin_password)" > "$ROOT/dsn/admin"
dsn messenger_migrate "$(secret postgres_migrate_password)" > "$ROOT/dsn/migrate"
dsn messenger_api "$(secret postgres_api_password)" > "$ROOT/dsn/api"
dsn messenger_worker "$(secret postgres_worker_password)" > "$ROOT/dsn/worker"
chmod 644 "$ROOT"/dsn/*
cat > "$ROOT/seaweedfs/s3.json" <<EOF
{
"identities": [
{
"name": "lab7-admin-bootstrap",
"credentials": [{"accessKey": "$(secret s3_admin_access)", "secretKey": "$(secret s3_admin_secret)"}],
"actions": ["Admin"]
},
{
"name": "lab7-api-bucket-scoped",
"credentials": [{"accessKey": "$(secret s3_api_access)", "secretKey": "$(secret s3_api_secret)"}],
"actions": ["Read:${bucket}", "Write:${bucket}", "List:${bucket}"]
},
{
"name": "lab7-worker-bucket-scoped",
"credentials": [{"accessKey": "$(secret s3_worker_access)", "secretKey": "$(secret s3_worker_secret)"}],
"actions": ["Read:${bucket}", "Write:${bucket}", "List:${bucket}"]
}
]
}
EOF
chmod 644 "$ROOT/seaweedfs/s3.json"
session_prefix='mtusi:lab3:session:*'
cat > "$ROOT/acl/session.acl" <<EOF
user default off
user session on >$(secret valkey_session_password) ~mtusi:* +get +set +del +incr +pexpire +pttl +eval +evalsha +ping +hello +auth +client|setinfo
user operator on >$(secret valkey_operator_password) ~* +@all
EOF
cat > "$ROOT/acl/broker.acl" <<EOF
user default off
user api on >$(secret broker_api_password) ~lab7:* +xadd +xlen +xrevrange +xrange +xinfo +xpending +ping +hello +auth +client|setinfo
user operator on >$(secret valkey_operator_password) ~* +@all
user worker on >$(secret broker_worker_password) ~lab7:* +xgroup +xreadgroup +xack +xautoclaim +xpending +xlen +xinfo +ping +hello +auth +client|setinfo
EOF
chmod 644 "$ROOT/acl"/*.acl
# KV documents served by OpenBao after AppRole authentication.
cat > "$ROOT/kv/api.json" <<EOF
{
"database_url": "$(cat "$ROOT/dsn/api")",
"cache_url": "rediss://session:$(secret valkey_session_password)@session-gw:6379/0",
"broker_url": "rediss://api:$(secret broker_api_password)@broker-gw:6379/0",
"s3_access_key": "$(secret s3_api_access)",
"s3_secret_key": "$(secret s3_api_secret)"
}
EOF
cat > "$ROOT/kv/worker.json" <<EOF
{
"database_url": "$(cat "$ROOT/dsn/worker")",
"broker_url": "rediss://worker:$(secret broker_worker_password)@broker-gw:6379/0",
"s3_access_key": "$(secret s3_worker_access)",
"s3_secret_key": "$(secret s3_worker_secret)"
}
EOF
chmod 644 "$ROOT/kv"/*.json
python3 scripts/render-grafana-datasources.py >/dev/null
echo "local PKI, credentials, ACLs and OpenBao KV inputs are ready under $ROOT (no values printed)"
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Accept both the Compose v2 plugin ("docker compose") and the standalone
# binary ("docker-compose"), so the same Makefile works on both installations.
set -eu
if docker compose version >/dev/null 2>&1; then
exec docker compose "$@"
fi
if command -v docker-compose >/dev/null 2>&1; then
exec docker-compose "$@"
fi
echo "Docker Compose is required (docker compose or docker-compose)" >&2
exit 2
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Render the Grafana datasource provisioning file with the local mTLS material.
The template is committed; the rendered file contains public certificates and
one service client key, so it is written under .local-secrets/ (mode 0600) and
is never committed. Grafana reads it read-only.
"""
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TEMPLATE = ROOT / "infra/grafana/provisioning/datasources/datasources.yaml.tmpl"
PKI = ROOT / ".local-secrets/pki"
OUTPUT = ROOT / ".local-secrets/grafana/datasources.yaml"
def indent(path: Path, spaces: int) -> str:
body = path.read_text()
prefix = " " * spaces
return "\n".join(prefix + line for line in body.rstrip("\n").splitlines())
def main() -> None:
template = TEMPLATE.read_text()
rendered = (
template.replace("__CA_PEM__", indent(PKI / "service-ca.crt", 8))
.replace("__CLIENT_CERT_PEM__", indent(PKI / "grafana-client.crt", 8))
.replace("__CLIENT_KEY_PEM__", indent(PKI / "grafana-client.key", 8))
)
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
OUTPUT.write_text(rendered)
OUTPUT.chmod(0o644)
print("rendered Grafana datasource provisioning under .local-secrets/grafana/")
if __name__ == "__main__":
main()
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# Restart the API, worker and every state store while keeping named volumes.
# OpenBao comes back sealed, so the operator-authorized one-shot unseals it; the
# apps then receive the same scoped secrets and existing data stays intact.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
echo "restart.sh: .env is missing; run make env first" >&2
exit 2
fi
compose="./scripts/compose.sh --env-file .env"
wait_healthy() {
container=$1
attempts=0
while [ "$attempts" -lt 90 ]; do
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: $container did not become healthy" >&2
return 1
}
echo "restart.sh: restarting postgres, session valkey, broker, S3 and OpenBao (volumes kept)"
$compose restart postgres valkey-store broker-store s3-store openbao
for service in postgres valkey-store broker-store s3-store openbao; do
container=$($compose ps -q "$service")
wait_healthy "$container"
done
echo "restart.sh: unsealing OpenBao with the local operator share"
$compose run --rm --no-deps openbao-bootstrap unseal-only
echo "restart.sh: restarting every API replica and the worker"
$compose restart api worker
for container in $($compose ps -q api) $($compose ps -q worker); do
wait_healthy "$container"
done
CA=.local-secrets/pki/edge-ca.crt
attempts=0
while [ "$attempts" -lt 120 ]; do
if curl -fsS --cacert "$CA" -o /dev/null "https://localhost:${LB_PORT:-8447}/health/ready" 2>/dev/null; then
echo "restart.sh: all lab7 services restarted; volumes preserved"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: LB readiness did not recover" >&2
exit 1
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Stop exactly the API replica that served TARGET_INSTANCE_ID and leave it
# stopped. The public X-Instance-Id is an opaque alias: SHA-256(container
# hostname)[:12], so the mapping is exact but a response header does not reveal
# a hostname or IP.
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
if [ ! -f .env ]; then
echo "stop-one.sh: .env is missing; run make env first" >&2
exit 2
fi
alias_for() {
if command -v shasum >/dev/null 2>&1; then
printf '%s' "$1" | shasum -a 256 | cut -c1-12
else
printf '%s' "$1" | openssl dgst -sha256 -r | cut -c1-12
fi
}
target=""
for container in $(./scripts/compose.sh --env-file .env ps -q api); do
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
if [ "lab7-api-$(alias_for "$hostname")" = "$TARGET_INSTANCE_ID" ]; then
target=$container
break
fi
done
if [ -z "$target" ]; then
echo "stop-one.sh: no running API container matches $TARGET_INSTANCE_ID" >&2
exit 1
fi
echo "stop-one.sh: stopping API container $target (instance $TARGET_INSTANCE_ID)"
docker stop --time 15 "$target" >/dev/null
state=$(docker inspect -f '{{.State.Status}}' "$target")
if [ "$state" != "exited" ] && [ "$state" != "dead" ]; then
echo "stop-one.sh: container state is $state, expected exited" >&2
exit 1
fi
echo "stop-one.sh: container $target is $state; other replicas keep serving"
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Wait until /health/ready answers 200 through the HTTPS load balancer using the
# locally generated edge CA. No --insecure and no plaintext fallback.
set -eu
cd "$(dirname "$0")/.."
CA=${CA_FILE:-.local-secrets/pki/edge-ca.crt}
url=${1:-https://localhost:${LB_PORT:-8447}/health/ready}
attempts=0
while [ "$attempts" -lt 180 ]; do
if curl -fsS --cacert "$CA" -o /dev/null "$url" 2>/dev/null; then
echo "ready: $url"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "not ready after 180 seconds: $url" >&2
exit 1
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# Wait for Prometheus, Loki, Tempo and Grafana local administrative endpoints.
set -eu
cd "$(dirname "$0")/.."
CA=.local-secrets/pki/edge-ca.crt
wait_url() {
name=$1; url=$2; args=${3:-}
attempts=0
while [ "$attempts" -lt 120 ]; do
# shellcheck disable=SC2086
if curl -fsS $args -o /dev/null "$url" 2>/dev/null; then
echo "$name ready"
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "$name did not become ready: $url" >&2
return 1
}
wait_url prometheus "http://127.0.0.1:${PROMETHEUS_PORT:-9097}/-/ready"
wait_url loki "http://127.0.0.1:${LOKI_PORT:-3107}/ready"
wait_url tempo "http://127.0.0.1:${TEMPO_PORT:-3207}/ready"
wait_url grafana "https://localhost:${GRAFANA_PORT:-3007}/api/health" "--cacert $CA"