forked from mtusi2026/mtusi2026lab7
feat: harden authentication (Argon2id by measurement, login limits, body limit)
Apply auth-hardening up to the bench_login label: Argon2id parameters from [auth] chosen by driver.py argon2-params (m=64 MiB, t=2, p=1), rehash on login, per-process KDF budget with 429, shared login failure limit in Valkey with a local fallback, X-Forwarded-For from HAProxy, 64 KiB body limit (400) in LB and middleware, bench login profile, tests, threat model and trust matrix rows. Hypotheses H1-H4 are committed here before the baseline label. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ from .clients import (
|
||||
FakeCache,
|
||||
FakeImageRenderer,
|
||||
FakeJobPublisher,
|
||||
FakeLoginLimiter,
|
||||
FakeObjectStorage,
|
||||
FakeStoredObject,
|
||||
)
|
||||
@@ -37,6 +38,7 @@ __all__ = [
|
||||
"FakeIdempotencyRepository",
|
||||
"FakeImageRenderer",
|
||||
"FakeJobPublisher",
|
||||
"FakeLoginLimiter",
|
||||
"FakeMessageRepository",
|
||||
"FakeObjectStorage",
|
||||
"FakeSessionRepository",
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
и издателя виден рядом с блоками.
|
||||
"""
|
||||
|
||||
import math
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -13,12 +15,19 @@ from typing import BinaryIO
|
||||
from uuid import UUID
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.ports.login_limit import AbstractLoginLimiter
|
||||
from src.infra import login_limit
|
||||
from src.infra.s3 import (
|
||||
StorageStats,
|
||||
StoredObjectInfo,
|
||||
StoredObjectPage,
|
||||
)
|
||||
from src.schemas.dataclasses import JobPublicationDTO, RenderedVariantsDTO
|
||||
from src.schemas.dataclasses import (
|
||||
JobPublicationDTO,
|
||||
LoginAttemptDTO,
|
||||
RenderedVariantsDTO,
|
||||
)
|
||||
from src.schemas.enums import LoginOutcome
|
||||
|
||||
from .database import FakeDatabase
|
||||
|
||||
@@ -39,6 +48,7 @@ class FakeCache:
|
||||
self.namespace = namespace
|
||||
self._db = database
|
||||
self.values: dict[str, str] = {}
|
||||
self.expires: dict[str, float] = {}
|
||||
self.failing = False
|
||||
|
||||
async def get(self, key: str) -> str | None:
|
||||
@@ -52,10 +62,88 @@ class FakeCache:
|
||||
self.values[key] = value
|
||||
return True
|
||||
|
||||
async def run_script(
|
||||
self,
|
||||
script: str,
|
||||
*,
|
||||
keys: Sequence[str],
|
||||
args: Sequence[str | int],
|
||||
) -> object | None:
|
||||
"""Сценарии предела входа (`src/infra/login_limit.py`) на словаре
|
||||
фейка: тот же результат, что Lua на Valkey; срок ключа — по
|
||||
monotonic-часам (`expires`)."""
|
||||
self._db.events.append("cache.script")
|
||||
if self.failing:
|
||||
return None
|
||||
now = time.monotonic()
|
||||
for key in [key for key in keys if self._expired(key, now)]:
|
||||
self.values.pop(key, None)
|
||||
self.expires.pop(key, None)
|
||||
if script == login_limit.ACQUIRE_SCRIPT:
|
||||
window = int(args[0])
|
||||
wait = 0
|
||||
for key, limit in zip(keys, args[1:], strict=True):
|
||||
if int(self.values.get(key, "0")) >= int(limit):
|
||||
ttl = math.ceil(self.expires[key] - now)
|
||||
wait = max(wait, ttl, 1)
|
||||
if wait:
|
||||
return wait
|
||||
for key in keys:
|
||||
self.values[key] = str(int(self.values.get(key, "0")) + 1)
|
||||
self.expires.setdefault(key, now + window)
|
||||
return 0
|
||||
if script == login_limit.SETTLE_SCRIPT:
|
||||
for key, mode in zip(keys, args, strict=True):
|
||||
if mode == "del":
|
||||
self.values.pop(key, None)
|
||||
self.expires.pop(key, None)
|
||||
elif int(self.values.get(key, "0")) > 0:
|
||||
self.values[key] = str(int(self.values[key]) - 1)
|
||||
return 1
|
||||
raise NotImplementedError(script)
|
||||
|
||||
def _expired(self, key: str, now: float) -> bool:
|
||||
expires = self.expires.get(key)
|
||||
return expires is not None and expires <= now
|
||||
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class FakeLoginLimiter(AbstractLoginLimiter):
|
||||
"""Предел входа фейка: `blocked` — `acquire` отказывает с этим
|
||||
остатком окна; исходы — в `settled` и журнале базы."""
|
||||
|
||||
def __init__(self, database: FakeDatabase) -> None:
|
||||
self._db = database
|
||||
self.blocked: int | None = None
|
||||
self.settled: list[LoginOutcome] = []
|
||||
|
||||
async def acquire(
|
||||
self,
|
||||
*,
|
||||
username: str, # noqa: ARG002
|
||||
address: str, # noqa: ARG002
|
||||
) -> LoginAttemptDTO:
|
||||
self._db.events.append("limiter.acquire")
|
||||
if self.blocked is not None:
|
||||
return LoginAttemptDTO(
|
||||
allowed=False,
|
||||
retry_after_seconds=self.blocked,
|
||||
)
|
||||
return LoginAttemptDTO(allowed=True, keys=("pair", "address"))
|
||||
|
||||
async def settle(
|
||||
self,
|
||||
*,
|
||||
attempt: LoginAttemptDTO,
|
||||
outcome: LoginOutcome,
|
||||
) -> None:
|
||||
if attempt.allowed:
|
||||
self._db.events.append(f"limiter.settle.{outcome.value}")
|
||||
self.settled.append(outcome)
|
||||
|
||||
|
||||
class FakeStoredObject:
|
||||
def __init__(self, info: StoredObjectInfo, data: bytes, storage) -> None:
|
||||
self.info = info
|
||||
|
||||
Reference in New Issue
Block a user