testirovanie-robot/test/access.test.ts
Peppa 101de37da5
All checks were successful
peppa/lint lint: success за 0с
peppa/typecheck typecheck: success за 0с
peppa/test test: success за 4с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 13s
deploy / deploy (pull_request) Successful in 7s
TR-24: тест входа, выхода и «Назад» на казахском и английском, память проекта
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 12:21:58 +05:00

221 lines
11 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 { createRevocationList, SESSION_TTL_MS } from "../src/session.ts";
import { cookieFrom, startApp, type TestApp } from "./helpers.ts";
let app: TestApp;
afterEach(() => app?.close());
const expectRedirectToLogin = (response: Response) => {
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/login");
};
describe("Requirement: Страница входа", () => {
it("Scenario: Вошедший пользователь открывает страницу входа", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const response = await app.get("/login", { cookie });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
expect(await response.text()).not.toContain("<form");
});
});
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 home = await app.get("/", { cookie: cookieFrom(response, "session") ?? "" });
const html = await home.text();
expect(home.status).toBe(200);
expect(html).toContain("Вы вошли как anna");
expect(html).toContain('<button type="submit">Выйти</button>');
});
it.each([["/"], ["/reports"], ["/no/such/page"], ["/logout"]])(
"Scenario Outline: Закрытый адрес без входа ведёт на страницу входа — %s",
async (path) => {
app = await startApp();
const response = await app.get(path);
expectRedirectToLogin(response);
expect(await response.text()).toBe("");
},
);
it("Scenario: Обновление страницы не сбрасывает вход", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
for (let i = 0; i < 3; i++) {
const response = await app.get("/", { cookie });
expect(response.status).toBe(200);
// Повторные ответы не трогают отметку о входе.
expect(cookieFrom(response, "session")).toBeUndefined();
expect(await response.text()).toContain("Вы вошли как anna");
}
});
it("Scenario: Вход пропадает при закрытии браузера", async () => {
app = await startApp();
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).not.toMatch(/Max-Age|Expires/i);
});
it("страница входа и её оформление открыты без входа", async () => {
app = await startApp();
expect((await app.get("/login")).status).toBe(200);
expect((await app.get("/static/style.css")).status).toBe(200);
});
it("закрытый адрес без входа закрыт для любого способа запроса", async () => {
app = await startApp();
expectRedirectToLogin(await app.post("/reports", {}));
});
});
describe("Requirement: Выход", () => {
it("Scenario: Выход ведёт на страницу входа", async () => {
app = await startApp({ cookieSecure: true });
const cookie = await app.signIn("anna", "s3cret-pass");
const response = await app.post("/logout", {}, { cookie });
expectRedirectToLogin(response);
const cleared = response.headers.getSetCookie().find((c) => c.startsWith("session=")) ?? "";
expect(cleared).toMatch(/^session=;/);
expect(cleared).toContain("Max-Age=0");
// Те же признаки, что при выдаче, иначе браузер не сотрёт отметку.
expect(cleared).toContain("Path=/");
expect(cleared).toContain("Secure");
});
it("Scenario: После выхода прямая ссылка ведёт на страницу входа", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const logout = await app.post("/logout", {}, { cookie });
// Браузер после выхода отправляет то, что осталось от отметки, — пустое значение.
const left = cookieFrom(logout, "session") ?? "";
expect(left).toBe("session=");
expectRedirectToLogin(await app.get("/", { cookie: left }));
expectRedirectToLogin(await app.get("/"));
// Страница входа снова показывает форму, а не перенаправляет на главную.
const login = await app.get("/login", { cookie: left });
expect(login.status).toBe(200);
expect(await login.text()).toContain('<button type="submit">Войти</button>');
});
it("Scenario: Прежняя отметка о входе после выхода не работает", async () => {
app = await startApp();
const copied = await app.signIn("anna", "s3cret-pass");
expect((await app.get("/", { cookie: copied })).status).toBe(200);
await app.post("/logout", {}, { cookie: copied });
expectRedirectToLogin(await app.get("/", { cookie: copied }));
expect((await app.get("/login", { cookie: copied })).status).toBe(200);
});
it("Scenario: Кнопка «Назад» после выхода", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const home = await app.get("/", { cookie });
expect(await home.text()).toContain("<h1>Вы вошли как anna</h1>");
// Браузеру запрещено хранить страницу: по «Назад» он запросит её заново.
expect(home.headers.get("cache-control")).toBe("no-store");
const logout = await app.post("/logout", {}, { cookie });
expect(logout.headers.get("cache-control")).toBe("no-store");
// «Назад»: повторный запрос главной — отметка в браузере стёрта либо осталась прежняя.
const attempts: Record<string, string>[] = [{}, { cookie }];
for (const headers of attempts) {
const back = await app.get("/", headers);
expectRedirectToLogin(back);
expect(back.headers.get("cache-control")).toBe("no-store");
const text = await back.text();
expect(text).not.toContain("Вы вошли как anna");
expect(text).not.toContain("Выйти");
}
});
it.each([
["kk", "Сіз anna ретінде кірдіңіз", "Шығу"],
["en", "You are signed in as anna", "Sign out"],
])("Scenario: Вход, выход и «Назад» на языке %s", async (lang, title, button) => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const home = await (await app.get(`/?lang=${lang}`, { cookie })).text();
expect(home).toContain(`<h1>${title}</h1>`);
expect(home).toContain(`<button type="submit">${button}</button>`);
await app.post("/logout", {}, { cookie });
const attempts: Record<string, string>[] = [{}, { cookie }];
for (const headers of attempts) {
const back = await app.get(`/?lang=${lang}`, headers);
expectRedirectToLogin(back);
expect(await back.text()).not.toContain(title);
}
});
it("Scenario: Выход без входа", async () => {
app = await startApp();
expectRedirectToLogin(await app.post("/logout", {}));
expectRedirectToLogin(await app.post("/logout", {}, { cookie: "session=garbage" }));
});
it("Scenario: Выход одного пользователя не затрагивает другой браузер", async () => {
app = await startApp();
const first = await app.signIn("anna", "s3cret-pass");
const second = await app.signIn("anna", "s3cret-pass");
expect(second).not.toBe(first);
await app.post("/logout", {}, { cookie: first });
expectRedirectToLogin(await app.get("/", { cookie: first }));
const response = await app.get("/", { cookie: second });
expect(response.status).toBe(200);
expect(await response.text()).toContain("Вы вошли как anna");
});
it("выход работает только кнопкой: открытие адреса выхода ссылкой вход не сбрасывает", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const response = await app.get("/logout", { cookie });
expect(response.status).toBe(404);
expect((await app.get("/", { cookie })).status).toBe(200);
});
it("кнопка «Выйти» отправляет форму на адрес выхода", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const html = await (await app.get("/", { cookie })).text();
expect(html).toMatch(
/<form method="post" action="\/logout">\s*<button type="submit">Выйти<\/button>\s*<\/form>/,
);
});
it.each([
["kk", "Шығу"],
["en", "Sign out"],
])("кнопка выхода переведена — %s", async (lang, label) => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const html = await (await app.get(`/?lang=${lang}`, { cookie })).text();
expect(html).toContain(`<button type="submit">${label}</button>`);
});
});
describe("session: отменённые отметки о входе", () => {
it("отменённая отметка считается отменённой, остальные — нет", () => {
const list = createRevocationList();
list.revoke("token-a", 1000);
expect(list.isRevoked("token-a", 1001)).toBe(true);
expect(list.isRevoked("token-b", 1001)).toBe(false);
});
it("запись хранится не дольше срока действия отметки", () => {
const list = createRevocationList();
list.revoke("token-a", 1000);
expect(list.isRevoked("token-a", 1000 + SESSION_TTL_MS - 1)).toBe(true);
expect(list.isRevoked("token-a", 1000 + SESSION_TTL_MS)).toBe(false);
// Следующая отмена вычищает просроченные записи и не ломает новые.
list.revoke("token-b", 1000 + SESSION_TTL_MS);
expect(list.isRevoked("token-a", 1000 + SESSION_TTL_MS)).toBe(false);
expect(list.isRevoked("token-b", 1000 + SESSION_TTL_MS + 1)).toBe(true);
});
});