- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/visitor.test.ts?format=json
346 linespinch 97% · groups 1% · rename 1% · autosettle 1% · open 1% · readspeed 1%Last change readspeed in version 261, 8 versions changed it
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.
11import assert from "node:assert/strict";
12import { execFile } from "node:child_process";
13import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
14import { createServer, type IncomingHttpHeaders, type Server } from "node:http";
15import type { AddressInfo } from "node:net";
16import { tmpdir } from "node:os";
17import { join, resolve } from "node:path";
18import { after, before, describe, it } from "node:test";
19import { Api } from "../src/api.ts";
20import { writeBox } from "../src/box.ts";
21import { writeConfig } from "../src/config.ts";
22import { isPublic } from "../src/join-commands.ts";
23import { commandTable, main } from "../src/main.ts";
24import { VISITOR_ELSEWHERE, VISITOR_READS } from "../src/visitor.ts";
26const CLIENT = resolve(import.meta.dirname, "..", "abso.ts");
27const ESC = "\x1b";
28const TOKEN = "abso_test-token-never-sent";
29const 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. */
32const REFUSED = [
33 "init",
34 "key",
35 "box",
36 "whoami",
37 "doctor",
38 "orgs",
39 "org",
40 // A project's groups are its members' to read and write; a visitor sees none.
41 "groups",
42 "group",
43 "skill",
44 "join",
45 "record",
46 "push",
47 "bisect",
48 "reader",
49 "settle",
50 "pull",
51 "run",
52 "serve",
53 "mv",
54 "review",
55 "note",
56 "notes",
57 "ask",
58 "waiting",
59 "answer",
60 "ack",
61 "reply",
62 "unqueue",
63 "visibility",
64 "autosettle",
65 "flag",
66 "ci",
67 "shot",
68 "prep",
69 "fetch",
70 "pause",
71 "resume",
72 "logs",
73 "switch",
74 "land",
75 "draft-pull",
76 "diff",
77 "restore",
78 "export",
79 "announce",
80 "start",
81 "news",
82 "fix-eol",
83 "who",
84 "drop",
85 "pluck",
86 "amend",
87 "label",
88 "labels",
89 "follow",
90 "check-ignore",
91 "pipeline",
92];
94let site: Server;
95let url: string;
96// Where the site's redirect points: a visitor never gets here.
97let elsewhere: Server;
98let elsewhereUrl: string;
99const heard: { url: string; headers: IncomingHttpHeaders }[] = [];
100let elsewhereHeard = 0;
101const dirs: string[] = [];
102const temp = (name: string) => {
103 const dir = mkdtempSync(join(tmpdir(), `abso-test-visitor-${name}-`));
104 dirs.push(dir);
105 return dir;
106};
108const json = (res: import("node:http").ServerResponse, status: number, body: unknown, headers = {}) =>
109 res.writeHead(status, { "content-type": "application/json", ...headers }).end(JSON.stringify(body));
111before(async () => {
112 elsewhere = createServer((_req, res) => {
113 elsewhereHeard++;
114 json(res, 200, { version: 9, agents: [] });
115 });
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")
127 return json(
128 res,
129 429,
130 { error: `too many signed-out reads from this address: 120 a minute; sign in, or try again ${ESC}[2Jlater` },
131 { "Retry-After": "60" },
132 );
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" });
140 });
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}`;
143});
144after(() => {
145 site.close();
146 elsewhere.close();
147 for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
148});
150/** Runs the client as its own process, in `cwd`, with `home` as its home and only the environment given. */
151function client(
152 cwd: string,
153 home: string,
154 args: string[],
155 extra: Record<string, string> = {},
156): Promise<{ code: number; stdout: string; stderr: string }> {
157 const env: Record<string, string> = {
158 PATH: process.env.PATH ?? "",
159 HOME: home,
160 USERPROFILE: home,
161 AVCS_SERVERS_FILE: "no-servers.json",
162 ABSO_ISSUES_SERVER: url,
163 ...extra,
164 };
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 }),
169 );
170 });
171}
173/** A visitor folder made by abso join, signed out, and the home it was made in. */
174async 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");
178 mkdirSync(root);
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 };
182}
184describe("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")), {
192 server: url,
193 project: "abso-core",
194 visitor: true,
195 });
196 });
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();
200 writeBox(
201 {
202 server: url,
203 id: "b_0123abcd",
204 credential: CREDENTIAL,
205 grant: { projects: [{ project: "abso-core", role: "writer" }] },
206 expiresAt: Date.now() + 86_400_000,
207 },
208 home,
209 );
210 const tokens = { ABSO_TOKEN: TOKEN, AVCS_TOKEN: TOKEN };
211 heard.length = 0;
212 elsewhereHeard = 0;
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/);
222 }
223 assert.equal(elsewhereHeard, 0);
224 });
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 });
234 }) as typeof fetch;
235 try {
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);
239 } finally {
240 globalThis.fetch = real;
241 }
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);
248 }
249 });
251 it("join answers a private project, a members-only one and a missing one alike, by the code alone", async () => {
252 const runs = [];
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])) });
256 }
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);
262 }
263 assert.match(runs[0]!.stderr, /isn't signed in to .*abso login signs it in/);
264 });
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 });
272 }) as typeof fetch;
273 try {
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() });
279 } finally {
280 globalThis.fetch = real;
281 }
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}`);
287 });
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()))
292 assert.ok(
293 sorted.has(name),
294 `abso ${name} is new: add it to VISITOR_READS if it only reads, else to REFUSED here`,
295 );
296 const root = temp("refuse");
297 writeConfig(root, { server: url, project: "abso-core", agent: "", visitor: true });
298 const real = globalThis.fetch;
299 let calls = 0;
300 globalThis.fetch = (async () => {
301 calls++;
302 return new Response("{}", { status: 200 });
303 }) as typeof fetch;
304 try {
305 const tries = [
306 ...REFUSED.map((c) => [c]),
307 ["issue", "new", "a title"],
308 ["issue", "3", "--comment", "hi"],
309 ["issues", "--drafts"],
310 ["blame", "a.txt", "--mine"],
311 ];
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(" "));
316 }
317 } finally {
318 globalThis.fetch = real;
319 }
320 assert.equal(calls, 0);
321 });
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/);
333 });
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);
345 });
346});