forked from mtusi2026/mtusi2026lab7
lab7: Argon2id из env (замер bench/argon2_bench.py), лимит неудачных входов в Valkey (429 + Retry-After), cap_drop ALL и no-new-privileges, X-Instance-Id = случайный alias
This commit is contained in:
@@ -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 = {}
|
||||
|
||||
+29
-3
@@ -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)
|
||||
|
||||
+45
-10
@@ -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 <container> 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),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+24
-12
@@ -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=...$<salt>$<hash>`: 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):
|
||||
|
||||
@@ -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))
|
||||
@@ -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)}})
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user