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.
This commit is contained in:
@@ -10,6 +10,7 @@ import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
import { chatPlugin } from "./chat";
|
||||
import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
@@ -26,6 +27,8 @@ export interface AppOptions {
|
||||
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
|
||||
watchNotebooks?: boolean;
|
||||
terminal?: Omit<TerminalOptions, "workspaceDir">;
|
||||
/** Overrides for the self-update trigger (tests). */
|
||||
update?: Partial<UpdateOptions>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,7 +36,7 @@ export interface AppOptions {
|
||||
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
|
||||
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
|
||||
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
|
||||
* src/static/ built web app with SPA fallback
|
||||
* src/static/ built web app with SPA fallback; src/update/ self-update trigger (root runs it via systemd)
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = loadConfig(options.config);
|
||||
@@ -41,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await registerSettings(app, config);
|
||||
await registerUpdate(app, { ...defaultUpdateOptions(config.dataDir), ...options.update });
|
||||
await app.register(websocket);
|
||||
const builtins = () => builtinValues(config);
|
||||
await app.register(workspacePlugin, { config, builtins });
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, mkdir, open, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type {
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateState,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* Self-update from the web UI (#15). The service never gains privileges: it only writes
|
||||
* a request file. A root-owned systemd path unit (deploy/install.sh) watches that file
|
||||
* and starts `shellbook-update.service`, which runs the fixed root-owned updater and
|
||||
* writes its output to a root-owned log. Here we only read that state back.
|
||||
*/
|
||||
export interface UpdateOptions {
|
||||
/** Written to request an update; watched by shellbook-update.path. */
|
||||
requestFile: string;
|
||||
/** Present when the trigger units are installed. */
|
||||
triggerUnit: string;
|
||||
/** Output of the last update run (StandardOutput of the update unit). */
|
||||
logFile: string;
|
||||
/** The git checkout the server runs from. */
|
||||
repoDir: string;
|
||||
/** Runs a program with argv (no shell) and returns stdout; rejects on failure. */
|
||||
run(file: string, args: string[], timeoutMs: number): Promise<string>;
|
||||
}
|
||||
|
||||
const UNIT = "shellbook-update.service";
|
||||
const LOG_BYTES = 64 * 1024;
|
||||
const LOG_LINES = 200;
|
||||
|
||||
function run(file: string, args: string[], timeoutMs: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
file,
|
||||
args,
|
||||
// Never wait for credentials on a terminal that is not there.
|
||||
{ timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
|
||||
(error, stdout) => (error ? reject(error) : resolve(stdout)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function defaultUpdateOptions(dataDir: string): UpdateOptions {
|
||||
return {
|
||||
requestFile: join(dataDir, "update-request"),
|
||||
triggerUnit: "/etc/systemd/system/shellbook-update.path",
|
||||
logFile: "/var/log/shellbook-update.log",
|
||||
// systemd starts the service in the checkout (WorkingDirectory=/opt/shellbook).
|
||||
repoDir: process.cwd(),
|
||||
run,
|
||||
};
|
||||
}
|
||||
|
||||
/** `--timestamp=unix` prints `@<seconds>`; empty or `n/a` means never. */
|
||||
function timestamp(value: string | undefined): string | null {
|
||||
const match = value?.match(/^@(\d+)$/);
|
||||
return match ? new Date(Number(match[1]) * 1000).toISOString() : null;
|
||||
}
|
||||
|
||||
/** The last lines of the log, reading at most LOG_BYTES from its end. */
|
||||
async function logTail(path: string): Promise<string> {
|
||||
let file;
|
||||
try {
|
||||
file = await open(path, "r");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
const length = Math.min(size, LOG_BYTES);
|
||||
const buffer = Buffer.alloc(length);
|
||||
await file.read(buffer, 0, length, size - length);
|
||||
const lines = buffer.toString("utf8").split("\n");
|
||||
// Drop a partial first line when the read started mid-file.
|
||||
if (length < size) lines.shift();
|
||||
if (lines.at(-1) === "") lines.pop();
|
||||
return lines.slice(-LOG_LINES).join("\n");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function createUpdater(options: UpdateOptions) {
|
||||
const git = (args: string[], timeoutMs = 5000) =>
|
||||
options.run("git", ["-C", options.repoDir, ...args], timeoutMs).then((out) => out.trim());
|
||||
const current = () => git(["rev-parse", "--short", "HEAD"]).catch(() => null);
|
||||
const available = () => access(options.triggerUnit).then(() => true, () => false);
|
||||
|
||||
async function unitState(): Promise<Pick<UpdateStatusResponse, "state" | "startedAt" | "finishedAt">> {
|
||||
let output: string;
|
||||
try {
|
||||
output = await options.run(
|
||||
"systemctl",
|
||||
["show", UNIT, "--timestamp=unix", "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp"],
|
||||
5000,
|
||||
);
|
||||
} catch {
|
||||
return { state: "unknown", startedAt: null, finishedAt: null };
|
||||
}
|
||||
const props: Record<string, string> = Object.fromEntries(
|
||||
output.split("\n").filter((line) => line.includes("=")).map((line) => {
|
||||
const at = line.indexOf("=");
|
||||
return [line.slice(0, at), line.slice(at + 1).trim()];
|
||||
}),
|
||||
);
|
||||
const startedAt = timestamp(props.ExecMainStartTimestamp);
|
||||
const finishedAt = timestamp(props.ExecMainExitTimestamp);
|
||||
let state: UpdateState;
|
||||
if (["activating", "active", "reloading", "deactivating"].includes(props.ActiveState ?? "")) state = "running";
|
||||
else if (props.ActiveState === "failed" || (startedAt && props.Result !== "success")) state = "failed";
|
||||
else state = startedAt ? "succeeded" : "idle";
|
||||
return { state, startedAt, finishedAt: state === "running" ? null : finishedAt };
|
||||
}
|
||||
|
||||
return {
|
||||
async status(): Promise<UpdateStatusResponse> {
|
||||
const [isAvailable, commit] = await Promise.all([available(), current()]);
|
||||
if (!isAvailable)
|
||||
return { available: false, state: "idle", current: commit, startedAt: null, finishedAt: null, log: "" };
|
||||
return { available: true, current: commit, ...(await unitState()), log: await logTail(options.logFile) };
|
||||
},
|
||||
|
||||
/** Fetches the tracked branch (FETCH_HEAD only) and lists the commits an update would bring. */
|
||||
async check(): Promise<UpdateCheckResponse> {
|
||||
const commit = await current();
|
||||
const branch = await git(["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null);
|
||||
// A detached HEAD is a pinned SHELLBOOK_REF: the installer never pulls it.
|
||||
if (!branch) return { current: commit, latest: null, pinned: true, changes: [] };
|
||||
const upstream = await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
|
||||
const slash = upstream.indexOf("/");
|
||||
if (slash <= 0) throw new Error(`Unexpected upstream: ${upstream}`);
|
||||
await git(["fetch", "--quiet", "--no-tags", "--", upstream.slice(0, slash), upstream.slice(slash + 1)], 30_000);
|
||||
const latest = await git(["rev-parse", "--short", "FETCH_HEAD"]);
|
||||
const log = await git(["log", "--format=%h%x09%s", "-n", "50", "HEAD..FETCH_HEAD"]);
|
||||
const changes = log
|
||||
? log.split("\n").map((line) => {
|
||||
const tab = line.indexOf("\t");
|
||||
return { commit: line.slice(0, tab), subject: line.slice(tab + 1) };
|
||||
})
|
||||
: [];
|
||||
return { current: commit, latest, pinned: false, changes };
|
||||
},
|
||||
|
||||
/** Requests an update; systemd runs it as root. Returns null when it cannot start. */
|
||||
async start(): Promise<{ ok: true; response: UpdateStartResponse } | { ok: false; error: string }> {
|
||||
if (!(await available())) return { ok: false, error: "Updating from the web UI is not installed here. Run shellbook-update as root." };
|
||||
if ((await unitState()).state === "running") return { ok: false, error: "An update is already running." };
|
||||
const requestedAt = new Date().toISOString();
|
||||
await mkdir(dirname(options.requestFile), { recursive: true });
|
||||
// Closing the written file is what triggers the path unit (PathChanged=).
|
||||
await writeFile(options.requestFile, requestedAt + "\n", { mode: 0o600 });
|
||||
return { ok: true, response: { requestedAt } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function registerUpdate(app: FastifyInstance, options: UpdateOptions): Promise<void> {
|
||||
const updater = createUpdater(options);
|
||||
app.get("/api/settings/update", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await updater.status()),
|
||||
);
|
||||
app.post("/api/settings/update/check", async (_request, reply) => {
|
||||
if ((await updater.status()).state === "running")
|
||||
return reply.code(409).send({ error: "An update is running." });
|
||||
try {
|
||||
return reply.header("Cache-Control", "no-store").send(await updater.check());
|
||||
} catch (error) {
|
||||
app.log.warn({ err: error }, "update check failed");
|
||||
return reply.code(502).send({ error: "Could not check the repository for updates." });
|
||||
}
|
||||
});
|
||||
app.post("/api/settings/update", async (_request, reply) => {
|
||||
const result = await updater.start();
|
||||
return result.ok ? reply.code(202).send(result.response) : reply.code(409).send({ error: result.error });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user