From 05df1695febfb45edbebb0a7a1365b10bcd0a4a2 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:57:24 +0300 Subject: [PATCH] =?UTF-8?q?lab7:=20Argon2id=20=D0=B8=D0=B7=20env=20(=D0=B7?= =?UTF-8?q?=D0=B0=D0=BC=D0=B5=D1=80=20bench/argon2=5Fbench.py),=20=D0=BB?= =?UTF-8?q?=D0=B8=D0=BC=D0=B8=D1=82=20=D0=BD=D0=B5=D1=83=D0=B4=D0=B0=D1=87?= =?UTF-8?q?=D0=BD=D1=8B=D1=85=20=D0=B2=D1=85=D0=BE=D0=B4=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B2=20Valkey=20(429=20+=20Retry-After),=20cap=5Fdrop=20ALL?= =?UTF-8?q?=20=D0=B8=20no-new-privileges,=20X-Instance-Id=20=3D=20=D1=81?= =?UTF-8?q?=D0=BB=D1=83=D1=87=D0=B0=D0=B9=D0=BD=D1=8B=D0=B9=20alias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bench/argon2_bench.py | 96 +++++++++++++++++++++++ compose.yaml | 78 +++++++++++++++++++ infra/haproxy/haproxy.cfg | 4 + infra/valkey/start.sh | 4 +- scripts/lbctl.py | 12 ++- scripts/stop-one.sh | 13 ++-- src/messenger/__main__.py | 3 +- src/messenger/app.py | 32 +++++++- src/messenger/config.py | 55 ++++++++++--- src/messenger/passwords.py | 36 ++++++--- src/messenger/ratelimit.py | 116 ++++++++++++++++++++++++++++ src/messenger/relay.py | 3 +- src/messenger/worker.py | 3 +- student-tests/test_balancing.py | 16 ++-- student-tests/test_idempotency.py | 2 +- student-tests/test_pipeline_flow.py | 8 +- 16 files changed, 431 insertions(+), 50 deletions(-) create mode 100644 bench/argon2_bench.py create mode 100644 src/messenger/ratelimit.py diff --git a/bench/argon2_bench.py b/bench/argon2_bench.py new file mode 100644 index 0000000..804a7dd --- /dev/null +++ b/bench/argon2_bench.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Argon2id parameter measurement ON THIS STAND (README grade 3: "параметры обоснованы измерением"). + +Runs INSIDE an API replica, i.e. with exactly the CPU/RAM limits of production (compose: 1 CPU, +512 MiB) and the same argon2-cffi build: + + docker compose exec -T api python - < bench/argon2_bench.py > evidence/argon2/bench.json + +For every (m, t) of the grid (p = 1): N sequential hashes -> median / p95 latency and CPU time per +hash; then, for the candidate parameters, K threads hashing at once (K = 1, 2, 4) -> latency +under contention and hashes/s of the replica = the most logins/s one replica can verify +(the cost of a password guessing / login DoS attempt). Prints one JSON document (no passwords: +a fixed synthetic one is hashed). +""" +import json +import os +import platform +import statistics +import threading +import time + +import importlib.metadata +from argon2 import PasswordHasher, Type + +PASSWORD = "synthetic-benchmark-password" +GRID_M = [19456, 32768, 47104, 65536] # KiB: 19 MiB (OWASP minimum), 32, 46, 64 MiB +GRID_T = [2, 3, 4] +N = int(os.environ.get("BENCH_N", "15")) +THREADS = [1, 2, 4] +PER_THREAD = int(os.environ.get("BENCH_PER_THREAD", "6")) + + +def cgroup_limits() -> dict: + out = {} + for name, path in (("cpu_max", "/sys/fs/cgroup/cpu.max"), ("memory_max", "/sys/fs/cgroup/memory.max")): + try: + with open(path) as f: + out[name] = f.read().strip() + except OSError: + out[name] = None + return out + + +def sequential(m: int, t: int) -> dict: + ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=1, hash_len=32, salt_len=16, type=Type.ID) + ph.hash(PASSWORD) # warm-up (allocator, first-touch of the pages) + wall, cpu = [], [] + for _ in range(N): + w0, c0 = time.perf_counter(), time.thread_time() + ph.hash(PASSWORD) + wall.append((time.perf_counter() - w0) * 1000) + cpu.append((time.thread_time() - c0) * 1000) + wall.sort() + return {"m_kib": m, "t": t, "p": 1, "n": N, "median_ms": round(statistics.median(wall), 1), + "p95_ms": round(wall[min(len(wall) - 1, int(0.95 * len(wall)))], 1), + "cpu_ms_per_hash": round(statistics.median(cpu), 1), + "hash_example_prefix": ph.hash(PASSWORD).split("$")[1:4]} + + +def concurrent(m: int, t: int, threads: int) -> dict: + ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=1, hash_len=32, salt_len=16, type=Type.ID) + lat: list[float] = [] + lock = threading.Lock() + + def work(): + for _ in range(PER_THREAD): + w0 = time.perf_counter() + ph.hash(PASSWORD) + with lock: + lat.append((time.perf_counter() - w0) * 1000) + + c0, w0 = time.process_time(), time.perf_counter() + pool = [threading.Thread(target=work) for _ in range(threads)] + for th in pool: + th.start() + for th in pool: + th.join() + wall = time.perf_counter() - w0 + lat.sort() + return {"m_kib": m, "t": t, "threads": threads, "hashes": len(lat), "wall_s": round(wall, 2), + "hashes_per_s": round(len(lat) / wall, 1), "median_ms": round(statistics.median(lat), 1), + "p95_ms": round(lat[min(len(lat) - 1, int(0.95 * len(lat)))], 1), + "cpu_utilisation": round((time.process_time() - c0) / wall, 2), + "ram_mib_hashing": round(m * threads / 1024, 1)} + + +def main() -> None: + report = {"when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "python": platform.python_version(), + "argon2_cffi": importlib.metadata.version("argon2-cffi"), "cpus_visible": os.cpu_count(), "cgroup": cgroup_limits(), + "sequential": [sequential(m, t) for m in GRID_M for t in GRID_T]} + report["concurrent"] = [concurrent(m, t, k) for (m, t) in ((19456, 2), (47104, 2), (19456, 3)) for k in THREADS] + print(json.dumps(report, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/compose.yaml b/compose.yaml index ac09912..f23a7b1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -33,6 +33,9 @@ name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} # database_url, cache_url, broker_url and the S3 key pair are NOT mounted as files into api, relay, # worker any more (src/messenger/bao.py). x-bao-env: &bao-env + # Not a secret: the random X-Instance-Id alias of the process (config.py), for the operator's + # alias -> container mapping (scripts/stop-one.sh). + INSTANCE_ID_FILE: /tmp/instance_id BAO_ADDR: https://openbao:8200 BAO_CACERT: /run/secrets/internal-ca.crt BAO_ROLE_ID_FILE: /run/secrets/bao_role_id @@ -49,6 +52,16 @@ x-api-env: &api-env DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3} CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-0.5} PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2} + # Lab 7: Argon2id parameters, chosen by a measurement on this stand (bench/argon2_bench.py, + # REPORT.md); the application refuses values below m=19456 KiB, t=2, p=1. + ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456} + ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2} + ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1} + # Lab 7: failed-login limits (src/messenger/ratelimit.py) -> 429 + Retry-After. + LOGIN_RATE_LIMIT_USER: ${LOGIN_RATE_LIMIT_USER:-5} + LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS: ${LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS:-60} + LOGIN_RATE_LIMIT_IP: ${LOGIN_RATE_LIMIT_IP:-50} + LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS: ${LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS:-300} IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} # Graceful stop: 3 s drain (readiness 503, still serving) + up to 8 s for in-flight requests. DRAIN_SECONDS: ${DRAIN_SECONDS:-3} @@ -166,6 +179,11 @@ services: start_period: 10s stop_grace_period: 30s # clean shutdown checkpoint instead of crash recovery restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -192,6 +210,11 @@ services: retries: 30 start_period: 5s restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -232,6 +255,11 @@ services: start_period: 10s stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [storage] deploy: resources: @@ -262,6 +290,11 @@ services: start_period: 20s stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: the image starts as root only to chown its data and drop to its own user + # (gosu/su-exec): exactly the capabilities for that, nothing else (no NET_RAW, MKNOD, ...). + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID] + security_opt: ["no-new-privileges:true"] networks: [queue] deploy: resources: @@ -287,6 +320,9 @@ services: healthcheck: disable: true restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -329,6 +365,9 @@ services: healthcheck: disable: true restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [storage] deploy: resources: @@ -381,6 +420,9 @@ services: condition: service_healthy # healthy = unsealed (see the openbao healthcheck) stop_grace_period: 15s # > DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS (11 s) restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [edge, data, storage, telemetry, vault] deploy: replicas: ${API_REPLICAS:-2} @@ -418,6 +460,9 @@ services: api: condition: service_healthy restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [edge] deploy: resources: @@ -456,6 +501,9 @@ services: condition: service_healthy stop_grace_period: 10s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data, queue, telemetry, vault] deploy: resources: @@ -504,6 +552,9 @@ services: condition: service_healthy stop_grace_period: 30s # > WORKER_SHUTDOWN_SECONDS (20 s) + release restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data, storage, queue, telemetry, vault] deploy: replicas: ${WORKER_REPLICAS:-1} @@ -541,6 +592,9 @@ services: s3: condition: service_healthy restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data, storage] deploy: resources: @@ -563,6 +617,9 @@ services: postgres: condition: service_healthy restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [data] deploy: resources: @@ -588,6 +645,9 @@ services: - {source: pki_foreign_lb_crt, target: foreign-lb.crt} - {source: pki_foreign_lb_key, target: foreign-lb.key} restart: "no" + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [edge] deploy: resources: @@ -622,6 +682,9 @@ services: start_period: 5s stop_grace_period: 15s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [vault] deploy: resources: @@ -646,6 +709,9 @@ services: volumes: - ./infra/otel:/etc/otelcol:ro restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -681,6 +747,9 @@ services: start_period: 10s stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -700,6 +769,9 @@ services: - lokidata:/loki stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -719,6 +791,9 @@ services: - tempodata:/var/tempo stop_grace_period: 30s restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry] deploy: resources: @@ -778,6 +853,9 @@ services: tempo: condition: service_started restart: unless-stopped + # Lab 7 hardening: no Linux capabilities at all, no privilege gain via setuid binaries. + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] networks: [telemetry, ui] deploy: resources: diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 05a5428..ad25c42 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -89,6 +89,10 @@ frontend public # API echoes it, and errors generated by the LB itself carry the same value. http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ } http-request set-var(txn.request_id) req.hdr(x-request-id) + # Lab 7: the client address for the API's login rate limit. OVERWRITTEN (never appended to a + # client-supplied value), so a client cannot pick its own "IP"; the API trusts it only because + # nobody but this LB (mTLS identity lb) can connect to the API. + http-request set-header X-Forwarded-For %[src] log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] \"%HM %HPO\"" use_backend api if { nbsrv(api) gt 0 } default_backend api_core diff --git a/infra/valkey/start.sh b/infra/valkey/start.sh index 55b7010..8f53fd6 100644 --- a/infra/valkey/start.sh +++ b/infra/valkey/start.sh @@ -4,7 +4,7 @@ # user default off no anonymous/shared-password access at all # user api SHA-256 of its password only (the plain password never lands in a file here), # keys session:* (sessions.py) and ratelimit:* (login limit), commands it uses: -# GET/SET/DEL (sessions), INCR/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING +# GET/SET/DEL (sessions), INCR(BY)/PEXPIRE/PTTL in MULTI/EXEC (rate limit), PING # (readiness), CLIENT SETINFO (sent by redis-py on connect). FLUSHALL, CONFIG, # KEYS, DEBUG, ACL, ... are refused with NOPERM. set -eu @@ -12,7 +12,7 @@ umask 077 mkdir -p /tmp/valkey hash="$(tr -d '\r\n' < /run/secrets/valkey_api_password | sha256sum | cut -d' ' -f1)" printf 'user default off\n' > /tmp/valkey/users.acl -printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \ +printf 'user api on #%s resetkeys ~session:* ~ratelimit:* resetchannels -@all +get +set +del +incr +incrby +pexpire +pttl +multi +exec +discard +ping +client|setinfo\n' \ "$hash" >> /tmp/valkey/users.acl chown -R valkey /tmp/valkey exec docker-entrypoint.sh valkey-server /etc/valkey/valkey.conf diff --git a/scripts/lbctl.py b/scripts/lbctl.py index 259d35e..9d393a3 100644 --- a/scripts/lbctl.py +++ b/scripts/lbctl.py @@ -13,6 +13,7 @@ from __future__ import annotations import argparse import json +import os import subprocess import sys import time @@ -33,6 +34,13 @@ def run(*args: str, timeout: float = 60) -> str: return result.stdout +def instance_alias(container_id: str) -> str | None: + """X-Instance-Id of the process running in the container (lab 7: random alias, not the hostname).""" + result = subprocess.run(["docker", "exec", container_id, "cat", "/tmp/instance_id"], capture_output=True, + text=True, timeout=30, env={**os.environ, "MSYS_NO_PATHCONV": "1"}) + return (result.stdout.strip() or None) if result.returncode == 0 else None + + def replicas(all_states: bool = True) -> list[dict]: """API containers of this compose project (running and stopped).""" ids = run("docker", "compose", "ps", "-q", *(["-a"] if all_states else []), "api").split() @@ -46,6 +54,8 @@ def replicas(all_states: bool = True) -> list[dict]: "id": item["Id"][:12], "name": item["Name"].lstrip("/"), "hostname": item["Config"]["Hostname"], + # Lab 7: X-Instance-Id is a random alias the process writes to /tmp/instance_id. + "instance": instance_alias(item["Id"][:12]) if item["State"]["Status"] == "running" else None, "state": item["State"]["Status"], "health": (item["State"].get("Health") or {}).get("Status", "-"), "exit_code": item["State"]["ExitCode"], @@ -75,7 +85,7 @@ def lb_servers() -> list[dict]: container = by_ip.get(addr) servers.append({"slot": name, "addr": addr, "state": state, "container": container["name"] if container else None, - "instance_id": container["hostname"] if container else None}) + "instance_id": container["instance"] if container else None}) return servers diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh index 85bc37a..2e73fe2 100644 --- a/scripts/stop-one.sh +++ b/scripts/stop-one.sh @@ -1,14 +1,17 @@ #!/bin/sh # Failover hook for `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`. -# Stops exactly ONE API replica: the container whose X-Instance-Id (= container hostname, -# see src/messenger/config.py) is in TARGET_INSTANCE_ID. DB, Valkey, LB and volumes are -# not touched. The replica is LEFT STOPPED (`docker stop` = no restart by the policy); -# restore it explicitly afterwards: scripts/restore-api.sh. +# Stops exactly ONE API replica: the container whose X-Instance-Id is TARGET_INSTANCE_ID. +# Lab 7: X-Instance-Id is a random alias (no hostname/IP, src/messenger/config.py); each replica +# writes its alias to /tmp/instance_id inside its own container, which is how the operator maps +# alias -> container. DB, Valkey, LB, OpenBao and volumes are not touched. The replica is LEFT +# STOPPED (`docker stop` = no restart by the policy); restore it explicitly afterwards: +# scripts/restore-api.sh (make restore). # STOP_MODE=stop (default) SIGTERM: readiness 503, 3 s drain, graceful exit (~4 s) # STOP_MODE=kill SIGKILL at once (`docker stop -t 0`): crash of the process # Returns within 10 s. The test hides the output; run by hand to see it (no secrets printed). set -eu cd "$(dirname "$0")/.." +export MSYS_NO_PATHCONV=1 # Git Bash: keep /tmp/instance_id a container path : "${TARGET_INSTANCE_ID:?test provides target API instance alias}" case "$TARGET_INSTANCE_ID" in *[!A-Za-z0-9._-]*) echo "stop-one: invalid TARGET_INSTANCE_ID" >&2; exit 2 ;; @@ -18,7 +21,7 @@ mode="${STOP_MODE:-stop}" target="" # Only RUNNING containers of THIS compose project's service `api` are candidates. for id in $(docker compose ps -q api); do - if [ "$(docker inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then + if [ "$(docker exec "$id" cat /tmp/instance_id 2>/dev/null | tr -d '\r\n')" = "$TARGET_INSTANCE_ID" ]; then target="$id" fi done diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py index 84220c5..a1a7b3a 100644 --- a/src/messenger/__main__.py +++ b/src/messenger/__main__.py @@ -22,7 +22,7 @@ import uvicorn from . import __version__, logging_setup, telemetry, tls from .app import create_app -from .config import ConfigError, Settings +from .config import ConfigError, Settings, publish_instance_id log = logging.getLogger("messenger") @@ -63,6 +63,7 @@ def main() -> int: print(f"configuration error: {exc}", file=sys.stderr) return 2 logging_setup.configure(settings.log_level) + publish_instance_id(settings.instance_id) telemetry.setup("messenger-api", settings.instance_id, __version__) app = create_app(settings) mtls: dict = {} diff --git a/src/messenger/app.py b/src/messenger/app.py index db9c99e..5ad080f 100644 --- a/src/messenger/app.py +++ b/src/messenger/app.py @@ -22,7 +22,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen from opentelemetry import context as otel_context from opentelemetry import trace -from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, tls, validation +from . import attachments, authhdr, cursor, docs, passwords, ratelimit, repo, telemetry, tls, validation from .config import Settings from .db import Database from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable @@ -322,15 +322,36 @@ async def register_user(request: Request) -> JSONResponse: return ok(user.to_json(), 201) +def client_ip(request: Request) -> str: + """Client address for the login rate limit: X-Forwarded-For as SET (overwritten) by HAProxy. + Trusted because only the LB identity can connect to the API (mTLS allowlist, tls.py).""" + forwarded = request.headers.get("x-forwarded-for", "").strip() + if forwarded and len(forwarded) <= 64 and "," not in forwarded: + return forwarded + return request.client.host if request.client else "-" + + async def create_session(request: Request) -> JSONResponse: - """Login: only `Authorization: Basic`; wrong user and wrong password give the same 401.""" + """Login: only `Authorization: Basic`; wrong user and wrong password give the same 401. + Lab 7: failed attempts are limited per username and per client IP (ratelimit.py) -> 429 with + Retry-After, checked BEFORE the Argon2 work.""" username, password = authhdr.parse_basic(request.headers.get("authorization")) await reject_body(request) + limiter: ratelimit.LoginLimiter = request.app.state.login_limiter + ip = client_ip(request) + try: + await limiter.check(username, ip) + except ratelimit.RateLimited as exc: + log.info("login_rate_limited", extra={"fields": {"request_id": request.state.request_id, + "retry_after_s": exc.retry_after}}) + raise found = await repo.get_credentials(db_of(request), username) user, stored_hash = found if found else (None, None) if not await passwords.verify_password(stored_hash, password) or user is None: + await limiter.failed(username, ip) log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}}) raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE) + await limiter.succeeded(username) ttl = request.app.state.settings.session_ttl_seconds token, expires_at = await sessions_of(request).create(user.id, ttl) log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}}) @@ -623,7 +644,8 @@ def create_app(settings: Settings | None = None) -> Starlette: @contextlib.asynccontextmanager async def lifespan(app: Starlette): - passwords.configure(settings.hash_concurrency) + passwords.configure(settings.hash_concurrency, settings.argon2_memory_kib, settings.argon2_iterations, + settings.argon2_parallelism) telemetry.observe_pool(db.pool, db.name) await db.open() await storage.open() @@ -636,6 +658,9 @@ def create_app(settings: Settings | None = None) -> Starlette: "s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version, "upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency, "pending_grace_s": settings.pending_grace_seconds, + "argon2": passwords.parameters(), + "login_limit": {"user": f"{settings.login_user_limit}/{settings.login_user_window_seconds}s", + "ip": f"{settings.login_ip_limit}/{settings.login_ip_window_seconds}s"}, "fault_points": sorted(settings.fault_points)}}) tasks = [asyncio.create_task(purge_loop())] if settings.janitor_interval_seconds > 0: @@ -692,6 +717,7 @@ def create_app(settings: Settings | None = None) -> Starlette: app.state.settings = settings app.state.db = db app.state.sessions = sessions + app.state.login_limiter = ratelimit.LoginLimiter(settings, getattr(sessions, "client", None)) app.state.storage = storage app.state.staging = staging app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency) diff --git a/src/messenger/config.py b/src/messenger/config.py index 6fd0b75..10e471a 100644 --- a/src/messenger/config.py +++ b/src/messenger/config.py @@ -9,7 +9,7 @@ from __future__ import annotations import os import re -import socket +import secrets from dataclasses import dataclass, field from pathlib import Path @@ -21,17 +21,34 @@ class ConfigError(ValueError): INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") -def _instance_id() -> str: - """X-Instance-Id of this process: INSTANCE_ID or the container hostname. +_INSTANCE_ID: str | None = None - Docker sets the hostname of a container to its short container ID, so the value - is unique per replica, stable for the life of the process and maps 1:1 to a real - container (`docker inspect`), which scripts/stop-one.sh relies on. + +def _instance_id() -> str: + """X-Instance-Id of this process (also service.instance.id, lease owner, broker connection name). + + Lab 7 (contract, balancing): a RANDOM alias drawn at process start, e.g. `i-3f9a1c2b7d10` + (48 random bits) - it reveals neither the hostname/container ID nor an IP, is unique per process + and stable for its life. INSTANCE_ID overrides it (tests). The MAIN process of a service writes it + to INSTANCE_ID_FILE (publish_instance_id), so the operator can map alias -> container. """ - value = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname() - if INSTANCE_ID_RE.fullmatch(value) is None: - raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}") - return value + global _INSTANCE_ID + if _INSTANCE_ID is None: + value = os.environ.get("INSTANCE_ID", "").strip() or "i-" + secrets.token_hex(6) + if INSTANCE_ID_RE.fullmatch(value) is None: + raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}") + _INSTANCE_ID = value + return _INSTANCE_ID + + +def publish_instance_id(instance_id: str) -> None: + """Called by the service's main process only (api/relay/worker entry points): writes the alias to + INSTANCE_ID_FILE (compose: /tmp/instance_id inside the container) for + `docker exec cat /tmp/instance_id` (scripts/stop-one.sh, lbctl.py). A helper process + started in the same container (docker compose exec ... python) must not overwrite it.""" + target = os.environ.get("INSTANCE_ID_FILE", "").strip() + if target: + Path(target).write_text(instance_id + "\n", encoding="ascii") def _int(name: str, default: int, low: int, high: int) -> int: @@ -173,6 +190,14 @@ class Settings: tls_ca_file: str = "" tls_client_ca_file: str = "" health_port: int = 0 + # Lab 7: Argon2id parameters (passwords.py) and the login rate limit (ratelimit.py). + argon2_memory_kib: int = 19456 + argon2_iterations: int = 2 + argon2_parallelism: int = 1 + login_user_limit: int = 5 + login_user_window_seconds: int = 60 + login_ip_limit: int = 50 + login_ip_window_seconds: int = 300 def fault_value(self, point: str, default: int = 0) -> int: return self.fault_values.get(point, default) @@ -230,6 +255,16 @@ class Settings: **s3_settings(credentials_required=s3_credentials), **jobs_settings(broker_required=False), **tls_settings(), + # OWASP minimum for Argon2id is m=19 MiB, t=2, p=1: never configurable below it. + argon2_memory_kib=_int("ARGON2_MEMORY_KIB", 19456, 19456, 1024 * 1024), + argon2_iterations=_int("ARGON2_ITERATIONS", 2, 2, 20), + argon2_parallelism=_int("ARGON2_PARALLELISM", 1, 1, 8), + # Failed logins: per username (brute force of one account) and per client IP (spraying + # many accounts), fixed windows in Valkey, shared by all replicas. + login_user_limit=_int("LOGIN_RATE_LIMIT_USER", 5, 1, 1000), + login_user_window_seconds=_int("LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS", 60, 1, 86400), + login_ip_limit=_int("LOGIN_RATE_LIMIT_IP", 50, 1, 100000), + login_ip_window_seconds=_int("LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS", 300, 1, 86400), ) diff --git a/src/messenger/passwords.py b/src/messenger/passwords.py index a1fc35a..573b08e 100644 --- a/src/messenger/passwords.py +++ b/src/messenger/passwords.py @@ -1,28 +1,40 @@ -"""Password hashing with Argon2id (memory-hard password KDF; also mandatory in lab 7). +"""Password hashing with Argon2id (memory-hard password KDF; mandatory in lab 7). -* Parameters follow the OWASP minimum for Argon2id: m=19 MiB, t=2, p=1. Unlike bcrypt - there is no 72-byte limit, so any 12-128 code point UTF-8 password is hashed whole. -* Hashing takes tens of milliseconds of CPU and 19 MiB of RAM. It runs in a worker - thread (argon2-cffi releases the GIL), so the event loop keeps serving other - requests, and a semaphore caps parallel hashes (memory/CPU DoS protection). -* An unknown username is checked against a dummy hash, so "no such user" and - "wrong password" take the same time and return the same 401. +* Parameters: ARGON2_MEMORY_KIB / ARGON2_ITERATIONS / ARGON2_PARALLELISM, never below the OWASP + minimum m=19 MiB, t=2, p=1 (config.py refuses lower values). The values in compose.yaml were + chosen by a measurement on this stand (bench/argon2_bench.py, REPORT.md, evidence/argon2/). +* The stored value is the PHC string `$argon2id$v=19$m=...,t=...,p=...$$`: algorithm, + version, parameters and a random 16-byte salt travel WITH the hash, so verification always uses + the parameters the hash was made with, and a change of parameters does not break old hashes. +* No 72-byte limit (unlike bcrypt): any 12-128 code point UTF-8 password is hashed whole. +* Hashing takes tens of milliseconds of CPU and m KiB of RAM. It runs in a worker thread + (argon2-cffi releases the GIL), so the event loop keeps serving other requests, and a semaphore + caps parallel hashes per replica (PASSWORD_HASH_CONCURRENCY: RAM = concurrency x m). +* An unknown username is checked against a dummy hash, so "no such user" and "wrong password" + take the same time and return the same 401. """ from __future__ import annotations import asyncio -from argon2 import PasswordHasher +from argon2 import PasswordHasher, Type from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError -_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16) +_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16, type=Type.ID) _semaphore: asyncio.Semaphore | None = None _dummy_hash: str | None = None -def configure(concurrency: int) -> None: - global _semaphore +def configure(concurrency: int, memory_kib: int = 19456, iterations: int = 2, parallelism: int = 1) -> None: + global _semaphore, _hasher, _dummy_hash _semaphore = asyncio.Semaphore(concurrency) + _hasher = PasswordHasher(time_cost=iterations, memory_cost=memory_kib, parallelism=parallelism, + hash_len=32, salt_len=16, type=Type.ID) + _dummy_hash = None # re-created with the current parameters (same cost as a real verify) + + +def parameters() -> dict: + return {"memory_kib": _hasher.memory_cost, "iterations": _hasher.time_cost, "parallelism": _hasher.parallelism} async def _run(func, *args): diff --git a/src/messenger/ratelimit.py b/src/messenger/ratelimit.py new file mode 100644 index 0000000..f0517ca --- /dev/null +++ b/src/messenger/ratelimit.py @@ -0,0 +1,116 @@ +"""Lab 7: rate limit of FAILED logins -> 429 rate_limited + Retry-After (POST /api/v1/auth/sessions). + +Two fixed-window counters of failed attempts, kept in Valkey (keys ratelimit:*, the API's ACL +user may touch only these and session:*), so every replica sees the same numbers: + + per username LOGIN_RATE_LIMIT_USER failures / LOGIN_RATE_LIMIT_USER_WINDOW_SECONDS (5 / 60 s): + stops a password guessing attack on ONE account; + per client IP LOGIN_RATE_LIMIT_IP failures / LOGIN_RATE_LIMIT_IP_WINDOW_SECONDS (50 / 300 s): + stops trying one password on MANY accounts from one address. + +Order in the handler: check (no Argon2 work at all while blocked: a blocked attacker costs one +Valkey GET, not 19+ MiB and ~tens of ms of CPU) -> verify the password -> on failure count it, +on success reset the username counter. Retry-After = the remaining TTL of the window, in seconds +(rounded up). A correct password during the block is also 429: otherwise the block would be an +oracle that tells the attacker when the guess was right. + +The client IP comes from X-Forwarded-For, which HAProxy OVERWRITES with the TCP source address +(infra/haproxy/haproxy.cfg). It can be trusted here only because the API accepts connections from +the LB identity alone (mTLS allowlist, tls.py): a client cannot reach the API without the LB. +Keys contain SHA-256 prefixes, not raw usernames/IPs. Valkey unavailable -> 503 (the login cannot +create a session without it anyway). With SESSION_STORE=postgres (no Valkey) the counters live in +the process (per replica) - documented limitation, not the default of the stand. +Known residual risk: anybody can lock a known username for one window (60 s) by failing on purpose. +""" +from __future__ import annotations + +import asyncio +import hashlib +import math +import time +from dataclasses import dataclass + +from redis import exceptions as redis_errors + +from .errors import ApiError, Unavailable + + +class RateLimited(ApiError): + status = 429 + code = "rate_limited" + default_message = "Слишком много неудачных попыток входа, повторите позже" + + def __init__(self, retry_after: int): + super().__init__() + self.retry_after = max(1, retry_after) + + @property + def headers(self) -> dict[str, str]: + return {"Retry-After": str(self.retry_after)} + + +@dataclass(frozen=True) +class Rule: + name: str + limit: int + window_s: int + + +def _digest(value: str) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:32] + + +class LoginLimiter: + def __init__(self, settings, client=None): + self.client = client # redis.asyncio.Redis of the session store, or None + self.timeout = settings.cache_timeout_seconds * 2 + self.rules = (Rule("u", settings.login_user_limit, settings.login_user_window_seconds), + Rule("ip", settings.login_ip_limit, settings.login_ip_window_seconds)) + self._local: dict[str, tuple[int, float]] = {} # fallback without Valkey: key -> (count, until) + + def _keys(self, username: str, ip: str) -> list[tuple[Rule, str]]: + return [(self.rules[0], f"ratelimit:login:u:{_digest(username)}"), + (self.rules[1], f"ratelimit:login:ip:{_digest(ip)}")] + + async def _call(self, coro): + try: + async with asyncio.timeout(self.timeout): + return await coro + except (redis_errors.RedisError, TimeoutError, OSError): + raise Unavailable("Хранилище сессий недоступно") from None + + async def check(self, username: str, ip: str) -> None: + """Raise RateLimited if any window is exhausted.""" + for rule, key in self._keys(username, ip): + if self.client is None: + count, until = self._local.get(key, (0, 0.0)) + ttl_ms = (until - time.monotonic()) * 1000 + if ttl_ms <= 0: + continue + else: + pipe = self.client.pipeline(transaction=True) + pipe.get(key) + pipe.pttl(key) + raw, ttl_ms = await self._call(pipe.execute()) + count = int(raw or 0) + if count >= rule.limit and ttl_ms > 0: + raise RateLimited(math.ceil(ttl_ms / 1000)) + + async def failed(self, username: str, ip: str) -> None: + for rule, key in self._keys(username, ip): + if self.client is None: + count, until = self._local.get(key, (0, 0.0)) + now = time.monotonic() + self._local[key] = (count + 1, until) if until > now else (1, now + rule.window_s) + continue + pipe = self.client.pipeline(transaction=True) + pipe.incr(key) + pipe.pexpire(key, rule.window_s * 1000, nx=True) # the window starts at the FIRST failure + await self._call(pipe.execute()) + + async def succeeded(self, username: str) -> None: + rule, key = self._keys(username, "")[0] + if self.client is None: + self._local.pop(key, None) + else: + await self._call(self.client.delete(key)) diff --git a/src/messenger/relay.py b/src/messenger/relay.py index ec45a0f..388e8dd 100644 --- a/src/messenger/relay.py +++ b/src/messenger/relay.py @@ -32,7 +32,7 @@ import aio_pika from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractExchange from . import __version__, broker, jobs, logging_setup, service, telemetry -from .config import ConfigError, Settings +from .config import ConfigError, Settings, publish_instance_id from .db import Database from .errors import Unavailable @@ -223,6 +223,7 @@ def main() -> int: print(f"configuration error: {exc}", file=sys.stderr) return 2 logging_setup.configure(settings.log_level) + publish_instance_id(settings.instance_id) telemetry.setup("messenger-relay", settings.instance_id, __version__) log.info("relay_starting", extra={"fields": {"instance_id": settings.instance_id, "fault_points": sorted(settings.fault_points)}}) diff --git a/src/messenger/worker.py b/src/messenger/worker.py index 42f4989..6efa19c 100644 --- a/src/messenger/worker.py +++ b/src/messenger/worker.py @@ -42,7 +42,7 @@ import aio_pika from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue from . import __version__, broker, imaging, jobs, logging_setup, service, telemetry -from .config import ConfigError, Settings +from .config import ConfigError, Settings, publish_instance_id from .db import Database from .errors import Unavailable from .imaging import ProcessingError @@ -388,6 +388,7 @@ def main() -> int: print(f"configuration error: {exc}", file=sys.stderr) return 2 logging_setup.configure(settings.log_level) + publish_instance_id(settings.instance_id) telemetry.setup("messenger-worker", settings.instance_id, __version__) log.info("worker_starting", extra={"fields": { "instance_id": settings.instance_id, "concurrency": settings.worker_concurrency, diff --git a/student-tests/test_balancing.py b/student-tests/test_balancing.py index 6ee08bc..98065ea 100644 --- a/student-tests/test_balancing.py +++ b/student-tests/test_balancing.py @@ -29,9 +29,9 @@ def instances_seen(api: Api, token: str, requests: int = 40) -> list[str]: def test_one_session_is_served_by_every_real_replica(api): actor = api.user("rr") seen = instances_seen(api, actor["token"]) - running = {r["hostname"] for r in running_replicas()} + running = {r["instance"] for r in running_replicas()} assert len(running) == REPLICAS >= 2 - assert set(seen) == running, "X-Instance-Id values must be exactly the hostnames of the running containers" + assert set(seen) == running, "X-Instance-Id values must be exactly the aliases of the running containers" # Round robin on ONE keep-alive client connection: consecutive requests switch replicas, # so there is no sticky session hiding split state. switches = sum(1 for a, b in zip(seen, seen[1:]) if a != b) @@ -104,7 +104,7 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position isolate = isolated_from_postgres if how == "pg_hba" else disconnected_from_data_network with isolate(replica): started = time.monotonic() - while replica["hostname"] in lbctl.up_instances(): + while replica["instance"] in lbctl.up_instances(): assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s" time.sleep(0.1) detected = time.monotonic() - started @@ -114,7 +114,7 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position assert probe_inside(replica, "/health/ready") == 503 # ... but not ready assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable" seen = instances_seen(api, actor["token"], 40) - assert replica["hostname"] not in seen and len(seen) == 40 + assert replica["instance"] not in seen and len(seen) == 40 for i in range(20): # writes keep working, only through the ready replicas assert api.register(f"r{i}")["id"] print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s") @@ -195,7 +195,7 @@ def test_graceful_stop_of_each_replica_loses_no_request(api, position): stopped_after = time.monotonic() - started time.sleep(3) after = [e for e in traffic.events if e[0] > time.monotonic() - 2] - assert after and replica["hostname"] not in {e[3] for e in after} + assert after and replica["instance"] not in {e[3] for e in after} time.sleep(1) state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True, check=True).stdout)[0]["State"] @@ -220,7 +220,7 @@ def test_killed_replica_bounded_errors_recovery_and_no_duplicates(api, position) post_ok = [e for e in traffic.events if e[0] > killed_at and e[1] == "POST" and e[2] == 201] assert post_ok and post_ok[0][0] - killed_at <= 10, "writes did not recover within 10 s" late = [e for e in traffic.events if e[0] > killed_at + 3.5] - assert late and replica["hostname"] not in {e[3] for e in late} + assert late and replica["instance"] not in {e[3] for e in late} assert last_failure <= 10 traffic.check_history(api) print(f"{replica['name']}: killed; {len(failures)} failed of {len(traffic.events)}, last failure +{last_failure:.2f} s") @@ -248,11 +248,11 @@ def test_graceful_shutdown_order_in_logs(api): # ------------------------------------------------------------------ discovery: restart and scaling def test_full_restart_lb_rediscovers_all_replicas(api): actor = api.user("restart") - before = {r["hostname"]: r["started_at"] for r in running_replicas()} + before = {r["instance"]: r["started_at"] for r in running_replicas()} run_hook("restart.sh") wait_healthy("postgres", "valkey", "api") wait_stand() - after = {r["hostname"]: r["started_at"] for r in running_replicas()} + after = {r["instance"]: r["started_at"] for r in running_replicas()} assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted" assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed diff --git a/student-tests/test_idempotency.py b/student-tests/test_idempotency.py index a1e2bcc..e704485 100644 --- a/student-tests/test_idempotency.py +++ b/student-tests/test_idempotency.py @@ -273,7 +273,7 @@ def test_replay_after_the_serving_replica_is_stopped(api, pair): key = uuid.uuid4().hex first = api.post_message(alice, chat, {"text": "до остановки"}, key=key) served_by = first.headers["x-instance-id"] - replica = next(r for r in running_replicas() if r["hostname"] == served_by) + replica = next(r for r in running_replicas() if r["instance"] == served_by) with replica_stopped(replica): for _ in range(5): again = Api().post_message(alice, chat, {"text": "до остановки"}, key=key) diff --git a/student-tests/test_pipeline_flow.py b/student-tests/test_pipeline_flow.py index 3d25e4f..8cc7071 100644 --- a/student-tests/test_pipeline_flow.py +++ b/student-tests/test_pipeline_flow.py @@ -20,7 +20,7 @@ import pytest from PIL import Image import imagegen -from conftest import (attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, +from conftest import (lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys, s3_size, service_down, service_with_env, wait_healthy, wait_stand) pytestmark = pytest.mark.stack @@ -359,11 +359,9 @@ def test_bad_message_is_dead_lettered_not_processed(api, pair): # ------------------------------------------------------------------ lease, hung worker, shutdown, concurrency def worker_containers() -> dict[str, str]: - """hostname (= lease_owner) -> container id of every running worker.""" + """instance alias (= lease_owner, lab 7: random, in /tmp/instance_id) -> container id of every running worker.""" ids = compose("ps", "-q", "worker").stdout.split() - out = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, - text=True, check=True).stdout - return dict(line.split() for line in out.splitlines()) + return {lbctl.instance_alias(cid): cid for cid in ids} def test_hung_worker_loses_its_lease_and_cannot_publish(api, pair):