diff --git a/scripts/start-webspeak.sh b/scripts/start-webspeak.sh index 323eef1..c5007a3 100755 --- a/scripts/start-webspeak.sh +++ b/scripts/start-webspeak.sh @@ -53,15 +53,71 @@ task_backup_can_repair() { } state_file="$data_dir/updates/state.json" -task_id="" -task_status="" -if [ -f "$state_file" ]; then - task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1) - task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1) -fi -case "$task_id" in - ""|*[!A-Za-z0-9_-]*) task_id="" ;; -esac +lock_file="$data_dir/updates/update.lock" +read_update_task() { + task_id="" + task_status="" + if [ -f "$state_file" ]; then + task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1) + task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1) + fi + case "$task_id" in + ""|*[!A-Za-z0-9_-]*) task_id="" ;; + esac +} +read_update_task + +process_start() { + # After the last ')' field 3 is first; starttime (field 22) is twentieth. + if [ -r "/proc/$1/stat" ]; then + sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}' + fi +} + +release_recovery_lock() { + if [ "${lock_owned:-0}" = 1 ] && [ "$(cat "$lock_file" 2>/dev/null)" = "$lock_payload" ]; then + rm -f -- "$lock_file" + fi + lock_owned=0 +} + +acquire_recovery_lock() { + # Share the updater's exclusive-create JSON lock. A distinct task id stops + # a delayed restart runner from taking this recovery lock over. Keep it for + # the entire restore, and only reclaim a proven-dead, unchanged owner. + mkdir -p "$data_dir/updates" + lock_owned=0 + start=$(process_start "$$") + lock_payload="{\"pid\":$$,\"taskId\":\"recovery_$$\",\"createdAt\":\"\",\"processStart\":\"$start\"}" + for attempt in 1 2 3 4; do + if (umask 077; set -C; printf '%s\n' "$lock_payload" > "$lock_file") 2>/dev/null; then + lock_owned=1 + trap 'release_recovery_lock' 0 + trap 'exit 1' HUP INT TERM + return 0 + fi + observed=$(cat "$lock_file" 2>/dev/null) || return 1 + owner=$(printf '%s\n' "$observed" | sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\)[[:space:]]*[,}].*/\1/p' | head -n 1) + owner_task=$(printf '%s\n' "$observed" | sed -n 's/.*"taskId"[[:space:]]*:[[:space:]]*"\([^"]\{1,\}\)".*/\1/p' | head -n 1) + case "$owner" in ""|*[!0-9]*) return 1 ;; esac + [ -n "$owner_task" ] || return 1 + if [ "$owner" != 0 ]; then + if kill -0 "$owner" 2>/dev/null || [ -d "/proc/$owner" ]; then + saved_start=$(printf '%s\n' "$observed" | sed -n 's/.*"processStart"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1) + current_start=$(process_start "$owner") + # Unknown markers and inaccessible processes are conservatively live. + if [ -z "$saved_start" ] || [ -z "$current_start" ] || [ "$saved_start" = "$current_start" ]; then + return 1 + fi + elif [ ! -d /proc ]; then + return 1 + fi + fi + [ "$(cat "$lock_file" 2>/dev/null)" = "$observed" ] || continue + rm -f -- "$lock_file" || return 1 + done + return 1 +} recovery_needed() { if code_missing; then @@ -105,6 +161,15 @@ restore_from_backup() { } if recovery_needed; then + if ! acquire_recovery_lock; then + echo "WebSpeak update or recovery is already running, or its lock cannot be verified; refusing to change application files." >&2 + exit 75 + fi + # The runner may have completed between the first state read and the lock. + read_update_task +fi + +if [ "${lock_owned:-0}" = 1 ] && recovery_needed; then restore_backup="" # The interrupted task is the source of truth. Its backup may be partial @@ -140,4 +205,5 @@ if recovery_needed; then fi fi +release_recovery_lock exec "$PWD/runtime/node" "$PWD/dist/index.js" diff --git a/src/updater/restart-runner.test.ts b/src/updater/restart-runner.test.ts index 1663beb..3aefead 100644 --- a/src/updater/restart-runner.test.ts +++ b/src/updater/restart-runner.test.ts @@ -126,6 +126,21 @@ async function stopPidFile(pidFile: string): Promise { } } +test("a runner refused by another lock owner leaves its files and state untouched", async t => { + const fixture = runnerFixture(t); + writePlan(fixture, await availablePort(), fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" }); + const owner = JSON.stringify({ pid: process.pid, taskId: "recovery_owner", createdAt: new Date().toISOString() }); + writeFileSync(fixture.lockPath, owner); + writeFileSync(fixture.statePath, JSON.stringify({ schemaVersion: 1, task: null })); + const before = readFileSync(fixture.statePath, "utf8"); + assert.equal(await runRestartPlan(fixture.planPath), 1); + assert.equal(readFileSync(fixture.statePath, "utf8"), before); + assert.equal(readFileSync(fixture.lockPath, "utf8"), owner); + assert.equal(existsSync(fixture.backupDir), false); + assert.equal(existsSync(fixture.pidFile), false); + assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "1.0.0"); +}); + test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => { const fixture = runnerFixture(t); const port = await availablePort(); diff --git a/src/updater/restart-runner.ts b/src/updater/restart-runner.ts index 411296d..6b8539c 100644 --- a/src/updater/restart-runner.ts +++ b/src/updater/restart-runner.ts @@ -273,8 +273,6 @@ export async function runRestartPlan(planPath: string): Promise { const state = new StateWriter(plan); let swapped = false; let newApp: ChildProcess | undefined; - state.status("restarting"); - state.step("restart", "running"); // Take over the update lock before doing anything else. The parent process // is about to exit and its lock would otherwise have a dead pid, letting a // second instance starting in this window roll the healthy code back. @@ -285,6 +283,8 @@ export async function runRestartPlan(planPath: string): Promise { } catch (error) { throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over."); } + state.status("restarting"); + state.step("restart", "running"); await waitForParent(plan.waitForPid, plan.parentTimeoutMs); state.step("swap", "running"); swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir); @@ -303,6 +303,9 @@ export async function runRestartPlan(planPath: string): Promise { try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ } return 0; } catch (error) { + // A recovery process or another update owns the tree. Without ownership + // this runner must not rewrite its state or start an app during recovery. + if (!releaseLock) return 1; await stopApp(newApp); const code = error instanceof RunnerError || error instanceof CodeSwapError ? error.code diff --git a/src/updater/swap-recovery.test.ts b/src/updater/swap-recovery.test.ts index eef6b41..960d6f0 100644 --- a/src/updater/swap-recovery.test.ts +++ b/src/updater/swap-recovery.test.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { UpdateService } from "./update-service.js"; import { CODE_ENTRIES, swapCode } from "./code-swap.js"; +import { acquireUpdateLock, updateLockIsHeld } from "./update-state.js"; const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url)); const REPO_ROOT = path.resolve(SOURCE_DIR, "..", ".."); @@ -17,6 +18,67 @@ const TASK_ID = "upd_sigkill_window"; const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } }; +for (const lockKind of ["live", "unreadable"] as const) { + test(`launcher preserves a target while the update lock is ${lockKind}`, { timeout: 15_000, skip: process.platform !== "linux" }, async t => { + const fixture = buildFixture(t, await availablePort()); + swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir); + const lockPath = path.join(fixture.dataDir, "updates", "update.lock"); + if (lockKind === "live") { + const release = acquireUpdateLock(lockPath, TASK_ID); + t.after(release); + assert.equal(updateLockIsHeld(lockPath, TASK_ID), true); + } else { + writeFileSync(lockPath, "{invalid"); + } + const before = readFileSync(lockPath, "utf8"); + const app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { + cwd: fixture.rootDir, env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir }, stdio: "ignore", + }); + t.after(() => stop(app)); + await waitFor(() => app.exitCode !== null, "launcher did not refuse the held update lock", 5_000); + assert.equal(app.exitCode, 75); + assert.equal(readFileSync(lockPath, "utf8"), before); + assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0"); + assert.equal(JSON.parse(readFileSync(path.join(fixture.backupDir, "package.json"), "utf8")).version, "0.3.2"); + }); +} + +test("concurrent launchers cannot restore the same interrupted tree together", { timeout: 20_000, skip: process.platform !== "linux" }, async t => { + const port = await availablePort(); + const fixture = buildFixture(t, port); + swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir); + const bin = path.join(fixture.directory, "bin"); + mkdirSync(bin); + // Pause the first real restore at mv, without adding a production test hook. + writeFileSync(path.join(bin, "mv"), `#!/bin/sh +printf '%s' "$$" > "$RECOVERY_TEST_BARRIER/entered" +attempt=0 +while [ ! -f "$RECOVERY_TEST_BARRIER/resume" ] && [ "$attempt" -lt 200 ]; do + sleep 0.05 + attempt=$((attempt + 1)) +done +exec /bin/mv "$@" +`, { mode: 0o755 }); + const env = { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir, + PATH: `${bin}${path.delimiter}${process.env.PATH}`, RECOVERY_TEST_BARRIER: fixture.barrierDir }; + const first = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" }); + let second: ChildProcess | undefined; + t.after(() => { writeFileSync(path.join(fixture.barrierDir, "resume"), ""); stop(first); stop(second); }); + await waitFor(() => existsSync(path.join(fixture.barrierDir, "entered")), "first launcher did not start restoring"); + const lockPath = path.join(fixture.dataDir, "updates", "update.lock"); + assert.equal(updateLockIsHeld(lockPath), true); + const owner = readFileSync(lockPath, "utf8"); + second = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" }); + await waitFor(() => second!.exitCode !== null, "second launcher did not refuse concurrent recovery", 5_000); + assert.equal(second.exitCode, 75); + assert.equal(readFileSync(lockPath, "utf8"), owner); + writeFileSync(path.join(fixture.barrierDir, "resume"), ""); + await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "first launcher did not finish recovery"); + assert.equal(existsSync(lockPath), false); + stop(first); + await waitFor(() => !processAlive(first.pid), "recovered app did not stop", 5_000); +}); + // Exercise a kill after every old entry's rename, before the manifest is // updated. In particular the backup is still partial for the first entries. for (const entry of CODE_ENTRIES) { diff --git a/src/updater/update-service.test.ts b/src/updater/update-service.test.ts index a9a847a..3d81148 100644 --- a/src/updater/update-service.test.ts +++ b/src/updater/update-service.test.ts @@ -295,18 +295,96 @@ test("an asynchronous download write failure rejects the update without crashing }, })) as unknown as typeof fs.createWriteStream; syncBuiltinESMExports(); - const stalledBody = () => new ReadableStream({ + const cancelled = new Set(); + const responses: Response[] = []; + const signals: AbortSignal[] = []; + const stalledBody = (url: string) => new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); }, pull() { return new Promise(() => {}); }, + cancel() { cancelled.add(url); }, }); - const fetch = (async (input: string | URL | Request) => { + const fetch = (async (input: string | URL | Request, init?: RequestInit) => { if (String(input) === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 }); - return new Response(stalledBody(), { status: 200 }); + signals.push(init!.signal!); + const response = new Response(stalledBody(String(input)), { status: 200 }); + responses.push(response); + return response; }) as typeof globalThis.fetch; const { service, launched } = createService(t, [], new Map(), { fetch }); await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_FAILED")); assert.equal(launched.length, 0); + assert.equal(cancelled.size, 2); + assert.ok(signals.every(signal => signal.aborted)); + assert.ok(responses.every(response => !response.body!.locked)); +}); + +test("a rejected asset aborts its stalled sibling before update cleanup returns", { timeout: 5_000 }, async t => { + const archive = packageArchive("0.4.0"); + const checksums = Buffer.from(checksumText(ASSET_NAME, archive)); + const release = releaseJson({ version: "0.4.0", assets: [{ name: ASSET_NAME, data: archive }, { name: CHECKSUM_ASSET_NAME, data: checksums }] }); + const responses: Response[] = [], signals: AbortSignal[] = []; + let cancelled = 0; + const { service, dataDir } = createService(t, [], new Map(), { fetch: (async (input, init) => { + const url = String(input); + if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release])); + signals.push(init!.signal!); + const body = new ReadableStream({ + start(controller) { controller.enqueue(new Uint8Array([1])); }, + pull() { return new Promise(() => {}); }, + cancel() { cancelled++; }, + }); + const response = new Response(body, { headers: url.endsWith(ASSET_NAME) ? { "content-length": String(513 * 1024 * 1024) } : {} }); + responses.push(response); + return response; + }) as typeof fetch }); + await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE")); + assert.equal(cancelled, 2); + assert.ok(signals.every(signal => signal.aborted)); + assert.ok(responses.every(response => !response.body!.locked)); + assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false); +}); + +test("download rejection cancels its body and releases the reader, including unread responses", async t => { + for (const declaredSize of [false, true]) { + let cancelled = false; + let signal: AbortSignal | null | undefined; + const body = new ReadableStream({ + start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); }, + cancel() { cancelled = true; }, + }); + const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => { + signal = init?.signal; + return new Response(body, { headers: declaredSize ? { "content-length": "3" } : {} }); + }) as typeof fetch }); + const target = path.join(workspace(t), "asset"); + // A small injected byte limit exercises the production rejection path + // without allocating or writing a 512 MiB package in a regression test. + const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise }; + await assert.rejects(download.downloadAsset({ name: ASSET_NAME, + url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 1), + updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE")); + assert.equal(cancelled, true); + assert.equal(body.locked, false); + assert.equal(signal?.aborted, true); + assert.equal(existsSync(target), false); + assert.equal(existsSync(`${target}.${process.pid}.tmp`), false); + } +}); + +test("a successful download releases its reader without aborting the request", async t => { + let signal: AbortSignal | null | undefined; + const response = new Response(new Uint8Array([1, 2, 3])); + const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => { + signal = init?.signal; return response; + }) as typeof fetch }); + const target = path.join(workspace(t), "asset"); + const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise }; + await download.downloadAsset({ name: ASSET_NAME, + url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 4); + assert.deepEqual(readFileSync(target), Buffer.from([1, 2, 3])); + assert.equal(response.body!.locked, false); + assert.equal(signal?.aborted, false); }); test("a download redirected outside GitHub is refused before it is written", async t => { diff --git a/src/updater/update-service.ts b/src/updater/update-service.ts index 38daa9d..30845c5 100644 --- a/src/updater/update-service.ts +++ b/src/updater/update-service.ts @@ -330,10 +330,22 @@ export class UpdateService { const archivePath = path.join(downloadDirectory, assetName); const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME); this.startStep(task, "download"); - const [archive, checksumFile] = await Promise.all([ - this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT), - this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT), - ]); + const downloadsController = new AbortController(); + const downloads = [ + this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT, downloadsController.signal), + this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT, downloadsController.signal), + ]; + let archive: DownloadResult; + let checksumFile: DownloadResult; + try { + [archive, checksumFile] = await Promise.all(downloads); + } catch (error) { + downloadsController.abort(); + // No sibling may still hold a response reader or write into the task + // directory when applyUpdate's failure cleanup removes that directory. + await Promise.allSettled(downloads); + throw error; + } this.finishStep(task, "download", "succeeded"); this.updateTaskStatus(task, "verifying"); this.startStep(task, "checksum"); @@ -476,37 +488,49 @@ export class UpdateService { if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422); } - private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number): Promise { + private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number, cancelSignal?: AbortSignal): Promise { try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); } catch (error) { throw mapError(error); } let response: Response; + const controller = new AbortController(); + const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000), ...(cancelSignal ? [cancelSignal] : [])]); try { response = await this.fetcher(asset.url, { headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" }, - signal: AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000), + signal, }); } catch (error) { + controller.abort(); throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502); } - if (response.url) { - try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); } - catch (error) { throw mapError(error); } - } - if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502); - const declared = Number(response.headers.get("content-length") ?? ""); - if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422); - const temporary = `${destination}.${process.pid}.tmp`; - const hash = createHash("sha256"); - const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" }); - let bytes = 0; - let failStream!: (error: Error) => void; - const streamFailure = new Promise((resolve) => { failStream = resolve; }); - stream.on("error", failStream); - const finished = new Promise((resolve) => { stream.once("finish", resolve); }); + let reader: ReadableStreamDefaultReader | undefined; + let stream: ReturnType | undefined; + let temporary: string | undefined; + let onAbort: (() => void) | undefined; try { - const iterator = (response.body as unknown as AsyncIterable)[Symbol.asyncIterator](); + if (response.url) { + try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); } + catch (error) { throw mapError(error); } + } + if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502); + const declared = Number(response.headers.get("content-length") ?? ""); + if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422); + temporary = `${destination}.${process.pid}.tmp`; + const hash = createHash("sha256"); + signal.throwIfAborted(); + reader = response.body.getReader(); + stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" }); + let bytes = 0; + let failStream!: (error: Error) => void; + const streamFailure = new Promise((resolve) => { failStream = resolve; }); + stream.on("error", failStream); + onAbort = () => failStream(signal.reason instanceof Error ? signal.reason : new Error("Download aborted.")); + signal.addEventListener("abort", onAbort, { once: true }); + if (signal.aborted) onAbort(); + const writer = stream; + const finished = new Promise((resolve) => { writer.once("finish", resolve); }); while (true) { - const next = await Promise.race([iterator.next(), streamFailure]); + const next = await Promise.race([reader.read(), streamFailure]); if (next instanceof Error) throw next; if (next.done) break; const buffer = Buffer.from(next.value); @@ -514,7 +538,7 @@ export class UpdateService { if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422); hash.update(buffer); if (!stream.write(buffer)) { - const drained = await Promise.race([streamFailure, new Promise((resolve) => { stream.once("drain", resolve); })]); + const drained = await Promise.race([streamFailure, new Promise((resolve) => { writer.once("drain", resolve); })]); if (drained instanceof Error) throw drained; } } @@ -522,13 +546,18 @@ export class UpdateService { const streamError = await Promise.race([finished.then(() => null), streamFailure]); if (streamError) throw streamError; await rename(temporary, destination); + return { sha256: hash.digest("hex"), bytes }; } catch (error) { - stream.destroy(); - await rm(temporary, { force: true }).catch(() => undefined); + controller.abort(); + await (reader ? reader.cancel() : response.body?.cancel())?.catch(() => undefined); + stream?.destroy(); + if (temporary) await rm(temporary, { force: true }).catch(() => undefined); if (error instanceof UpdateError) throw error; throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502); + } finally { + if (onAbort) signal.removeEventListener("abort", onAbort); + reader?.releaseLock(); } - return { sha256: hash.digest("hex"), bytes }; } /**