import test from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { mkdtemp, writeFile, rename, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { createServer } from "node:net"; import { once } from "node:events"; test("atomic password updates take effect without restart and fail closed on invalid files", async (t) => { const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-reload-")); t.after(() => rm(dir, { recursive: true, force: true })); const auth = join(dir, "auth.json"); const data = { password: "old-password", secret: "s".repeat(40) }; await writeFile(auth, JSON.stringify(data)); const portServer = createServer().listen(0,"127.0.0.1"); await once(portServer,"listening"); const port = portServer.address().port; await new Promise((done) => portServer.close(done)); const child = spawn(process.execPath, ["serve.mjs", "--port", String(port)], { cwd: fileURLToPath(new URL("..", import.meta.url)), env: { ...process.env, PIPELINES_WEB_AUTH: "", PIPELINES_WEB_AUTH_FILE: auth }, stdio:["ignore","pipe","inherit"] }); t.after(async () => { const stopped = once(child,"exit"); child.kill(); await stopped; }); await once(child.stdout,"data"); const base = `http://127.0.0.1:${port}`; const login = (password) => fetch(base + "/login", { method:"POST", body:new URLSearchParams({password}), redirect:"manual" }); const first = await login("old-password"); assert.equal(first.status,303); const cookie = first.headers.get("set-cookie").split(";")[0]; await writeFile(auth + ".next", JSON.stringify({ ...data, password:"new-password" })); await rename(auth + ".next",auth); assert.equal((await login("old-password")).status,401); const second = await login("new-password"); assert.equal(second.status,303); // A changed password signs the earlier session out; the new one is signed in. assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,200); const cookie2 = second.headers.get("set-cookie").split(";")[0]; assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,302); await writeFile(auth + ".next", "malformed"); await rename(auth + ".next",auth); assert.equal((await login("new-password")).status,503); assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,503); await writeFile(auth,JSON.stringify(data)); assert.equal((await login("old-password")).status,303); });