Files
mtusi2026lab7-safronov/bench/k6/login.js
T
ricoromaandClaude Opus 5.5 13fdd187c6 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>
2026-11-17 17:52:48 +03:00

190 lines
6.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Профиль входа (change auth-hardening, design, решение 7): цена дорогого
// потока входов через LB. MODE=flood — основной контейнер k6: фон лёгких
// запросов (GET /users/me и страница истории по очереди, LIGHT_RATE в
// секунду, токен заранее) и поток неудачных входов FLOOD_RATE в секунду —
// половина по существующим username, половина по неизвестным. MODE=good —
// второй контейнер k6 (другой адрес клиента у LB): верные входы GOOD_RATE в
// секунду. Открытая модель (constant-arrival-rate, VU заранее), ответ не
// повторяется. Строки в файл консоли:
// login-t0,<мс> начало нагрузки (часы ВМ), MODE=flood
// l,<отправка мс>,<мс>,<статус>,<вид me|history>
// f,<отправка мс>,<мс>,<статус>,<Retry-After|->,<X-Instance-Id|->,<1|0>
// g,<отправка мс>,<мс>,<статус>,<Retry-After|->,<X-Instance-Id|->
// Пароли — только в памяти setup(): в файлы и итог не попадают.
import encoding from "k6/encoding";
import http from "k6/http";
import { check, fail } from "k6";
import {
API,
SUMMARY_THRESHOLDS,
SUMMARY_TREND_STATS,
authHeaders,
createChat,
mulberry32,
sendMessage,
summaryFiles,
} from "./lib.js";
const MODE = __ENV.MODE || "flood";
const DURATION_S = Number(__ENV.DURATION_S || 75);
const LIGHT_RATE = Number(__ENV.LIGHT_RATE || 50);
const FLOOD_RATE = Number(__ENV.FLOOD_RATE || 0);
const GOOD_RATE = Number(__ENV.GOOD_RATE || 1);
const USERS = Number(__ENV.USERS || 20);
const SEED = Number(__ENV.SEED || 1);
const RUN = __ENV.RUN || "run";
// больше timeout server LB (10 с): клиент видит ответ LB
const TIMEOUT = "15s";
function rate(value, preVus, maxVus) {
return {
executor: "constant-arrival-rate",
rate: value,
timeUnit: "1s",
duration: `${DURATION_S}s`,
preAllocatedVUs: preVus,
maxVUs: maxVus,
gracefulStop: "20s",
};
}
const scenarios = {};
if (MODE === "flood") {
scenarios.light = { ...rate(LIGHT_RATE, 50, 200), exec: "light" };
if (FLOOD_RATE > 0) {
scenarios.flood = { ...rate(FLOOD_RATE, 100, 400), exec: "flood" };
}
} else {
scenarios.good = { ...rate(GOOD_RATE, 5, 20), exec: "good" };
}
export const options = {
scenarios,
summaryTrendStats: SUMMARY_TREND_STATS,
thresholds: SUMMARY_THRESHOLDS,
setupTimeout: "300s",
};
function password() {
return `${crypto.randomUUID()}-${crypto.randomUUID()}`;
}
function registerUser(username, secret) {
const res = http.post(
`${API}/users`,
JSON.stringify({ username, display_name: "Bench", password: secret }),
{ headers: { "Content-Type": "application/json" } },
);
if (!check(res, { "register 201": (r) => r.status === 201 })) {
fail(`register: ${res.status}`);
}
return res.json("id");
}
function basic(username, secret) {
return `Basic ${encoding.b64encode(`${username}:${secret}`)}`;
}
function login(username, secret) {
return http.post(`${API}/auth/sessions`, null, {
headers: { Authorization: basic(username, secret) },
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(201),
});
}
export function setup() {
const tag = `${RUN.replace(/[^a-z0-9]/g, "").slice(-12)}${MODE[0]}`;
if (MODE === "good") {
const username = `lg_${tag}`.slice(0, 32);
const secret = password();
registerUser(username, secret);
return { username, secret };
}
const usernames = [];
for (let i = 0; i < USERS; i += 1) {
const username = `lf_${tag}_${i}`.slice(0, 32);
registerUser(username, password());
usernames.push(username);
}
const readerName = `lr_${tag}`.slice(0, 32);
const readerSecret = password();
const readerId = registerUser(readerName, readerSecret);
const session = login(readerName, readerSecret);
if (session.status !== 201) {
fail(`reader login: ${session.status}`);
}
const token = session.json("token");
const chatId = createChat(token, "login bench", [readerId]);
for (let i = 0; i < 20; i += 1) {
sendMessage(chatId, token, `login-bench-${i}`);
}
const t0 = Date.now();
console.log(`login-t0,${t0}`);
return { usernames, token, chatId, tag };
}
function header(res, name) {
return res.headers[name] || "-";
}
function elapsed(start, res) {
const t = res.timings;
const measured = t.blocked + t.connecting + t.tls_handshaking + t.duration;
return Math.max(
0,
Math.round(res.status === 0 ? Date.now() - start : measured),
);
}
let lightTurn = 0;
export function light(data) {
lightTurn += 1;
const kind = lightTurn % 2 === 0 ? "me" : "history";
const url =
kind === "me"
? `${API}/users/me`
: `${API}/chats/${data.chatId}/messages?limit=20`;
const start = Date.now();
const res = http.get(url, {
headers: authHeaders(data.token),
timeout: TIMEOUT,
responseType: "none",
});
console.log(`l,${start},${elapsed(start, res)},${res.status},${kind}`);
}
let random = null;
export function flood(data) {
if (random === null) {
random = mulberry32(SEED + __VU);
}
const known = random() < 0.5;
const username = known
? data.usernames[Math.floor(random() * data.usernames.length)]
: `lu_${data.tag}_${Math.floor(random() * 1e9)}`.slice(0, 32);
const start = Date.now();
const res = login(username, password());
console.log(
`f,${start},${elapsed(start, res)},${res.status},` +
`${header(res, "Retry-After")},${header(res, "X-Instance-Id")},` +
`${known ? 1 : 0}`,
);
}
export function good(data) {
const start = Date.now();
const res = login(data.username, data.secret);
console.log(
`g,${start},${elapsed(start, res)},${res.status},` +
`${header(res, "Retry-After")},${header(res, "X-Instance-Id")}`,
);
}
export function handleSummary(data) {
return summaryFiles(data);
}