Files
Florian Schmidt 2fc5f99f59 feat(server): request updates through a systemd trigger (#15)
The service stays unprivileged: POST /api/settings/update only writes the
update-request file in the data directory, which a root-owned path unit
watches. Status comes from systemctl show and the root-owned update log;
the check fetches the tracked branch into FETCH_HEAD and lists new commits.
2026-11-16 15:31:00 +01:00

169 lines
8.3 KiB
TypeScript

import { afterEach, expect, it } from "vitest";
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app";
import type { UpdateOptions } from "../src/update";
const dirs: string[] = [];
const apps: FastifyInstance[] = [];
afterEach(async () => {
for (const app of apps.splice(0)) await app.close();
for (const path of dirs.splice(0)) await rm(path, { recursive: true, force: true });
});
type Reply = string | Error;
/** Fake for `git`/`systemctl`: answers by "file arg arg…" prefix and records every call. */
function fakeRun(answers: Record<string, Reply>) {
const calls: string[][] = [];
const run: UpdateOptions["run"] = async (file, args) => {
calls.push([file, ...args]);
const line = [file, ...args].join(" ");
const key = Object.keys(answers).sort((a, b) => b.length - a.length).find((k) => line.startsWith(k));
if (key === undefined) throw new Error(`unexpected command: ${line}`);
const answer = answers[key]!;
if (answer instanceof Error) throw answer;
return answer;
};
return { run, calls };
}
const show = (state: string, result = "success", start = "@1763300000", exit = "@1763300090") =>
`ActiveState=${state}\nResult=${result}\nExecMainStartTimestamp=${start}\nExecMainExitTimestamp=${exit}\n`;
const git = (repo: string) => `git -C ${repo}`;
async function setup(answers: Record<string, Reply>, installed = true, withAuth = false) {
const root = await mkdtemp(join(tmpdir(), "update-"));
dirs.push(root);
const triggerUnit = join(root, "shellbook-update.path");
if (installed) await writeFile(triggerUnit, "[Path]\n");
const fake = fakeRun(answers);
const options: Partial<UpdateOptions> = {
triggerUnit,
logFile: join(root, "update.log"),
repoDir: join(root, "repo"),
run: fake.run,
};
const app = await buildApp({ config: { dataDir: join(root, "data") }, auth: withAuth ? undefined : false, update: options });
apps.push(app);
return { app, root, repo: options.repoDir!, calls: fake.calls, requestFile: join(root, "data", "update-request"), logFile: options.logFile! };
}
it("reports the installed commit, the last run and the end of its log", async () => {
const { app, logFile, calls } = await setup({
"git -C": "abc1234\n",
"systemctl show shellbook-update.service": show("inactive"),
});
const lines = Array.from({ length: 400 }, (_, i) => `line ${i}`);
await writeFile(logFile, lines.join("\n") + "\n");
const status = (await app.inject("/api/settings/update")).json();
expect(status).toMatchObject({
available: true,
state: "succeeded",
current: "abc1234",
startedAt: new Date(1763300000 * 1000).toISOString(),
finishedAt: new Date(1763300090 * 1000).toISOString(),
});
// Only the end of a long log is returned.
expect(status.log.split("\n")[0]).toBe("line 200");
expect(status.log).toContain("line 399");
// Read-only queries only, with argv (no shell).
expect(calls.map((c) => c[0])).toEqual(expect.arrayContaining(["git", "systemctl"]));
expect(calls.find((c) => c[0] === "systemctl")).toEqual([
"systemctl", "show", "shellbook-update.service", "--timestamp=unix",
"--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp",
]);
});
it.each([
[show("activating", "success", "@1763300000", ""), "running"],
[show("failed", "exit-code"), "failed"],
[show("inactive", "success", "", ""), "idle"],
])("maps unit state %#", async (output, state) => {
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": output });
expect((await app.inject("/api/settings/update")).json().state).toBe(state);
});
it("says so when systemd cannot be asked, and is unavailable without the trigger unit", async () => {
const broken = await setup({ "git -C": new Error("no git"), "systemctl show": new Error("no systemd") });
expect((await broken.app.inject("/api/settings/update")).json()).toMatchObject({ available: true, state: "unknown", current: null });
const missing = await setup({ "git -C": "abc1234\n" }, false);
expect((await missing.app.inject("/api/settings/update")).json()).toMatchObject({ available: false, state: "idle", current: "abc1234" });
// Never asks systemd or writes a request without the units.
expect(missing.calls.some((c) => c[0] === "systemctl")).toBe(false);
expect((await missing.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
await expect(stat(missing.requestFile)).rejects.toMatchObject({ code: "ENOENT" });
});
it("starts an update only by writing the request file, and never twice at once", async () => {
const idle = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") });
const started = await idle.app.inject({ method: "POST", url: "/api/settings/update", payload: {} });
expect(started.statusCode).toBe(202);
const { requestedAt } = started.json();
expect(Date.parse(requestedAt)).not.toBeNaN();
expect((await readFile(idle.requestFile, "utf8")).trim()).toBe(requestedAt);
// The server itself never starts units or runs the updater.
expect(idle.calls.filter((c) => c[0] === "systemctl").every((c) => c[1] === "show")).toBe(true);
const busy = await setup({ "git -C": "abc1234\n", "systemctl show": show("active", "success", "@1763300000", "") });
expect((await busy.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
});
it("checks the tracked branch and lists the commits an update would bring", async () => {
const answers: Record<string, Reply> = {};
const target = await setup(answers);
Object.assign(answers, {
[`${git(target.repo)} rev-parse --short HEAD`]: "abc1234\n",
[`${git(target.repo)} symbolic-ref -q --short HEAD`]: "main\n",
[`${git(target.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
[`${git(target.repo)} fetch --quiet --no-tags -- origin main`]: "",
[`${git(target.repo)} rev-parse --short FETCH_HEAD`]: "def5678\n",
[`${git(target.repo)} log --format=%h%x09%s -n 50 HEAD..FETCH_HEAD`]: "def5678\tfeat(web): b\nbbb0000\tfix: a\ttab\n",
"systemctl show": show("inactive"),
});
const result = await target.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
expect(result.statusCode).toBe(200);
expect(result.json()).toEqual({
current: "abc1234",
latest: "def5678",
pinned: false,
changes: [
{ commit: "def5678", subject: "feat(web): b" },
{ commit: "bbb0000", subject: "fix: a\ttab" },
],
});
});
it("reports a pinned checkout without fetching, and a failed fetch as 502", async () => {
const pinnedAnswers: Record<string, Reply> = {};
const pinned = await setup(pinnedAnswers);
Object.assign(pinnedAnswers, {
[`${git(pinned.repo)} rev-parse --short HEAD`]: "abc1234\n",
[`${git(pinned.repo)} symbolic-ref -q --short HEAD`]: new Error("detached"),
"systemctl show": show("inactive"),
});
const result = await pinned.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
expect(result.json()).toEqual({ current: "abc1234", latest: null, pinned: true, changes: [] });
expect(pinned.calls.some((c) => c.includes("fetch"))).toBe(false);
const offlineAnswers: Record<string, Reply> = {};
const offline = await setup(offlineAnswers);
Object.assign(offlineAnswers, {
[`${git(offline.repo)} rev-parse --short HEAD`]: "abc1234\n",
[`${git(offline.repo)} symbolic-ref -q --short HEAD`]: "main\n",
[`${git(offline.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
[`${git(offline.repo)} fetch`]: new Error("Could not resolve host"),
"systemctl show": show("inactive"),
});
const failed = await offline.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
expect(failed.statusCode).toBe(502);
// The git error text stays in the server log, not in the response.
expect(failed.body).not.toContain("resolve host");
});
it("requires a session", async () => {
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") }, true, true);
expect((await app.inject("/api/settings/update")).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(401);
});