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:
2026-11-17 17:52:48 +03:00
co-authored by Claude Opus 5.5
parent 5573973670
commit 13fdd187c6
57 changed files with 4184 additions and 175 deletions
+505 -32
View File
@@ -47,6 +47,7 @@ from pathlib import Path
from typing import Any
import failover
import login
import overload
import plots
import reconcile
@@ -89,6 +90,9 @@ SUPPORTED_PROFILES = (
"uploads_quick",
"queue",
"queue_quick",
# замер входа (change auth-hardening, design, решение 7)
"login",
"login_quick",
)
# PKI прогона: pki.sh stand во временном каталоге вне репозитория, один раз на
# метку до первого стенда; каталог удаляется в finally. Путь запроса — в
@@ -128,6 +132,9 @@ CONTAINER_IMAGE = (
# bench.compose.yml в рабочем каталоге метки
VARIANT_COMPOSE = "variant.compose.yml"
K6 = "mtusi-bench-k6"
# профиль входа: второй генератор — верные входы с другого адреса клиента у
# LB (change auth-hardening, design, решение 7)
K6_GOOD = "mtusi-bench-k6-good"
# профиль сверки (design change track2-reconcile-cost, решения 3 и 8):
# загрузчик объектов на образе стенда, разовые проходы уборщика
# `<префикс><номер>`, override S3 с портом метрик шлюза и override образа
@@ -464,6 +471,41 @@ class Profile:
("UPLOADS__MAX_WAITING", "0"),
)
uploads_sample_interval_s: float = 0.2
# профиль входа (change auth-hardening, design, решение 7): варианты
# (bench/login.py, VARIANTS), commit образа «до» (архив https-tooling:
# HTTPS и mTLS уже есть, защиты входа нет), уровни потока неудачных
# входов в секунду, прогон без потока, окна прогрева и замера, фон лёгких
# запросов и верные входы в секунду, число существующих username потока,
# окружение вариантов (budget — предел входа выключен)
login_variants: tuple[str, ...] = ()
login_before: str = ""
login_rates: tuple[int, ...] = ()
login_baseline: bool = True
login_warmup_s: int = 15
login_window_s: int = 60
login_light_rate: int = 50
login_good_rate: int = 1
login_users: int = 20
login_budget_env: tuple[tuple[str, str], ...] = (
("AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT", "0"),
("AUTH__LOGIN_MAX_FAILURES_PER_ADDRESS", "0"),
)
# отладка и калибровка бюджета (задача 9.3): окружение вариантов кода
# checkout поверх их собственного (`--login-env`, в паспорт — overrides)
login_extra_env: tuple[tuple[str, str], ...] = ()
# итоговые значения [auth] (умолчания settings.py): сверка «Started API»
# вариантов budget и full до окна
login_expected_auth: tuple[tuple[str, Any], ...] = (
("auth_argon2_time_cost", 2),
("auth_argon2_memory_kib", 65536),
("auth_argon2_parallelism", 1),
("auth_kdf_concurrency", 1),
("auth_kdf_max_waiting", 16),
("auth_kdf_wait_timeout_seconds", 2),
("auth_login_window_seconds", 300),
("auth_login_max_failures_per_account", 10),
("auth_login_max_failures_per_address", 200),
)
s3_cpus: str = "1"
s3_memory: str = "512m"
# брокер, relay и worker: лимиты рабочего стенда без swap — у всех профилей
@@ -636,6 +678,10 @@ class Profile:
def is_uploads(self) -> bool:
return bool(self.uploads_variants)
@property
def is_login(self) -> bool:
return bool(self.login_variants)
@property
def is_reconcile(self) -> bool:
return bool(self.reconcile_stages)
@@ -1119,6 +1165,55 @@ PROFILES = {
uploads_sizes=(("10MiB", 3409),),
uploads_clients=(1, 10, 40),
),
# цена дорогого потока входов (change auth-hardening, design, решение 7):
# LB, две реплики, PostgreSQL и Valkey с лимитами рабочего стенда, без S3,
# брокера и телеметрии. Прогон без потока и варианты before / budget /
# full × L ∈ {10, 40}/с × 3 повтора; на прогон — реплики заново и ключи
# предела входа в Valkey удалены. «До» — 56ccb79 (архив https-tooling)
"login": Profile(
name="login",
sizes=(),
concurrency=(),
repeats=3,
read_warmup_s=0,
read_measure_s=0,
write_warmup=0,
write_measure=0,
members=1,
replicas=2,
cpus="1",
memory="512m",
db_cpus="2",
db_memory="1g",
cache_cpus="0.5",
cache_memory="128m",
login_variants=("before", "budget", "full"),
login_before="56ccb79",
login_rates=(10, 40),
),
"login_quick": Profile(
name="login_quick",
sizes=(),
concurrency=(),
repeats=1,
read_warmup_s=0,
read_measure_s=0,
write_warmup=0,
write_measure=0,
members=1,
replicas=2,
cpus="1",
memory="512m",
db_cpus="2",
db_memory="1g",
cache_cpus="0.5",
cache_memory="128m",
login_variants=("before", "budget", "full"),
login_before="56ccb79",
login_rates=(40,),
login_warmup_s=10,
login_window_s=30,
),
# стоимость сверки bucket и БД (трек 2 «5» лабы 4): LB, две реплики,
# хранилища и S3 с лимитами рабочего стенда, разовые проходы уборщика.
# Этапы A (1 MiB), B → C → D (4 KiB, набор растёт), затем отказ по
@@ -2112,7 +2207,7 @@ def leftovers() -> dict[str, list[str]]:
networks = sh("docker", "network", "ls", "--format", "{{.Name}}").split()
extra = [
name
for name in (K6, SAMPLER, FILL, IMAGES, LOOKUP, DU)
for name in (K6, K6_GOOD, SAMPLER, FILL, IMAGES, LOOKUP, DU)
if name in names
]
return {
@@ -2449,35 +2544,38 @@ class Stand:
if self.profile.generator_cpus
else []
)
sh(
"docker",
"run",
"-d",
"--name",
K6,
*limits,
"--network",
NETWORK,
"-v",
f"{ROOT / 'bench' / 'k6'}:/scripts:ro",
"-v",
f"{self.label_dir}:/out",
"-v",
f"{self.work_dir}:/work",
# генератор доверяет только CA PKI прогона: адрес — https://
# ingress:8443 (lib.js), выключателя проверки нет (change
# https-tooling, design, решение 5)
"-v",
f"{Path(PKI_RUN['stand']) / 'ca.crt'}:{K6_CA_FILE}:ro",
"-e",
f"SSL_CERT_FILE={K6_CA_FILE}",
"-e",
f"SSL_CERT_DIR={K6_CA_DIR}",
"--entrypoint",
"sleep",
K6_IMAGE,
"infinity",
)
# профиль входа — ещё второй генератор: другой адрес клиента у LB
generators = [K6, K6_GOOD] if self.profile.is_login else [K6]
for generator in generators:
sh(
"docker",
"run",
"-d",
"--name",
generator,
*limits,
"--network",
NETWORK,
"-v",
f"{ROOT / 'bench' / 'k6'}:/scripts:ro",
"-v",
f"{self.label_dir}:/out",
"-v",
f"{self.work_dir}:/work",
# генератор доверяет только CA PKI прогона: адрес — https://
# ingress:8443 (lib.js), выключателя проверки нет (change
# https-tooling, design, решение 5)
"-v",
f"{Path(PKI_RUN['stand']) / 'ca.crt'}:{K6_CA_FILE}:ro",
"-e",
f"SSL_CERT_FILE={K6_CA_FILE}",
"-e",
f"SSL_CERT_DIR={K6_CA_DIR}",
"--entrypoint",
"sleep",
K6_IMAGE,
"infinity",
)
self.wait_ready()
say(f"{self.profile.replicas} api replicas UP behind haproxy")
@@ -2924,6 +3022,59 @@ class Stand:
self.wait_processes_ready()
self.wait_ready()
def recycle_login(self, image: str, env: dict[str, str]) -> None:
"""Перед прогоном профиля входа (change `auth-hardening`, решение 7):
ключи предела входа в Valkey удалены, реплики — новые контейнеры на
образе варианта с его окружением (пик памяти — прогона), затем
готовность процессов и `UP` в LB."""
sh(
"docker",
"exec",
CACHE,
"sh",
"-c",
'valkey-cli -p "$VALKEY_PORT" --scan --pattern "*:login:*" '
'| xargs -r valkey-cli -p "$VALKEY_PORT" del > /dev/null',
)
self.compose("rm", "-s", "-f", APP_SERVICE, check=False)
sh("docker", "tag", image, APP_IMAGE)
path = self.work_dir / VARIANT_COMPOSE
self.extra_files = []
if env:
lines = ["services:", " api:", " environment:"]
lines += [f' {key}: "{value}"' for key, value in env.items()]
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
self.extra_files = [path]
self.compose(
"up",
"-d",
"--no-deps",
"--no-build",
"--force-recreate",
APP_SERVICE,
)
self.wait_processes_ready()
self.wait_ready()
def cgroup_value(self, name: str, file: str, key: str = "") -> int | None:
"""Число из файла cgroup контейнера (`cpu.stat` по ключу или
`memory.peak`); нет файла — None."""
text = sh(
"docker",
"exec",
name,
"cat",
f"/sys/fs/cgroup/{file}",
check=False,
)
if not key:
return int(text) if text.strip().isdigit() else None
for line in text.splitlines():
field, _, value = line.partition(" ")
if field == key and value.strip().isdigit():
return int(value)
return None
def app_env(self, name: str) -> dict[str, str]:
"""Окружение приложения контейнера без секретов: параметры в
формате настроек (`SECTION__FIELD`), без паролей, секрета и ключа
@@ -3127,6 +3278,7 @@ class Stand:
"-f",
"-v",
K6,
K6_GOOD,
SAMPLER,
RESTORE_DB,
FILL,
@@ -4024,9 +4176,11 @@ class Stand:
script: str,
env: dict[str, Any],
*extra: str,
container: str = K6,
) -> list[str]:
"""Команда `k6 run` сценария в контейнере k6 стенда; `extra` —
дополнительные флаги k6."""
дополнительные флаги k6, `container` — генератор (у профиля входа
их два)."""
common = {
"TEXT_LENGTH": self.profile.text_length,
"PAGE_LIMIT": self.profile.page_limit,
@@ -4039,7 +4193,7 @@ class Stand:
return [
"docker",
"exec",
K6,
container,
"k6",
"run",
"--quiet",
@@ -4082,6 +4236,8 @@ class Stand:
script: str,
env: dict[str, Any],
name: str,
*,
container: str = K6,
) -> subprocess.Popen:
"""Сценарий k6 в фоне; `console.log` k6 пишет сам в файл `name`
рабочего каталога, прочий вывод — в `<name>.out`.
@@ -4102,6 +4258,7 @@ class Stand:
env,
"--console-output",
f"/work/{name}",
container=container,
),
stdout=out,
stderr=subprocess.STDOUT,
@@ -4648,6 +4805,11 @@ class Results:
self.runs.append(row)
self.append("runs.csv", uploads.RUN_FIELDS, row)
def add_login(self, row: dict[str, Any]) -> None:
"""Прогон профиля входа — строка `runs.csv` (`login.RUN_FIELDS`)."""
self.runs.append(row)
self.append("runs.csv", login.RUN_FIELDS, row)
def add_prefill(self, row: dict[str, Any]) -> None:
self.prefill.append(row)
self.append("prefill.csv", PREFILL_FIELDS, row)
@@ -4792,6 +4954,8 @@ class Results:
(self.dir / name).write_text(svg, encoding="utf-8")
elif self.meta["profile"].get("uploads_variants"):
text = uploads.render_summary(self.meta, self.runs)
elif self.meta["profile"].get("login_variants"):
text = login.render_summary(self.meta, self.runs)
elif self.meta["profile"].get("rollout_from"):
text = rollout.render_summary(
self.meta,
@@ -5274,6 +5438,9 @@ class Bench:
if self.profile.is_uploads:
self.run_uploads()
return
if self.profile.is_login:
self.run_login()
return
if self.profile.is_series:
self.run_series()
return
@@ -7219,6 +7386,272 @@ class Bench:
)
self.progress(last={"run": name, "flags": row["flags"]})
# ------------------------------------------------ профиль входа
def login_env(self, variant: str) -> dict[str, str]:
"""Окружение реплик варианта: у `budget` предел входа выключен;
`login_extra_env` (отладка и калибровка бюджета, задача 9.3) — у
вариантов кода checkout."""
p = self.profile
env = dict(p.login_budget_env) if variant == "budget" else {}
if variant != "before":
env.update(dict(p.login_extra_env))
return env
def run_login(self) -> None:
"""Профиль входа (change `auth-hardening`, design, решение 7): образ
«до», план кругами, стенд без S3 и брокера, затем прогоны — на каждый
новые реплики варианта и пустые счётчики предела входа."""
p = self.profile
stand = self.stand
meta = self.results.meta
info: dict[str, Any] = meta.setdefault("login", {})
checkout = meta["app_image"]["id"]
images = {"budget": checkout, "full": checkout}
if "before" in p.login_variants:
self.stage = "before image"
commit = sh(
"git",
"-C",
str(ROOT),
"rev-parse",
"--short",
f"{p.login_before}^{{commit}}",
)
info["before_commit"] = commit
images["before"] = stand.build_from(commit)
self.say(f"login: image of {commit} built")
plan = login.plan_runs(
p.login_variants,
p.login_rates,
p.repeats,
p.order_seed,
baseline=p.login_baseline,
)
info.update(
{
"images": {v: images[v] for v in p.login_variants},
"rates": list(p.login_rates),
"warmup_s": p.login_warmup_s,
"window_s": p.login_window_s,
"light_rate": p.login_light_rate,
"good_rate": p.login_good_rate,
"users": p.login_users,
"env": {v: self.login_env(v) for v in p.login_variants},
"plan": plan,
"app_env": {},
},
)
self.runs_total = len(plan)
self.results.write_meta()
self.stage = "start"
stand.start(lambda text: self.say(f"login: {text}"))
meta["limits"] = stand.limits()
meta["stand"] = stand.passport()
self.results.write_meta()
self.say(f"login: {len(plan)} runs planned")
try:
for run in plan:
self.run_login_one(run, images[run["variant"]])
self.runs_done += 1
finally:
sh("docker", "tag", checkout, APP_IMAGE, check=False)
stand.extra_files = []
def check_login_variant(self, run: dict[str, Any], replica: str) -> None:
"""Вариант применён (спек `load-benchmark`, «Вариант не применён»):
запись «Started API» реплики — поля `auth_*` равны ожидаемым; у
образа «до» этих полей нет. Расхождение — отказ до окна."""
p = self.profile
started = None
for line in sh("docker", "logs", replica).splitlines():
if '"Started API"' in line:
started = json.loads(line)
if started is None:
raise BenchError(f"{run['run']}: no 'Started API' in {replica}")
fields = {k: v for k, v in started.items() if k.startswith("auth_")}
if run["variant"] == "before":
if fields:
raise BenchError(
f"{run['run']}: «before» replica has auth fields "
f"{sorted(fields)}: not the image of {p.login_before}",
)
return
expected = dict(p.login_expected_auth)
for key, value in self.login_env(run["variant"]).items():
field = "auth_" + key.split("__", 1)[1].lower()
if field in expected:
expected[field] = value
for field, value in expected.items():
got = fields.get(field)
if got is None or float(got) != float(value):
raise BenchError(
f"{run['run']}: replica started with {field}={got}, "
f"expected {value}",
)
def run_login_one(self, run: dict[str, Any], image: str) -> None:
"""Прогон: реплики варианта, сверка «Started API», генератор потока
и лёгких запросов, затем верные входы со второго генератора; CPU — по
`cpu.stat` контейнеров на границах окна, пик памяти реплик — их
`memory.peak` (контейнеры нового прогона), хэши — по журналу."""
p = self.profile
stand = self.stand
name = run["run"]
info = self.results.meta["login"]
self.stage = name
self.progress()
stand.recycle_login(image, self.login_env(run["variant"]))
replicas = stand.replicas()
for replica in replicas:
self.check_login_variant(run, replica)
if run["variant"] not in info["app_env"]:
info["app_env"][run["variant"]] = stand.app_env(replicas[0])
self.results.write_meta()
duration = p.login_warmup_s + p.login_window_s
flood_log = f"{name}.flood.k6"
good_log = f"{name}.good.k6"
run_started = time.time()
flood = stand.k6_console(
"login.js",
{
"MODE": "flood",
"DURATION_S": duration,
"LIGHT_RATE": p.login_light_rate,
"FLOOD_RATE": run["rate"],
"USERS": p.login_users,
"SEED": p.seed + run["order"],
"RUN": name,
"NAME": f"{name}-k6",
},
flood_log,
)
good: subprocess.Popen[bytes] | None = None
try:
t0 = self.wait_login_t0(flood, flood_log)
elapsed = time.time() - t0 / 1000
good = stand.k6_console(
"login.js",
{
"MODE": "good",
"DURATION_S": max(1, round(duration - elapsed)),
"GOOD_RATE": p.login_good_rate,
"RUN": name,
"NAME": f"{name}-good",
},
good_log,
container=K6_GOOD,
)
containers = {
**{f"api{i}": r for i, r in enumerate(replicas)},
"lb": LB,
"db": DB,
"cache": CACHE,
}
begin = t0 / 1000 + p.login_warmup_s
end = begin + p.login_window_s
time.sleep(max(0.0, begin - time.time()))
cpu_before = {
key: stand.cgroup_value(c, "cpu.stat", "usage_usec")
for key, c in containers.items()
}
time.sleep(max(0.0, end - time.time()))
cpu_after = {
key: stand.cgroup_value(c, "cpu.stat", "usage_usec")
for key, c in containers.items()
}
for proc, log in ((flood, flood_log), (good, good_log)):
proc.wait(timeout=120)
if proc.returncode != 0:
tail = (stand.work_dir / f"{log}.out").read_text(
encoding="utf-8",
errors="replace",
)[-3000:]
raise BenchError(
f"{name}: k6 login.js failed ({proc.returncode}):\n"
f"{tail}",
)
finally:
for proc in (flood, good):
if proc is not None and proc.poll() is None:
proc.kill()
down = stand.down_storages()
if down:
raise BenchError(f"{name}: storage died: {', '.join(down)}")
def cores(key: str) -> float | None:
a, b = cpu_before.get(key), cpu_after.get(key)
if a is None or b is None:
return None
return round((b - a) / 1e6 / p.login_window_s, 3)
api_cores = [cores(key) for key in containers if key.startswith("api")]
peaks = [
stand.cgroup_value(replica, "memory.peak") for replica in replicas
]
usage = {
"api_cpu_cores": (
round(sum(c for c in api_cores if c is not None), 3)
if all(c is not None for c in api_cores)
else None
),
"api_peak_mib": (
round(max(peaks) / 2**20, 1)
if all(v is not None for v in peaks)
else None
),
"lb_cpu_cores": cores("lb"),
"db_cpu_cores": cores("db"),
"cache_cpu_cores": cores("cache"),
}
hashes = [
login.count_hashes(
stand.logs(replica, run_started),
round(begin * 1000),
round(end * 1000),
)
for replica in replicas
]
text = "\n".join(
(stand.work_dir / log).read_text(
encoding="utf-8",
errors="replace",
)
for log in (flood_log, good_log)
)
_, lines = login.parse_k6(text)
stats = login.window_stats(
lines,
t0,
p.login_warmup_s,
p.login_window_s,
)
row = login.run_row(run, stats, hashes, usage, p.login_window_s)
self.results.add_login(row)
self.say(
f"{name} ({run['order']}/{self.runs_total}): light p95 "
f"{row['light_p95_ms']} ms, flood 401 {row['flood_s401']} 429 "
f"{row['flood_s429']}, good 201 {row['good_s201']}/"
f"{row['good_count']}, hashes {row['hashes']}, api CPU "
f"{row['api_cpu_cores']}, peak {row['api_peak_mib']} MiB",
)
self.progress(last={"run": name, "flags": row["flags"]})
def wait_login_t0(self, proc: subprocess.Popen, log: str) -> int:
"""`login-t0` генератора потока: конец setup() (регистрация
пользователей), начало нагрузки на часах ВМ."""
path = self.stand.work_dir / log
deadline = time.monotonic() + 300
while time.monotonic() < deadline:
if path.exists():
for line in path.read_text(encoding="utf-8").splitlines():
if line.startswith("login-t0,"):
return int(line.split(",")[1])
if proc.poll() is not None:
raise BenchError(f"{log}: k6 exited before setup finished")
time.sleep(0.2)
raise BenchError(f"{log}: no login-t0 in 300 s")
# ------------------------------------------------ профиль очереди
def run_queue(self) -> None:
@@ -9465,6 +9898,11 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
"--variants",
help="цена телеметрии и загрузки, отладка: варианты через запятую",
)
parser.add_argument(
"--login-env",
help="профиль входа, калибровка: KEY=VALUE через запятую — окружение "
"вариантов кода checkout (например AUTH__KDF_CONCURRENCY=2)",
)
parser.add_argument(
"--telemetry",
choices=("on", "off"),
@@ -9591,6 +10029,27 @@ def apply_overrides(
if not profile.is_series:
raise SystemExit(f"--fixed {args.fixed}: track 1 series only")
overrides["fixed_rps"] = tuple(int(x) for x in args.fixed.split(","))
if args.login_env:
if not profile.is_login:
raise SystemExit(f"--login-env {args.login_env}: login profiles")
pairs = tuple(
tuple(item.split("=", 1)) for item in args.login_env.split(",")
)
if any(
len(pair) != 2 or not re.fullmatch(r"AUTH__[A-Z0-9_]+", pair[0])
for pair in pairs
):
raise SystemExit(f"--login-env {args.login_env}: AUTH__*=value")
overrides["login_extra_env"] = pairs
if args.variants and profile.is_login:
names = tuple(args.variants.split(","))
if not names or set(names) - set(login.VARIANTS):
raise SystemExit(
f"--variants {args.variants}: login variants "
f"{', '.join(login.VARIANTS)}",
)
overrides["login_variants"] = names
args.variants = None
if args.variants:
names = tuple(args.variants.split(","))
known = dict(profile.uploads_success_codes)
@@ -9900,6 +10359,17 @@ def run_label(argv: list[str], args: argparse.Namespace) -> int:
if problem:
print(problem, flush=True)
return 2
if profile.is_login and "before" in profile.login_variants:
# commit образа «до» профиля входа — до стенда (change
# auth-hardening, design, решение 7)
problem = rollout_commit_problem(
profile.login_before,
"login_before",
"login «before»",
)
if problem:
print(problem, flush=True)
return 2
if profile.is_reconcile and profile.reconcile_s4_candidates:
# commit образа «до» отказа по пределу — до стенда (решение 7
# design change track2-reconcile-cost)
@@ -9930,6 +10400,9 @@ def run_label(argv: list[str], args: argparse.Namespace) -> int:
# очередь под перегрузкой: трек 1 лабы 5 (design change
# track1-queue-overload, решение 14)
kind = "queue"
if profile.is_login:
# цена потока входов: защита входа лабы 7 (change auth-hardening)
kind = "login"
if profile.is_telemetry_cost:
# цена телеметрии: трек 1 лабы 6 (design change track1-telemetry-cost,
# решение 12)