Versions 84 to 318
new file, 346 lines
1+// A visitor folder: abso join <project> --reader with no sign-in, for a public project. It reads 2+// through the routes anyone can read and sends no credential. The rules, each a test: 3+// - no Authorization header and no cookie go out, with a token in the environment and a box sign-in 4+// present, and no redirect is followed; 5+// - join answers a private project and a missing one alike, by the status answer's code alone; 6+// - the commands it runs are an allow-list, and a new command fails this test until it's sorted; 7+// - its config comes from the command line only, never from an answer; 8+// - what comes back goes through the terminal filter, a 429's text too; 9+// - show prints a file and writes nothing, even for a path outside the folder. 11+import assert from "node:assert/strict"; 12+import { execFile } from "node:child_process"; 13+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; 14+import { createServer, type IncomingHttpHeaders, type Server } from "node:http"; 15+import type { AddressInfo } from "node:net"; 16+import { tmpdir } from "node:os"; 17+import { join, resolve } from "node:path"; 18+import { after, before, describe, it } from "node:test"; 19+import { Api } from "../src/api.ts"; 20+import { writeBox } from "../src/box.ts"; 21+import { writeConfig } from "../src/config.ts"; 22+import { isPublic } from "../src/join-commands.ts"; 23+import { commandTable, main } from "../src/main.ts"; 24+import { VISITOR_ELSEWHERE, VISITOR_READS } from "../src/visitor.ts"; 26+const CLIENT = resolve(import.meta.dirname, "..", "abso.ts"); 28+const TOKEN = "abso_test-token-never-sent"; 29+const CREDENTIAL = "abso_bx_test-credential-never-sent"; 31+/** Every command a visitor folder refuses. A new command fails the allow-list test until it's here or a read. */ 40+ // A project's groups are its members' to read and write; a visitor sees none. 96+// Where the site's redirect points: a visitor never gets here. 97+let elsewhere: Server; 98+let elsewhereUrl: string; 99+const heard: { url: string; headers: IncomingHttpHeaders }[] = []; 100+let elsewhereHeard = 0; 101+const dirs: string[] = []; 102+const temp = (name: string) => { 103+ const dir = mkdtempSync(join(tmpdir(), `abso-test-visitor-${name}-`)); 108+const json = (res: import("node:http").ServerResponse, status: number, body: unknown, headers = {}) => 109+ res.writeHead(status, { "content-type": "application/json", ...headers }).end(JSON.stringify(body)); 112+ elsewhere = createServer((_req, res) => { 114+ json(res, 200, { version: 9, agents: [] }); 116+ await new Promise<void>((done) => elsewhere.listen(0, "127.0.0.1", done)); 117+ elsewhereUrl = `http://127.0.0.1:${(elsewhere.address() as AddressInfo).port}`; 118+ site = createServer((req, res) => { 119+ heard.push({ url: req.url ?? "", headers: req.headers }); 120+ const path = new URL(req.url ?? "/", "http://x").pathname; 121+ if (path === "/p/abso-core/status") 122+ // An answer naming another server: the folder's config never takes it. 123+ return json(res, 200, { version: 3, agents: [], server: "http://answer.example" }); 124+ if (path === "/p/abso-core/file") 125+ return json(res, 200, { path: "a.txt", version: 1, text: `hi ${ESC}]52;c;aGk=\x07 there\n` }); 126+ if (path === "/p/abso-core/log") 130+ { error: `too many signed-out reads from this address: 120 a minute; sign in, or try again ${ESC}[2Jlater` }, 131+ { "Retry-After": "60" }, 133+ if (path === "/p/abso-core/where") 134+ return res.writeHead(302, { location: `${elsewhereUrl}/p/abso-core/where` }).end(); 135+ // A private project answers 401 with a body that looks like a status: only the code counts. 136+ if (path === "/p/private/status") return json(res, 401, { version: 1, agents: [] }); 137+ if (path === "/p/forbidden/status") return json(res, 403, { error: "members only" }); 138+ if (path === "/p/missing/status") return json(res, 404, { error: "no such project" }); 139+ json(res, 401, { error: "sign in" }); 141+ await new Promise<void>((done) => site.listen(0, "127.0.0.1", done)); 142+ url = `http://127.0.0.1:${(site.address() as AddressInfo).port}`; 147+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); 150+/** Runs the client as its own process, in `cwd`, with `home` as its home and only the environment given. */ 155+ extra: Record<string, string> = {}, 156+): Promise<{ code: number; stdout: string; stderr: string }> { 157+ const env: Record<string, string> = { 158+ PATH: process.env.PATH ?? "", 161+ AVCS_SERVERS_FILE: "no-servers.json", 162+ ABSO_ISSUES_SERVER: url, 165+ if (process.env.SystemRoot) env.SystemRoot = process.env.SystemRoot; 166+ return new Promise((done) => { 167+ execFile(process.execPath, [CLIENT, ...args], { cwd, env }, (error, stdout, stderr) => 168+ done({ code: typeof error?.code === "number" ? error.code : 0, stdout, stderr }), 173+/** A visitor folder made by abso join, signed out, and the home it was made in. */ 174+async function joined(): Promise<{ root: string; home: string; out: string }> { 175+ const home = temp("home"); 176+ // In a parent of its own, so a test can tell nothing was written beside it. 177+ const root = join(temp("parent"), "folder"); 179+ const run = await client(root, home, ["join", "abso-core", "--reader", "--server", url]); 180+ assert.equal(run.code, 0, run.stderr); 181+ return { root, home, out: run.stdout }; 184+describe("a visitor folder", () => { 185+ it("join --reader, signed out, to a public project writes only its config, from the command line", async () => { 186+ const { root, out } = await joined(); 187+ assert.match(out, /Joined abso-core to read it signed out, at version 3/); 188+ assert.deepEqual(readdirSync(root), [".abso"]); 189+ assert.deepEqual(readdirSync(join(root, ".abso")), ["config.json"]); 190+ // The status answer named another server; the config keeps the one typed. 191+ assert.deepEqual(JSON.parse(readFileSync(join(root, ".abso", "config.json"), "utf8")), { 193+ project: "abso-core", 198+ it("sends no Authorization and no cookie, with a token set and a box sign-in present, and follows no redirect", async () => { 199+ const { root, home } = await joined(); 204+ credential: CREDENTIAL, 205+ grant: { projects: [{ project: "abso-core", role: "writer" }] }, 206+ expiresAt: Date.now() + 86_400_000, 210+ const tokens = { ABSO_TOKEN: TOKEN, AVCS_TOKEN: TOKEN }; 213+ assert.equal((await client(root, home, ["status"], tokens)).code, 0); 214+ assert.equal((await client(root, home, ["show", "1:a.txt"], tokens)).code, 0); 215+ const where = await client(root, home, ["where"], tokens); 216+ assert.notEqual(where.code, 0); 217+ assert.ok(heard.length >= 3); 218+ for (const { headers } of heard) { 219+ assert.equal(headers.authorization, undefined); 220+ assert.equal(headers.cookie, undefined); 221+ assert.doesNotMatch(JSON.stringify(headers), /never-sent/); 223+ assert.equal(elsewhereHeard, 0); 226+ it("asks fetch to follow no redirect and sends no credential, join's public check too (a fetch spy)", async () => { 227+ const root = temp("spy"); 228+ writeConfig(root, { server: url, project: "abso-core", agent: "", visitor: true }); 229+ const real = globalThis.fetch; 230+ const calls: RequestInit[] = []; 231+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { 232+ calls.push(init ?? {}); 233+ return new Response(JSON.stringify({ version: 3, agents: [] }), { status: 200 }); 236+ const out = await main(["status"], { cwd: root, env: { ABSO_TOKEN: TOKEN }, write: () => {} }); 237+ assert.equal(out.exit, 0, out.stderr); 238+ assert.equal(await isPublic(url, "abso-core"), true); 240+ globalThis.fetch = real; 242+ assert.equal(calls.length, 2); 243+ for (const init of calls) { 244+ assert.equal(init.redirect, "error"); 245+ const headers = new Headers(init.headers); 246+ assert.equal(headers.get("authorization"), null); 247+ assert.equal(headers.get("cookie"), null); 251+ it("join answers a private project, a members-only one and a missing one alike, by the code alone", async () => { 253+ for (const project of ["private", "forbidden", "missing"]) { 254+ const root = temp("closed"); 255+ runs.push({ root, ...(await client(root, temp("home"), ["join", project, "--reader", "--server", url])) }); 257+ for (const run of runs) { 258+ assert.equal(run.code, runs[0]!.code); 259+ assert.notEqual(run.code, 0); 260+ assert.equal(run.stderr, runs[0]!.stderr); 261+ assert.equal(existsSync(join(run.root, ".abso")), false); 263+ assert.match(runs[0]!.stderr, /isn't signed in to .*abso login signs it in/); 266+ it("every request its Api makes goes through one send: reads only, no redirect, no sign-in", async () => { 267+ const real = globalThis.fetch; 268+ const calls: RequestInit[] = []; 269+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { 270+ calls.push(init ?? {}); 271+ return new Response("{}", { status: 200 }); 274+ const visitor = new Api({ server: url, project: "abso-core", agent: "", visitor: true, token: TOKEN }); 275+ await visitor.send(`${url}/p/abso-core/serve`, { headers: visitor.headers() }); 276+ await assert.rejects(visitor.send(`${url}/p/abso-core/a/x/run`, { method: "POST" }), /sends only reads/); 277+ const member = new Api({ server: url, project: "abso-core", agent: "x", token: TOKEN }); 278+ await member.send(`${url}/p/abso-core/serve`, { headers: member.headers() }); 280+ globalThis.fetch = real; 282+ assert.equal(calls.length, 2); 283+ assert.equal(calls[0]!.redirect, "error"); 284+ assert.equal(new Headers(calls[0]!.headers).get("authorization"), null); 285+ assert.equal(calls[1]!.redirect, undefined); 286+ assert.equal(new Headers(calls[1]!.headers).get("authorization"), `Bearer ${TOKEN}`); 289+ it("runs only its reads: every other command is refused before any call, and a new command fails here", async () => { 290+ const sorted = new Set([...Object.keys(VISITOR_READS), ...VISITOR_ELSEWHERE, ...REFUSED]); 291+ for (const name of Object.keys(commandTable())) 294+ `abso ${name} is new: add it to VISITOR_READS if it only reads, else to REFUSED here`, 296+ const root = temp("refuse"); 297+ writeConfig(root, { server: url, project: "abso-core", agent: "", visitor: true }); 298+ const real = globalThis.fetch; 300+ globalThis.fetch = (async () => { 302+ return new Response("{}", { status: 200 }); 306+ ...REFUSED.map((c) => [c]), 307+ ["issue", "new", "a title"], 308+ ["issue", "3", "--comment", "hi"], 309+ ["issues", "--drafts"], 310+ ["blame", "a.txt", "--mine"], 312+ for (const argv of tries) { 313+ const out = await main(argv, { cwd: root, env: { ABSO_TOKEN: TOKEN }, write: () => {} }); 314+ assert.notEqual(out.exit, 0, argv.join(" ")); 315+ assert.match(out.stderr, /This folder reads abso-core signed out\. To work on it: abso login/, argv.join(" ")); 318+ globalThis.fetch = real; 320+ assert.equal(calls, 0); 323+ it("prints what comes back through the terminal filter, a 429's text too", async () => { 324+ const { root, home } = await joined(); 325+ const show = await client(root, home, ["show", "1:a.txt"]); 326+ assert.equal(show.code, 0, show.stderr); 327+ assert.doesNotMatch(show.stdout, /\x1b/); 328+ assert.match(show.stdout, /hi \\x1b\]52;c;aGk=\\x07 there/); 329+ const log = await client(root, home, ["log"]); 330+ assert.notEqual(log.code, 0); 331+ assert.doesNotMatch(log.stderr + log.stdout, /\x1b/); 332+ assert.match(log.stderr, /too many signed-out reads from this address/); 335+ it("show prints a file and writes nothing, even for a path outside the folder", async () => { 336+ const { root, home } = await joined(); 337+ const parent = resolve(root, ".."); 338+ const before = { here: readdirSync(root).sort(), above: readdirSync(parent).sort() }; 339+ await client(root, home, ["show", "1:a.txt"]); 340+ const outside = await client(root, home, ["show", "1:../x"]); 341+ assert.notEqual(outside.code, 0); 342+ assert.deepEqual(readdirSync(root).sort(), before.here); 343+ assert.deepEqual(readdirSync(parent).sort(), before.above); 344+ assert.equal(existsSync(join(parent, "x")), false);