peppa/packages/testkit/test/stale-actions.test.ts

185 lines
12 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-324: after a deploy the buttons of a page opened before it stopped working — the server-action
// ids are salted with Next's actions key, and the platform image got a random key on every build.
// Bugsink #23: «UnrecognizedActionError: Server Action "406e…" was not found on the server».
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, test } from "node:test";
import { PLATFORM_SECRETS } from "@peppa/core";
const path = (p: string) => new URL(`../../../${p}`, import.meta.url).pathname;
const read = (p: string) => readFileSync(path(p), "utf8");
const lib = (await import(new URL("../../../apps/web/lib/stale-action.ts", import.meta.url).href)) as typeof import("../../../apps/web/lib/stale-action.ts");
const KEY_LINE = /^NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=([A-Za-z0-9+/]{43}=)$/m;
/** Runs ensure_actions_key from scripts/lib/actions-key.sh against an .env file. */
function ensureKey(envFile: string) {
return execFileSync("bash", ["-c", `. "$1"; ensure_actions_key "$2" && printf '%s' "$NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"`, "x", path("scripts/lib/actions-key.sh"), envFile], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
}
describe("PEP-324: постоянный ключ действий в сборке образа", () => {
test("Сценарий: выкатка передаёт ключ в сборку секретом, а не аргументом", () => {
const deploy = read("scripts/platform-deploy.sh");
execFileSync("bash", ["-n", path("scripts/platform-deploy.sh")]);
const build = deploy.split("\n").find((l) => l.startsWith("run docker build"))!;
assert.match(build, /--secret id=next_actions_key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY/);
assert.doesNotMatch(build, /--build-arg[ =]"?NEXT_SERVER_ACTIONS/, "a build-arg would show in docker history");
const ensure = deploy.indexOf("run ensure_actions_key");
assert.ok(ensure > 0 && ensure < deploy.indexOf("run docker build"), "the key exists before the build");
});
test("Сценарий: next build в образе читает ключ из секрета BuildKit", () => {
const dockerfile = read("infra/platform/Dockerfile");
const stage = dockerfile.slice(0, dockerfile.lastIndexOf("\nFROM "));
const run = stage.slice(stage.indexOf("RUN --mount=type=secret,id=next_actions_key"));
assert.ok(stage.includes("RUN --mount=type=secret,id=next_actions_key"), "the build step mounts the secret");
const cmd = run.slice(0, run.indexOf("./node_modules/.bin/next build") + "./node_modules/.bin/next build".length).replace(/\\\n/g, " ").replace(/^RUN --mount=\S+ /, "");
// Run the very shell of the step with the secret file, install and next swapped for stubs.
const dir = mkdtempSync(join(tmpdir(), "pep324-"));
execFileSync("mkdir", ["-p", join(dir, "apps/web/node_modules/.bin")]);
const next = join(dir, "apps/web/node_modules/.bin/next");
writeFileSync(next, '#!/bin/sh\nprintf "key=%s" "$NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"\n');
chmodSync(next, 0o755);
const shell = (secret: string | null) => {
const file = join(dir, "secret");
if (secret !== null) writeFileSync(file, secret);
else execFileSync("rm", ["-f", file]);
const script = cmd.replace("pnpm install --frozen-lockfile", "true").replaceAll("/run/secrets/next_actions_key", file);
return execFileSync("sh", ["-c", script], { cwd: dir, encoding: "utf8", env: { PATH: process.env.PATH! } });
};
assert.match(shell("AAAAkeyAAAA"), /key=AAAAkeyAAAA$/);
// Without the secret (a hand-made local image) the build still goes, with a random key as before.
assert.match(shell(null), /key=$/);
});
test("Сценарий: ключа ещё нет — выкатка создаёт его один раз и не печатает", () => {
const dir = mkdtempSync(join(tmpdir(), "pep324-env-"));
const env = join(dir, ".env");
writeFileSync(env, "PEPPA_SECRET=x"); // no trailing newline
const out = execFileSync("bash", ["-c", `. "$1"; ensure_actions_key "$2" 2>&1`, "x", path("scripts/lib/actions-key.sh"), env], { encoding: "utf8" });
const text = readFileSync(env, "utf8");
const key = text.match(KEY_LINE)?.[1];
assert.ok(key, `a 44-char key line appears:\n${text}`);
assert.match(text, /^PEPPA_SECRET=x\n/, "the old line stays intact");
assert.ok(!out.includes(key!), "the value is not in the log");
// The second deploy keeps it and exports the same value.
assert.equal(ensureKey(env), key);
assert.equal(readFileSync(env, "utf8"), text);
});
test("Сценарий: ключ уже есть — строка не меняется", () => {
const dir = mkdtempSync(join(tmpdir(), "pep324-env-"));
const env = join(dir, ".env");
writeFileSync(env, "A=1\nNEXT_SERVER_ACTIONS_ENCRYPTION_KEY=abc\n");
assert.equal(ensureKey(env), "abc");
assert.equal(readFileSync(env, "utf8"), "A=1\nNEXT_SERVER_ACTIONS_ENCRYPTION_KEY=abc\n");
});
test("Сценарий: ключ — в ревизии секретов платформы с шагами смены", () => {
const def = PLATFORM_SECRETS.find((d) => d.name === "NEXT_SERVER_ACTIONS_ENCRYPTION_KEY");
assert.ok(def, "listed in PLATFORM_SECRETS");
assert.ok(def.steps.some((s) => s.includes("platform-deploy.sh")));
assert.ok(def.steps.some((s) => s.includes("peppa secrets rotated NEXT_SERVER_ACTIONS_ENCRYPTION_KEY")));
});
});
// Minimal DOM and storage mocks for the browser logic.
function mockStorage() {
const m = new Map<string, string>();
return { getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => void m.set(k, v), removeItem: (k: string) => void m.delete(k), m };
}
function mockField(o: { tag?: string; type?: string; name?: string; id?: string; value?: string; form?: unknown; attrs?: string[] }) {
return { tagName: o.tag ?? "TEXTAREA", type: o.type, name: o.name ?? "", id: o.id ?? "", value: o.value ?? "", form: o.form ?? null, hasAttribute: (a: string) => (o.attrs ?? []).includes(a) };
}
describe("PEP-324: неизвестное действие обновляет страницу", () => {
const BUGSINK_23 = 'Server Action "406e36ceb318b543405d508f17c1a2396a4e06ee40" was not found on the server. \nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action';
test("Сценарий: ошибка «такого действия нет» распознаётся во всех видах", async () => {
const { UnrecognizedActionError } = (await import(new URL("../../../apps/web/node_modules/next/dist/client/components/unrecognized-action-error.js", import.meta.url).href)) as { UnrecognizedActionError: new (m: string) => Error };
assert.equal(lib.isStaleAction(new UnrecognizedActionError(BUGSINK_23), (e) => e instanceof UnrecognizedActionError), true);
assert.equal(lib.isStaleAction(new Error("x"), (e) => e instanceof Error), true, "Next's own check is asked first");
const copy = Object.assign(new Error(BUGSINK_23), { name: "UnrecognizedActionError" });
assert.equal(lib.isStaleAction(copy), true, "from another copy of the module");
assert.equal(lib.isStaleAction(`Error: ${BUGSINK_23}`), true, "as console.error text");
assert.equal(lib.isStaleAction(new Error("boom")), false);
assert.equal(lib.isStaleAction(null), false);
});
test("Сценарий: кнопка открытой до выкатки вкладки — текст сохраняется и возвращается после обновления", () => {
const storage = mockStorage();
const form = {};
const t = new lib.DraftTracker();
const comment = mockField({ name: "comment", value: "Поправьте заголовок", form });
t.input(comment);
t.input(mockField({ tag: "INPUT", type: "password", name: "pw", value: "secret" }));
t.input(mockField({ tag: "INPUT", type: "hidden", name: "taskId", value: "7" }));
t.input(mockField({ value: "без имени" }));
const now = 1_000_000;
// The failing press is the submit of this very form.
t.submit(form, now);
assert.equal(lib.claimReload(storage, now), true, "the first time the page reloads itself");
lib.saveDrafts(storage, "/t/PEP-1", t.snapshot(now + 500), now + 500);
// After the reload: the field is on the page again, empty.
const fresh = mockField({ name: "comment" });
const placed: string[] = [];
const fields = lib.takeDrafts(storage, "/t/PEP-1", now + 3000);
assert.deepEqual(fields, { comment: "Поправьте заголовок" }, "no password, hidden or nameless fields");
const left = lib.restoreDrafts(fields!, (k) => (k === "comment" ? fresh : null), (el, v) => {
el.value = v;
placed.push(v);
});
assert.deepEqual(left, []);
assert.equal(fresh.value, "Поправьте заголовок");
assert.equal(lib.takeDrafts(storage, "/t/PEP-1", now + 4000), null, "restored once");
});
test("Сценарий: обновление не помогло — второй раз сама не обновляется", () => {
const storage = mockStorage();
assert.equal(lib.claimReload(storage, 0 + 1), true);
assert.equal(lib.claimReload(storage, 20_001), false, "20 s later: a button instead of a reload loop");
assert.equal(lib.claimReload(storage, 1 + lib.RELOAD_GUARD_MS + 1), true, "a minute later it may again");
});
test("Сценарий: отправленный текст не возвращается", () => {
const form = {};
const t = new lib.DraftTracker();
t.input(mockField({ name: "comment", value: "Готово", form }));
t.submit(form, 0);
// A minute later another button fails: the sent and cleared form stays empty.
assert.deepEqual(t.snapshot(60_000), {});
// A field typed after the submit is kept.
t.input(mockField({ name: "title", value: "Новое", form }));
assert.deepEqual(t.snapshot(60_000), { title: "Новое" });
});
test("Сценарий: текст другой страницы или старый — не возвращается, набранное заново не затирается", () => {
const storage = mockStorage();
lib.saveDrafts(storage, "/p/PEP", { comment: "x" }, 0);
assert.equal(lib.takeDrafts(storage, "/t/PEP-1", 1000), null);
lib.saveDrafts(storage, "/t/PEP-1", { comment: "x" }, 0);
assert.equal(lib.takeDrafts(storage, "/t/PEP-1", lib.DRAFTS_TTL_MS + 1), null);
const typed = mockField({ name: "comment", value: "уже набрано" });
lib.restoreDrafts({ comment: "x" }, () => typed, (el, v) => (el.value = v));
assert.equal(typed.value, "уже набрано");
});
test("Сценарий: в «Ошибки из прода» не уходит, другие ошибки уходят", () => {
const reporter = read("apps/web/components/ErrorReporter.tsx");
const send = reporter.slice(reporter.indexOf("const send = "));
assert.ok(send.indexOf("isStaleAction(message)") > 0 && send.indexOf("isStaleAction(message)") < send.indexOf("/api/client-errors"), "skipped before sending");
const guard = read("apps/web/components/StaleActionGuard.tsx");
assert.match(guard, /isStaleAction\(e\.reason\)\) return;\s*e\.preventDefault\(\)/);
assert.match(read("apps/web/app/layout.tsx"), /<StaleActionGuard \/>/);
const boundary = read("apps/web/app/error.tsx");
assert.match(boundary, /^"use client";/);
assert.match(boundary, /isStaleAction\(error\)/);
assert.match(guard, /isStaleText\(err, unstable_isUnrecognizedActionError\)/);
assert.match(boundary, /reportStaleAction\(\)/);
});
});