Перевести пароли на Argon2id и читать секреты через AppRole.

Лимит входа общий для реплик, размер тела ограничен, исходящие клиенты проверяют TLS, если задан CA.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-26 19:40:28 +03:00
co-authored by Cursor
parent 54b4b9e509
commit fb566d874c
19 changed files with 445 additions and 20 deletions
+109
View File
@@ -0,0 +1,109 @@
"""Read runtime secrets from OpenBao with AppRole. The root token is never used."""
from __future__ import annotations
import json
import logging
import ssl
import urllib.error
import urllib.request
from app import config
logger = logging.getLogger("messenger.bao")
_token = ""
_ttl = 0
def _context() -> ssl.SSLContext:
cafile = config.BAO_CACERT or config.TLS_CA_FILE
if not cafile:
raise RuntimeError("OpenBao CA file is not set")
context = ssl.create_default_context(cafile=cafile)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context
def _request(method: str, path: str, body: dict | None = None, token: str = "") -> dict:
data = None if body is None else json.dumps(body).encode("utf-8")
request = urllib.request.Request(
config.BAO_ADDR.rstrip("/") + path,
data=data,
method=method,
)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(request, context=_context(), timeout=5) as response:
raw = response.read()
except urllib.error.HTTPError as exc:
raise RuntimeError("OpenBao request failed with HTTP %s" % exc.code) from None
except urllib.error.URLError:
raise RuntimeError("OpenBao is unreachable or the TLS check failed") from None
if not raw:
return {}
return json.loads(raw.decode("utf-8"))
def _assign(data: dict) -> None:
mapping = {
"database_url": "DATABASE_URL",
"redis_url": "REDIS_URL",
"broker_url": "BROKER_URL",
"s3_access_key_id": "S3_ACCESS_KEY_ID",
"s3_secret_access_key": "S3_SECRET_ACCESS_KEY",
}
for field, attr in mapping.items():
value = data.get(field)
if isinstance(value, str) and value:
setattr(config, attr, value)
def apply() -> None:
"""Login and overlay secrets. No-op when BAO_ADDR is empty (local process without the stand)."""
global _token, _ttl
if not config.BAO_ADDR:
return
if not config.BAO_ROLE_ID or not config.BAO_SECRET_ID:
raise RuntimeError("OpenBao AppRole role_id and secret_id files are required")
login = _request(
"POST",
"/v1/auth/approle/login",
{"role_id": config.BAO_ROLE_ID, "secret_id": config.BAO_SECRET_ID},
)
auth = login.get("auth") or {}
token = auth.get("client_token") or ""
if not token:
raise RuntimeError("OpenBao login did not return a client token")
payload = _request("GET", "/v1/" + config.BAO_SECRET_PATH.strip("/"), token=token)
data = ((payload.get("data") or {}).get("data")) or {}
if not isinstance(data, dict) or not data:
raise RuntimeError("OpenBao secret is empty or the policy denied it")
_assign(data)
_token = token
_ttl = int(auth.get("lease_duration") or 0)
logger.info("loaded OpenBao secret path=%s ttl=%s", config.BAO_SECRET_PATH, _ttl)
def renew_once() -> None:
global _token
if not config.BAO_ADDR or not _token:
return
try:
_request("POST", "/v1/auth/token/renew-self", {}, token=_token)
logger.info("renewed OpenBao token")
except RuntimeError:
logger.warning("OpenBao renew failed; logging in again")
apply()
async def renew_loop() -> None:
import asyncio
while True:
delay = max(30, int(_ttl / 3) if _ttl else 60)
await asyncio.sleep(delay)
await asyncio.to_thread(renew_once)
+3 -2
View File
@@ -8,7 +8,7 @@ import logging
import aio_pika
from app import config, telemetry
from app import config, telemetry, tlsutil
logger = logging.getLogger("messenger.broker")
@@ -32,7 +32,8 @@ async def _ensure() -> tuple[aio_pika.RobustChannel, aio_pika.Exchange]:
return _channel, _exchange
if not config.BROKER_URL:
raise RuntimeError("BROKER_URL is not set")
_connection = await aio_pika.connect_robust(config.BROKER_URL)
ssl_context = tlsutil.server_context() if config.BROKER_URL.startswith("amqps://") else None
_connection = await aio_pika.connect_robust(config.BROKER_URL, ssl_context=ssl_context)
_channel = await _connection.channel(publisher_confirms=True)
_exchange = await _channel.declare_exchange(EXCHANGE, aio_pika.ExchangeType.DIRECT, durable=True)
await _channel.declare_queue(
+18
View File
@@ -61,6 +61,24 @@ OTEL_SERVICE_NAME = _env("OTEL_SERVICE_NAME", "messenger-api")
OTEL_EXPORTER_OTLP_ENDPOINT = _env("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318")
TRACE_SAMPLE_RATIO = float(_env("TRACE_SAMPLE_RATIO", "1"))
SERVICE_VERSION = _env("SERVICE_VERSION", "lab7")
ARGON2_MEMORY_KIB = int(_env("ARGON2_MEMORY_KIB", "19456"))
ARGON2_ITERATIONS = int(_env("ARGON2_ITERATIONS", "2"))
ARGON2_PARALLELISM = int(_env("ARGON2_PARALLELISM", "1"))
LOGIN_RATE_LIMIT = int(_env("LOGIN_RATE_LIMIT", "8"))
LOGIN_IP_RATE_LIMIT = int(_env("LOGIN_IP_RATE_LIMIT", "30"))
LOGIN_RATE_WINDOW_SECONDS = int(_env("LOGIN_RATE_WINDOW_SECONDS", "60"))
MAX_JSON_BYTES = int(_env("MAX_JSON_BYTES", "1048576"))
TLS_CA_FILE = _env("TLS_CA_FILE", "")
TLS_CERT_FILE = _env("TLS_CERT_FILE", "")
TLS_KEY_FILE = _env("TLS_KEY_FILE", "")
MTLS_PORT = int(_env("MTLS_PORT", "8443"))
MTLS_ALLOW_FILE = _env("MTLS_ALLOW_FILE", "")
BAO_ADDR = _env("BAO_ADDR", "")
BAO_CACERT = _env("BAO_CACERT", "")
BAO_ROLE_ID = _file_or_env("BAO_ROLE_ID")
BAO_SECRET_ID = _file_or_env("BAO_SECRET_ID")
BAO_SECRET_PATH = _env("BAO_SECRET_PATH", "secret/data/messenger/api")
BAO_TOKEN_TTL = 0
def lab_mode() -> bool:
+3 -1
View File
@@ -2,7 +2,7 @@ from pathlib import Path
import asyncpg
from app import config
from app import config, tlsutil
from app.errors import AppError
pool: asyncpg.Pool | None = None
@@ -25,12 +25,14 @@ async def connect() -> asyncpg.Pool:
global pool
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL is not set")
ssl_context = tlsutil.server_context() if config.DATABASE_URL.startswith("postgres") and config.TLS_CA_FILE else None
pool = await asyncpg.create_pool(
dsn=config.DATABASE_URL,
min_size=config.DB_POOL_MIN,
max_size=config.DB_POOL_MAX,
command_timeout=config.DB_COMMAND_TIMEOUT,
timeout=config.DB_CONNECT_TIMEOUT,
ssl=ssl_context,
)
return pool
+12 -3
View File
@@ -20,11 +20,18 @@ BEARER_CHALLENGE = 'Bearer realm="messenger"'
class AppError(Exception):
def __init__(self, status: int, message: str, www_authenticate: str | None = None) -> None:
def __init__(
self,
status: int,
message: str,
www_authenticate: str | None = None,
headers: Optional[Dict[str, str]] = None,
) -> None:
super().__init__(message)
self.status = status
self.message = message
self.www_authenticate = www_authenticate
self.headers = headers or {}
def error_response(
@@ -45,5 +52,7 @@ def error_response(
def from_app_error(exc: AppError, request_id: str) -> JSONResponse:
extra = {"WWW-Authenticate": exc.www_authenticate} if exc.www_authenticate else None
return error_response(exc.status, exc.message, request_id, extra)
extra: Dict[str, str] = dict(exc.headers)
if exc.www_authenticate:
extra["WWW-Authenticate"] = exc.www_authenticate
return error_response(exc.status, exc.message, request_id, extra or None)
+4 -1
View File
@@ -11,7 +11,7 @@ from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
from app import attachments, config, db, jobs, rediscli, telemetry
from app import attachments, bao, config, db, jobs, rediscli, telemetry
from app.docs import openapi_json, swagger_ui
from app.errors import AppError, error_response, from_app_error
from app.middleware import RequestContextMiddleware
@@ -69,6 +69,9 @@ def publish_instance_id() -> None:
async def startup() -> None:
publish_instance_id()
logging.getLogger("messenger").info("instance_id=%s", config.INSTANCE_ID)
await asyncio.to_thread(bao.apply)
if config.BAO_ADDR:
asyncio.create_task(bao.renew_loop())
await db.connect()
if config.MIGRATIONS_ON_START:
await db.apply_migrations()
+34 -3
View File
@@ -7,13 +7,21 @@ from starlette.datastructures import MutableHeaders
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from app import telemetry
from app import config, telemetry
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
def _body_limit(path: str, method: str) -> int:
if method in ("GET", "HEAD", "OPTIONS"):
return 1024
if "/attachments" in path or "/uploads" in path:
return config.MAX_UPLOAD_BYTES
return config.MAX_JSON_BYTES
class RequestContextMiddleware:
"""Pure ASGI middleware so upload handlers can read the body stream themselves."""
@@ -33,6 +41,25 @@ class RequestContextMiddleware:
raw_state["request_id"] = request_id
path = scope.get("path", "")
method = scope.get("method", "")
limit = _body_limit(path, method)
content_length = headers.get("content-length")
announced = None
if content_length:
try:
announced = int(content_length)
except ValueError:
announced = limit + 1
received = 0
async def limited_receive() -> Message:
nonlocal received
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > limit:
raise AppError(413, "payload too large")
return message
started = time.perf_counter()
status_code = 500
record = telemetry.observe_http(path)
@@ -66,11 +93,15 @@ class RequestContextMiddleware:
app = scope.get("app")
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
try:
if shutting_down and path not in ("/health/live", "/health/ready"):
if announced is not None and announced > limit:
status_code = 413
response: Response = error_response(413, "payload too large", request_id)
await response(scope, receive, send_wrapper)
elif shutting_down and path not in ("/health/live", "/health/ready"):
response: Response = error_response(503, "service is shutting down", request_id)
await response(scope, receive, send_wrapper)
else:
await self.app(scope, receive, send_wrapper)
await self.app(scope, limited_receive, send_wrapper)
except AppError as exc:
status_code = exc.status
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
+2 -1
View File
@@ -3,10 +3,11 @@ import asyncio
import logging
import sys
from app import config, db
from app import bao, config, db
async def _main() -> None:
await asyncio.to_thread(bao.apply)
if not config.DATABASE_URL:
raise SystemExit("DATABASE_URL is not set")
await db.connect()
+21 -1
View File
@@ -1,7 +1,20 @@
import os
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
hasher = PasswordHasher(time_cost=2, memory_cost=8192, parallelism=1)
# 19 MiB is the lab floor. Salt and parameters live inside the PHC string.
MEMORY_KIB = int(os.environ.get("ARGON2_MEMORY_KIB") or "19456")
ITERATIONS = int(os.environ.get("ARGON2_ITERATIONS") or "2")
PARALLELISM = int(os.environ.get("ARGON2_PARALLELISM") or "1")
hasher = PasswordHasher(
time_cost=ITERATIONS,
memory_cost=MEMORY_KIB,
parallelism=PARALLELISM,
hash_len=32,
salt_len=16,
)
_dummy = None
@@ -21,3 +34,10 @@ def verify_password(password_hash: str, password: str) -> bool:
return hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError, TypeError, ValueError):
return False
def needs_rehash(password_hash: str) -> bool:
try:
return hasher.check_needs_rehash(password_hash)
except (InvalidHashError, TypeError, ValueError):
return False
+36
View File
@@ -0,0 +1,36 @@
import hashlib
from app import config, rediscli
from app.errors import AppError
def _slot(prefix: str, value: str) -> str:
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()
return prefix + digest
async def reserve_login(username: str, ip: str) -> int | None:
"""Count a login attempt on the shared Redis. Returns Retry-After seconds when limited.
Both replicas use the same keys, so the limit is not per process.
The attempt is counted before Argon2 so a flood cannot spend the memory budget.
"""
user_key = _slot("login:u:", username[:128])
ip_key = _slot("login:ip:", ip[:64])
window = config.LOGIN_RATE_WINDOW_SECONDS
try:
redis = rediscli.require()
async with redis.pipeline(transaction=True) as pipe:
pipe.incr(user_key)
pipe.expire(user_key, window, nx=True)
pipe.incr(ip_key)
pipe.expire(ip_key, window, nx=True)
user_count, _, ip_count, _ = await pipe.execute()
if user_count > config.LOGIN_RATE_LIMIT or ip_count > config.LOGIN_IP_RATE_LIMIT:
ttl = int(await redis.ttl(user_key))
return max(ttl, 1)
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
return None
+8
View File
@@ -8,11 +8,19 @@ client: redis.Redis | None = None
async def connect() -> redis.Redis:
global client
tls_kwargs = {}
if config.REDIS_URL.startswith("rediss://"):
tls_kwargs = {
"ssl_ca_certs": config.TLS_CA_FILE or None,
"ssl_cert_reqs": "required",
"ssl_check_hostname": True,
}
client = redis.from_url(
config.REDIS_URL,
socket_connect_timeout=config.REDIS_SOCKET_TIMEOUT,
socket_timeout=config.REDIS_SOCKET_TIMEOUT,
decode_responses=True,
**tls_kwargs,
)
await client.ping()
return client
+21 -1
View File
@@ -10,7 +10,8 @@ from starlette.responses import JSONResponse, Response
from app import attachments, cache, config, db, direct, images, jobs, rediscli, s3, sessions, store
from app.cursor_codec import decode_cursor, encode_cursor
from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, AppError, error_response
from app.passwords import dummy_hash, hash_password, verify_password
from app.passwords import dummy_hash, hash_password, needs_rehash, verify_password
from app.ratelimit import reserve_login
from app.validation import (
parse_json_body,
require_exact_keys,
@@ -87,6 +88,15 @@ async def current_user(request: Request) -> Response:
return _json(user, request.state.request_id)
def _client_ip(request: Request) -> str:
real = request.headers.get("x-real-ip") or ""
if real.strip():
return real.split(",")[0].strip()
if request.client is not None:
return request.client.host
return "unknown"
async def create_session(request: Request) -> Response:
rid = request.state.request_id
header = request.headers.get("Authorization") or ""
@@ -100,10 +110,20 @@ async def create_session(request: Request) -> Response:
username, sep, password = decoded.partition(":")
if not sep:
return error_response(401, "authentication required", rid, {"WWW-Authenticate": BASIC_CHALLENGE})
retry_after = await reserve_login(username, _client_ip(request))
if retry_after is not None:
return error_response(
429,
"too many login attempts",
rid,
{"Retry-After": str(retry_after)},
)
row = await store.get_user_by_username(username)
password_hash = row["password_hash"] if row else dummy_hash()
if row is None or not verify_password(password_hash, password):
return error_response(401, "authentication required", rid, {"WWW-Authenticate": BASIC_CHALLENGE})
if needs_rehash(password_hash):
await store.update_password_hash(row["id"], hash_password(password))
token, expires_at = await sessions.create(row["id"])
return _json(
{
+2 -1
View File
@@ -9,7 +9,7 @@ import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from app import config
from app import config, tlsutil
from app.errors import AppError
logger = logging.getLogger("messenger.s3")
@@ -35,6 +35,7 @@ def _client_or_create():
read_timeout=20,
retries={"max_attempts": 2},
),
verify=tlsutil.https_verify(config.S3_ENDPOINT),
)
return _client
+12 -5
View File
@@ -8,16 +8,23 @@ import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from app import bao, config
def main() -> None:
endpoint = os.environ["S3_ENDPOINT"]
bucket = os.environ["S3_BUCKET"]
bao.apply()
endpoint = os.environ.get("S3_ENDPOINT") or config.S3_ENDPOINT
bucket = os.environ.get("S3_BUCKET") or config.S3_BUCKET
access_key = os.environ.get("S3_ACCESS_KEY_ID") or config.S3_ACCESS_KEY_ID
secret_key = os.environ.get("S3_SECRET_ACCESS_KEY") or config.S3_SECRET_ACCESS_KEY
verify = config.TLS_CA_FILE if endpoint.startswith("https://") and config.TLS_CA_FILE else True
client = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
region_name=os.environ.get("S3_REGION", "us-east-1"),
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=os.environ.get("S3_REGION", config.S3_REGION),
verify=verify,
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 2}),
)
last_error = "not attempted"
+12
View File
@@ -91,6 +91,18 @@ async def get_user(user_id: str) -> Optional[dict]:
return user_dict(row) if row else None
async def update_password_hash(user_id, password_hash: str) -> None:
try:
async with db.require().acquire() as conn:
await conn.execute(
"UPDATE users SET password_hash = $2 WHERE id = $1",
user_id,
password_hash,
)
except Exception:
raise AppError(503, "service unavailable") from None
async def get_user_by_username(username: str):
return await _run(
_fetchrow(
+106
View File
@@ -0,0 +1,106 @@
"""TLS server in front of the local API.
The proxy requires a client certificate from our CA, the LB URI SAN, and a
fingerprint that is still listed in the allow file. Uvicorn stays on 127.0.0.1.
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import ssl
from app import config
logger = logging.getLogger("messenger.tls")
ALLOWED_URI = "spiffe://messenger/lb"
def _allowed_fingerprints() -> set[str]:
path = config.MTLS_ALLOW_FILE
if not path:
return set()
try:
text = open(path, encoding="utf-8").read()
except OSError:
logger.warning("mTLS allow file is not readable")
return set()
return {line.strip().lower() for line in text.splitlines() if line.strip()}
def _identity_ok(ssl_object: ssl.SSLObject) -> bool:
cert = ssl_object.getpeercert()
if not cert:
return False
names = [value for kind, value in cert.get("subjectAltName", ()) if kind == "URI"]
if ALLOWED_URI not in names:
return False
der = ssl_object.getpeercert(binary_form=True)
if not der:
return False
fingerprint = hashlib.sha256(der).hexdigest()
return fingerprint in _allowed_fingerprints()
async def _pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
while True:
chunk = await reader.read(65536)
if not chunk:
break
writer.write(chunk)
await writer.drain()
except Exception:
pass
finally:
try:
writer.close()
await writer.wait_closed()
except Exception:
pass
async def _handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None:
ssl_object = client_writer.get_extra_info("ssl_object")
if ssl_object is None or not _identity_ok(ssl_object):
client_writer.close()
await client_writer.wait_closed()
return
try:
upstream_reader, upstream_writer = await asyncio.open_connection("127.0.0.1", config.PORT)
except Exception:
client_writer.close()
await client_writer.wait_closed()
return
await asyncio.gather(
_pipe(client_reader, upstream_writer),
_pipe(upstream_reader, client_writer),
)
def _context() -> ssl.SSLContext:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(config.TLS_CERT_FILE, config.TLS_KEY_FILE)
context.load_verify_locations(config.TLS_CA_FILE)
context.verify_mode = ssl.CERT_REQUIRED
return context
async def serve() -> None:
if not (config.TLS_CERT_FILE and config.TLS_KEY_FILE and config.TLS_CA_FILE):
raise SystemExit("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CA_FILE are required")
server = await asyncio.start_server(_handle, "0.0.0.0", config.MTLS_PORT, ssl=_context())
logger.info("mTLS proxy listening on %s", config.MTLS_PORT)
async with server:
await server.serve_forever()
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
asyncio.run(serve())
if __name__ == "__main__":
main()
+22
View File
@@ -0,0 +1,22 @@
import ssl
from app import config
def server_context() -> ssl.SSLContext | None:
"""Trust store for outbound TLS. None means the dependency is still plaintext."""
if not config.TLS_CA_FILE:
return None
context = ssl.create_default_context(cafile=config.TLS_CA_FILE)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
if config.TLS_CERT_FILE and config.TLS_KEY_FILE:
context.load_cert_chain(config.TLS_CERT_FILE, config.TLS_KEY_FILE)
return context
def https_verify(endpoint: str):
if endpoint.startswith("https://") and config.TLS_CA_FILE:
return config.TLS_CA_FILE
return True
+4 -1
View File
@@ -9,7 +9,7 @@ from uuid import UUID
import aio_pika
from app import broker, config, db, jobs, telemetry
from app import bao, broker, config, db, jobs, telemetry
from app.broker import payload_from
logger = logging.getLogger("messenger.worker")
@@ -80,6 +80,9 @@ async def _reap_loop(stop: asyncio.Event) -> None:
async def serve() -> None:
await asyncio.to_thread(bao.apply)
if config.BAO_ADDR:
asyncio.create_task(bao.renew_loop())
await db.connect()
stop = asyncio.Event()
loop = asyncio.get_running_loop()