testirovanie-robot/test/login.test.ts

526 lines
25 KiB
TypeScript
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.

import { afterEach, describe, expect, it } from "vitest";
import { loadConfig } from "../src/config.ts";
import { createSessionToken } from "../src/session.ts";
import { hashPassword } from "../src/users.ts";
import { cookieFrom, startApp, type TestApp } from "./helpers.ts";
const INVALID = "Неверный логин или пароль. Проверьте их и попробуйте ещё раз.";
const LOGIN_EMPTY = "Вы не заполнили логин. Введите его и нажмите «Войти».";
const PASSWORD_EMPTY = "Вы не заполнили пароль. Введите его и нажмите «Войти».";
const LOCKED =
"Слишком много попыток, подождите 15 минут. До этого вход закрыт даже с верным паролем.";
const REVIEW_HOST = "testirovanie-robot-staging.telecom.quest";
const PREVIEW_HOST = "testirovanie-robot-pr7.telecom.quest";
const LIVE_HOST = "testirovanie-robot-prod.telecom.quest";
/**
* Настройки приложения, запущенного по адресу `host`, пока владелец не задал логин и пароль.
* Без адреса — запуск у разработчика. Идут через `loadConfig`, чтобы проверялась вся цепочка.
*/
function unconfiguredAt(host: string | undefined) {
const { account } = loadConfig(host ? { APP_HOST: host, NODE_ENV: "production" } : {});
return { account };
}
// Пользователи А и Б из списка; хэши считаются один раз на файл тестов.
const users = [
{ login: "anna", passwordHash: hashPassword("Anna-pass-2026") },
{ login: "boris", passwordHash: hashPassword("boris") },
];
const startWithUsers = () =>
startApp({ users, account: { login: "owner", password: "owner-pass" } });
let app: TestApp;
afterEach(() => app?.close());
/** Значение поля «Логин» на странице. */
const loginFieldValue = (html: string) => /<input id="login"[^>]* value="([^"]*)"/.exec(html)?.[1];
/**
* Сообщение сразу под полем `id` — следующим элементом после него; поле при этом отмечено
* как незаполненное и связано с сообщением.
*/
function messageUnderField(html: string, id: string): string | undefined {
const pattern = new RegExp(
`<input id="${id}"[^>]* aria-invalid="true" aria-describedby="${id}-error"[^>]*>\\s*` +
`<p class="field-error" id="${id}-error">([^<]*)</p>`,
);
return pattern.exec(html)?.[1];
}
describe("Requirement: Страница входа", () => {
it("Scenario: Страница входа открывается", async () => {
app = await startApp();
const response = await app.get("/login");
const html = await response.text();
expect(response.status).toBe(200);
expect(html).toContain("<h1>Вход</h1>");
expect(html).toContain("Введите логин и пароль. После входа откроется главная страница.");
expect(html).toContain('<label for="login">Логин</label>');
expect(html).toContain('<label for="password">Пароль</label>');
expect(html).toMatch(/<input id="password"[^>]* type="password"/);
expect(html).toContain('<button type="submit">Войти</button>');
});
it("Scenario: Вход нажатием Enter", async () => {
app = await startApp();
const html = await (await app.get("/login")).text();
// Оба поля и кнопка отправки лежат в одной форме: Enter в любом поле отправляет её.
const form =
/<form method="post" action="\/login"[^>]*>([\s\S]*?)<\/form>/.exec(html)?.[1] ?? "";
expect(form).toContain('name="login"');
expect(form).toContain('name="password"');
expect(form).toContain('<button type="submit">');
});
});
describe("Requirement: Вход по логину и паролю", () => {
it("Scenario: Успешный вход", async () => {
app = await startApp();
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
const cookie = cookieFrom(response, "session") ?? "";
const home = await app.get("/", { cookie });
expect(await home.text()).toContain("Вы вошли как anna");
});
it("Scenario: Логин набран в другом регистре", async () => {
app = await startApp();
const response = await app.post("/login", { login: " Anna ", password: "s3cret-pass" });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
});
it.each([
["anna", "wrong"],
["boris", "s3cret-pass"],
["anna", "S3CRET-PASS"],
])("Scenario Outline: Неверный логин или пароль (%s / %s)", async (login, password) => {
app = await startApp();
const response = await app.post("/login", { login, password });
const html = await response.text();
expect(response.status).toBe(401);
expect(html).toContain(INVALID);
expect(loginFieldValue(html)).toBe(login);
expect(html).not.toMatch(/<input id="password"[^>]* value=/);
expect(html).not.toContain(password);
expect(cookieFrom(response, "session")).toBeUndefined();
});
it.each([
["", "s3cret-pass", LOGIN_EMPTY, undefined],
["anna", "", undefined, PASSWORD_EMPTY],
["", "", LOGIN_EMPTY, PASSWORD_EMPTY],
])(
"Scenario Outline: Поле не заполнено («%s» / «%s»)",
async (login, password, underLogin, underPassword) => {
app = await startApp();
const response = await app.post("/login", { login, password });
const html = await response.text();
expect(response.status).toBe(400);
expect(messageUnderField(html, "login")).toBe(underLogin);
expect(messageUnderField(html, "password")).toBe(underPassword);
expect(html.match(/class="field-error"/g)).toHaveLength(underLogin && underPassword ? 2 : 1);
expect(loginFieldValue(html)).toBe(login);
expect(html).not.toMatch(/<input id="password"[^>]* value=/);
expect(html).not.toContain("s3cret-pass");
// Над формой сообщения нет: ни общего, ни «Неверный логин или пароль».
expect(html).not.toContain('role="alert"');
expect(html).not.toContain(INVALID);
expect(cookieFrom(response, "session")).toBeUndefined();
},
);
it("Scenario Outline: Поле не заполнено — сообщения под полями есть на казахском и английском", async () => {
app = await startApp();
const kk = await (await app.post("/login?lang=kk", { login: "", password: "" })).text();
expect(messageUnderField(kk, "login")).toBe(
"Сіз логинді толтырмадыңыз. Оны енгізіп, «Кіру» түймесін басыңыз.",
);
expect(messageUnderField(kk, "password")).toBe(
"Сіз құпиясөзді толтырмадыңыз. Оны енгізіп, «Кіру» түймесін басыңыз.",
);
const en = await (await app.post("/login?lang=en", { login: "", password: "" })).text();
expect(messageUnderField(en, "login")).toBe(
"You left the login empty. Enter it and press “Sign in”.",
);
expect(messageUnderField(en, "password")).toBe(
"You left the password empty. Enter it and press “Sign in”.",
);
});
it("на странице входа без ошибок поля не отмечены и сообщений под ними нет", async () => {
app = await startApp();
for (const response of [
await app.get("/login"),
await app.post("/login", { login: "anna", password: "wrong" }),
]) {
const html = await response.text();
expect(html).not.toContain("aria-invalid");
expect(html).not.toContain("field-error");
}
});
it("Scenario: Пустая отправка не считается неверной попыткой", async () => {
app = await startApp();
for (let i = 0; i < 5; i++) {
const response = await app.post("/login", { login: "anna", password: "" });
expect(response.status).toBe(400);
}
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
});
it("форму можно отправить пустой: сообщение показывает страница, а не браузер", async () => {
app = await startApp();
const html = await (await app.get("/login")).text();
expect(html).toContain("novalidate");
expect(html).not.toMatch(/<input[^>]* required/);
});
it("введённый логин показывается без исполнения разметки", async () => {
app = await startApp();
const response = await app.post("/login", { login: '"><script>x</script>', password: "p" });
const html = await response.text();
expect(html).not.toContain("<script>");
expect(html).toContain("&lt;script&gt;");
});
});
describe("Requirement: Страница после входа", () => {
it("Scenario: Страница после входа", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const response = await app.get("/", { cookie });
const html = await response.text();
expect(response.status).toBe(200);
expect(html).toContain("Вы вошли как anna");
expect(html).toContain("Вход выполнен.");
expect(html).toContain('<button type="submit">Выйти</button>');
});
it("Scenario: Вход под А и под Б показывает разные логины", async () => {
app = await startWithUsers();
const first = await app.signIn("anna", "Anna-pass-2026");
const second = await app.signIn("boris", "boris");
const pageA = await (await app.get("/", { cookie: first })).text();
const pageB = await (await app.get("/", { cookie: second })).text();
expect(pageA).toContain("Вы вошли как anna");
expect(pageA).not.toContain("boris");
expect(pageB).toContain("Вы вошли как boris");
expect(pageB).not.toContain("anna");
});
it("Scenario: Вход под Б в том же браузере не показывает А", async () => {
app = await startWithUsers();
const first = await app.signIn("anna", "Anna-pass-2026");
await app.post("/logout", {}, { cookie: first });
const second = await app.signIn("boris", "boris");
const html = await (await app.get("/", { cookie: second })).text();
expect(html).toContain("Вы вошли как boris");
expect(html).not.toContain("anna");
});
it("вход под Б поверх входа А, без выхода, тоже показывает только Б", async () => {
app = await startWithUsers();
const first = await app.signIn("anna", "Anna-pass-2026");
const response = await app.post(
"/login",
{ login: "boris", password: "boris" },
{ cookie: first },
);
const html = await (
await app.get("/", { cookie: cookieFrom(response, "session") ?? "" })
).text();
expect(html).toContain("Вы вошли как boris");
expect(html).not.toContain("anna");
});
it("Scenario: Неудачный вход под Б не меняет вошедшего", async () => {
app = await startWithUsers();
const cookie = await app.signIn("anna", "Anna-pass-2026");
const failed = await app.post("/login", { login: "boris", password: "wrong" }, { cookie });
expect(failed.status).toBe(401);
expect(cookieFrom(failed, "session")).toBeUndefined();
expect(await (await app.get("/", { cookie })).text()).toContain("Вы вошли как anna");
});
it("логин на главной показан текстом, без исполнения разметки", async () => {
const login = '<b>&"x"</b>';
app = await startApp({ account: { login, password: "p" } });
const html = await (await app.get("/", { cookie: await app.signIn(login, "p") })).text();
expect(html).toContain("Вы вошли как &lt;b&gt;&amp;&quot;x&quot;&lt;/b&gt;");
expect(html).not.toContain("<b>");
});
it("Scenario: Страница после входа без входа", async () => {
app = await startApp();
const response = await app.get("/");
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/login");
const body = await response.text();
expect(body).not.toContain("Вы вошли как");
expect(body).not.toContain("Выйти");
});
it("Scenario: Подделанная отметка о входе", async () => {
app = await startApp();
const forged = createSessionToken("admin", Buffer.from("not-the-secret"), Date.UTC(2026, 0, 1));
const cookie = await app.signIn("anna", "s3cret-pass");
const swapped = `session=${forged.split(".")[0]}.${cookie.split(".")[1]}`;
for (const value of [`session=${forged}`, swapped, "session=garbage", "session=a.b"]) {
const response = await app.get("/", { cookie: value });
expect(response.headers.get("location"), value).toBe("/login");
}
});
it("отметка о входе недоступна скриптам и живёт, пока открыт браузер", async () => {
app = await startApp({ cookieSecure: true });
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
const cookie = response.headers.getSetCookie().find((c) => c.startsWith("session=")) ?? "";
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).not.toMatch(/Max-Age|Expires/i);
});
});
describe("Requirement: Страница входа — без подсказки, чем войти", () => {
it.each([
[REVIEW_HOST, "ru", "Пробны"],
[REVIEW_HOST, "kk", "Сынақ"],
[REVIEW_HOST, "en", "Trial"],
[PREVIEW_HOST, "ru", "Пробны"],
[LIVE_HOST, "ru", "Пробны"],
])(
"Scenario Outline: На странице входа нет подсказки с логином и паролем — %s, %s",
async (host, lang, text) => {
app = await startApp(unconfiguredAt(host));
const response = await app.get(`/login?lang=${lang}`);
const html = await response.text();
expect(response.status).toBe(200);
expect(html).toContain('<form method="post" action="/login"');
expect(html.toLowerCase()).not.toContain("demo");
expect(html.toLowerCase()).not.toContain(text.toLowerCase());
expect(html).not.toContain('class="hint"');
// Подсказка не появляется и после ошибки входа.
const failed = await app.post(`/login?lang=${lang}`, { login: "x", password: "wrong" });
expect((await failed.text()).toLowerCase()).not.toContain(text.toLowerCase());
},
);
it("Scenario: Логин и пароль владельца не показаны на странице входа", async () => {
app = await startApp();
const page = await (await app.get("/login")).text();
expect(page).not.toContain("anna");
expect(page).not.toContain("s3cret-pass");
const failed = await (await app.post("/login", { login: "x", password: "wrong" })).text();
expect(failed).not.toContain("anna");
expect(failed).not.toContain("s3cret-pass");
});
it("оформление страницы не содержит стиля подсказки", async () => {
app = await startApp();
expect(await (await app.get("/static/style.css")).text()).not.toContain("hint");
});
});
describe("Requirement: Вход по логину и паролю — общего входа demo нет", () => {
it.each([
["demo", "demo"],
["demo2", "demo2"],
])(
"Scenario Outline: Вход demo не пускает, когда владелец задал логин и пароль — %s",
async (login, password) => {
app = await startApp();
const response = await app.post("/login", { login, password });
const html = await response.text();
expect(response.status).toBe(401);
expect(cookieFrom(response, "session")).toBeUndefined();
expect(html).toContain(INVALID);
expect(loginFieldValue(html)).toBe(login);
expect(html.replace(/<input id="login"[^>]*>/, "")).not.toContain("demo");
},
);
it.each([
[REVIEW_HOST, "demo", "demo"],
[REVIEW_HOST, "demo2", "demo2"],
[PREVIEW_HOST, "demo", "demo"],
[LIVE_HOST, "demo", "demo"],
[undefined, "demo", "demo"],
])(
"Scenario Outline: Вход demo не пускает, когда владелец не задал логин и пароль — %s, %s",
async (host, login, password) => {
app = await startApp({ ...unconfiguredAt(host), users });
const response = await app.post("/login", { login, password });
const html = await response.text();
expect(response.status).toBe(401);
expect(cookieFrom(response, "session")).toBeUndefined();
expect(html).toContain(INVALID);
expect(html.replace(/<input id="login"[^>]*>/, "")).not.toContain("demo");
},
);
it("ответ на demo/demo тот же, что и на любой неверный пароль", async () => {
app = await startApp({ ...unconfiguredAt(REVIEW_HOST), users });
const demo = await app.post("/login", { login: "demo", password: "demo" });
const other = await app.post("/login", { login: "anna", password: "wrong" });
expect(demo.status).toBe(other.status);
const strip = (html: string) => html.replace(/<input id="login"[^>]*>/, "");
expect(strip(await demo.text())).toBe(strip(await other.text()));
});
it("Scenario: После неверного входа demo закрытая страница недоступна", async () => {
app = await startApp({ ...unconfiguredAt(REVIEW_HOST), users });
const failed = await app.post("/login", { login: "demo", password: "demo" });
expect(await failed.text()).toContain(INVALID);
const cookie = cookieFrom(failed, "session") ?? "";
for (const path of ["/", "/reports"]) {
const response = await app.get(path, { cookie });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/login");
const body = await response.text();
expect(body).not.toContain("Вы вошли как");
expect(body).not.toContain("Выйти");
}
});
it("Scenario: Пять неверных входов demo закрывают логин demo, как любой другой", async () => {
app = await startApp(unconfiguredAt(REVIEW_HOST));
for (let i = 0; i < 4; i++) {
const response = await app.post("/login", { login: "demo", password: "demo" });
expect(response.status).toBe(401);
}
const fifth = await app.post("/login", { login: "demo", password: "demo" });
expect(fifth.status).toBe(429);
expect(await fifth.text()).toContain(LOCKED);
});
it("Scenario: Пользователь из списка входит, когда владелец не задал логин и пароль", async () => {
app = await startApp({
...unconfiguredAt(LIVE_HOST),
users: [{ login: "boris", passwordHash: hashPassword("boris-pass") }],
});
const cookie = await app.signIn("boris", "boris-pass");
const html = await (await app.get("/", { cookie })).text();
expect(/<h1>([^<]*)<\/h1>/.exec(html)?.[1]).toBe("Вы вошли как boris");
});
it("Scenario: Настоящий пользователь с логином demo входит как обычный", async () => {
app = await startApp({
...unconfiguredAt(REVIEW_HOST),
users: [{ login: "demo", passwordHash: hashPassword("long-real-pass") }],
});
const refused = await app.post("/login", { login: "demo", password: "demo" });
expect(refused.status).toBe(401);
const cookie = await app.signIn("demo", "long-real-pass");
const html = await (await app.get("/", { cookie })).text();
expect(/<h1>([^<]*)<\/h1>/.exec(html)?.[1]).toBe("Вы вошли как demo");
});
it("Scenario: Без владельца и с пустым списком не входит никто", async () => {
app = await startApp({ ...unconfiguredAt(REVIEW_HOST), users: [] });
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
expect(response.status).toBe(401);
expect(cookieFrom(response, "session")).toBeUndefined();
expect(await response.text()).toContain(INVALID);
});
});
describe("Requirement: Язык экранов", () => {
it.each([
["ru", "Русский", "Войти"],
["kk", "Қазақша", "Кіру"],
["en", "English", "Sign in"],
])("Scenario Outline: Язык выбран в переключателе (%s)", async (code, name, button) => {
app = await startApp();
const start = await app.get("/login", { "accept-language": "de" });
expect(await start.text()).toContain(`<a href="/login?lang=${code}" lang="${code}"`);
const chosen = await app.get(`/login?lang=${code}`);
const html = await chosen.text();
expect(html).toContain(`<button type="submit">${button}</button>`);
expect(html).toContain(`aria-current="true">${name}</a>`);
const cookie = cookieFrom(chosen, "lang");
expect(cookie).toBe(`lang=${code}`);
const again = await app.get("/login", { cookie: cookie ?? "", "accept-language": "de" });
expect(await again.text()).toContain(`<button type="submit">${button}</button>`);
});
it("Scenario: Язык браузера не поддерживается", async () => {
app = await startApp();
const response = await app.get("/login", { "accept-language": "de-DE,de;q=0.9" });
expect(await response.text()).toContain('<button type="submit">Войти</button>');
expect(response.headers.get("content-language")).toBe("ru");
});
it("без выбора в переключателе берётся язык браузера", async () => {
app = await startApp();
const response = await app.get("/login", {
"accept-language": "de;q=0.9,kk-KZ;q=0.8,en;q=0.5",
});
expect(await response.text()).toContain('<button type="submit">Кіру</button>');
});
it("ошибка входа показана на выбранном языке", async () => {
app = await startApp();
const response = await app.post(
"/login",
{ login: "anna", password: "wrong" },
{ cookie: "lang=en" },
);
expect(await response.text()).toContain("Wrong login or password.");
});
});
describe("Requirement: Проверка работоспособности", () => {
it("Scenario: Сервис работает", async () => {
app = await startApp();
const response = await app.get("/healthz");
expect(response.status).toBe(200);
});
it("Scenario: Неизвестный адрес", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const response = await app.get("/no-such-page", { cookie });
expect(response.status).toBe(404);
expect(await response.text()).toContain("Такой страницы нет. Вернитесь на главную.");
});
it("сбой показывает две фразы без подробностей и сообщает об ошибке", async () => {
const errors: unknown[] = [];
app = await startApp({
onError: (error) => errors.push(error),
now: () => {
throw new Error("boom-secret-detail");
},
});
const response = await app.get("/");
const html = await response.text();
expect(response.status).toBe(500);
expect(html).toContain("Что-то пошло не так. Обновите страницу и попробуйте ещё раз.");
expect(html).not.toContain("boom-secret-detail");
expect(errors).toHaveLength(1);
});
it("слишком большая форма отклоняется", async () => {
app = await startApp();
const response = await app.post("/login", { login: "anna", password: "x".repeat(20_000) });
expect(response.status).toBe(413);
});
it("страницы запрещают встраивание и посторонние скрипты", async () => {
app = await startApp();
const response = await app.get("/login");
expect(response.headers.get("content-security-policy")).toContain("default-src 'none'");
expect(response.headers.get("cache-control")).toBe("no-store");
const css = await app.get("/static/style.css");
expect(css.headers.get("content-type")).toContain("text/css");
});
});