peppa/packages/testkit/test/health-anon.test.ts
peppa-bot ce03df667c
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 55с
peppa/build build: success за 35с
peppa/test test: failure за 1720с
peppa-ci / ci (pull_request) Failing after 31m5s
PEP-272: /api/health анониму — только ok; без X-Powered-By, script-src в CSP, аватар по https
- /api/health без ключа X-Peppa-Health (HMAC от PEPPA_SECRET, принимается и PREVIOUS) отдаёт только {ok};
  ключ шлют сторож адреса, сторож отставания выкатки, healthcheck контейнеров, скрипты выкатки
- poweredByHeader: false; CSP: script-src 'self' 'unsafe-inline' (unsafe-eval только в dev), worker-src 'self'
- httpsAvatar: http → https при записи и показе
- тест health-anon.test.ts, change archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 20:36:06 +00:00

106 lines
5.2 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.

// PEP-272: служебные данные — не анониму. /api/health без ключа отдаёт только {ok}; ключ (HMAC от
// PEPPA_SECRET) шлют внутренние проверки; без X-Powered-By, скрипты в CSP — только свои, аватар — https.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createServer, type Server } from "node:http";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { core, db, runner, teardown } from "./helpers.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
process.env.PEPPA_SECRET = "mock-health-secret";
const full = { ok: true, version: "0.15.0", commit: "abc1234", db: { ok: true, latencyMs: 1 }, services: [{ service: "web", ok: true }], boot: "abc1234-x" };
after(teardown);
describe("PEP-272: /api/health для анонима", () => {
test("Аноним видит только «ok»", () => {
assert.deepEqual(core.healthBody(full, null), { ok: true });
assert.deepEqual(core.healthBody({ ...full, ok: false }, undefined), { ok: false });
});
test("Неверный ключ — как аноним", () => {
assert.deepEqual(core.healthBody(full, "abc"), { ok: true });
assert.deepEqual(core.healthBody(full, core.healthToken()!.slice(0, 63) + "0"), { ok: true });
});
test("Всё работает: внутренняя проверка с ключом видит сводку", () => {
const key = core.healthHeaders()[core.HEALTH_HEADER];
assert.ok(key);
assert.deepEqual(core.healthBody(full, key), full);
});
test("Ротация: ключ от PEPPA_SECRET_PREVIOUS тоже принимается", () => {
const old = core.healthToken()!;
process.env.PEPPA_SECRET_PREVIOUS = process.env.PEPPA_SECRET;
process.env.PEPPA_SECRET = "mock-health-secret-new";
try {
assert.ok(core.healthTokenOk(old));
assert.ok(core.healthTokenOk(core.healthToken()));
} finally {
process.env.PEPPA_SECRET = "mock-health-secret";
delete process.env.PEPPA_SECRET_PREVIOUS;
}
});
test("Ключ shell-скриптов выкатки совпадает с ключом ядра", () => {
const sh = execFileSync("bash", ["-c", `. "${ROOT}/scripts/lib/health-token.sh"; health_token`], { encoding: "utf8", env: { ...process.env } }).trim();
assert.equal(sh, core.healthToken());
});
describe("сторож адреса шлёт ключ", () => {
let server: Server;
before(async () => {
server = createServer((req, res) => {
const body = core.healthBody(full, req.headers[core.HEALTH_HEADER] as string | undefined);
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(body));
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
process.env.PEPPA_PUBLIC_HEALTH_URL = `http://127.0.0.1:${(server.address() as { port: number }).port}/api/health`;
});
after(() => {
delete process.env.PEPPA_PUBLIC_HEALTH_URL;
server.close();
});
test("публичный адрес с полной сводкой узнан как FORGE", async () => {
assert.equal(await runner.publicHealthTick(db), true);
});
});
});
describe("PEP-272: ответы веба не раскрывают служебное", () => {
test("Заголовки страницы: без X-Powered-By, script-src только свои", async () => {
const prev = process.env.NODE_ENV;
(process.env as Record<string, string>).NODE_ENV = "production";
try {
const config = ((await import(new URL("../../../apps/web/next.config.ts", import.meta.url).href)) as { default: { poweredByHeader?: boolean; headers: () => Promise<{ source: string; headers: { key: string; value: string }[] }[]> } }).default;
assert.equal(config.poweredByHeader, false);
const all = (await config.headers()).find((h) => h.source === "/:path*")!;
const csp = all.headers.find((h) => h.key === "Content-Security-Policy")!.value;
assert.match(csp, /script-src 'self' 'unsafe-inline'(;|$)/);
assert.doesNotMatch(csp, /unsafe-eval/);
assert.match(csp, /worker-src 'self'/);
assert.match(csp, /frame-ancestors 'none'/);
} finally {
(process.env as Record<string, string | undefined>).NODE_ENV = prev;
}
});
for (const [url, shown] of [
["http://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"],
["https://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"],
["javascript:alert(1)", null],
["", null],
] as const) {
test(`Адрес аватара: ${url || "пусто"} → ${shown ?? "нет картинки"}`, () => {
assert.equal(core.httpsAvatar(url), shown);
});
}
test("Аватар Gitea по http сохраняется как https", async () => {
const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.telecom.quest/avatars/7" }, { access_token: "x" });
assert.equal(u.avatarUrl, "https://git.telecom.quest/avatars/7");
});
});