- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/box.test.ts?version=182&format=json
421 linesFirst import 44% · codex-mac-1 21% · speed 16% · trials 11% · pinch 6% · open 2% · review 1%Last change open in version 171, 10 versions changed it
You're reading version 182. The newest is 318, and 2 versions since then changed this file.
1// Signing in once per box (abso issue 108): login waits for approval and keeps
2// the credential outside every project folder; it never shows up in output and
3// only goes to the server that issued it.
5import assert from "node:assert/strict";
6import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
7import { tmpdir } from "node:os";
8import { join } from "node:path";
9import { test } from "node:test";
10import { parseArgs } from "../src/args.ts";
11import {
12 boxPublic,
13 boxText,
14 forgetBox,
15 login,
16 loginRequest,
17 logout,
18 mintFreeName,
19 mintKey,
20 readBox,
21 signedInServers,
22 writeBox,
23} from "../src/box.ts";
24import { serverFrom } from "../src/join-commands.ts";
25import { main } from "../src/main.ts";
27const SERVER = "https://staging.abso.example";
28const CREDENTIAL = "abso_bx_the-secret-credential";
29const grant = {
30 projects: [
31 { project: "abso", role: "writer" },
32 { project: "game", role: "reader" },
33 ],
34};
35const EXPIRES = "2026-10-15T00:00:00.000Z";
36const record = { server: SERVER, id: "b_0123abcd", credential: CREDENTIAL, grant, expiresAt: Date.parse(EXPIRES) };
38const home = () => mkdtempSync(join(tmpdir(), "abso-box-"));
40type Seen = { url: string; auth: string | null; body: unknown }[];
41function server(answers: [number, unknown][], seen: Seen): typeof fetch {
42 return (async (url, init) => {
43 seen.push({
44 url: String(url),
45 auth: new Headers(init?.headers).get("authorization"),
46 body: JSON.parse(String(init?.body ?? "null")),
47 });
48 const [status, body] = answers.shift() ?? [500, { error: "no more answers" }];
49 return new Response(JSON.stringify(body), { status });
50 }) as typeof fetch;
51}
53const started = {
54 device_code: "device-code-long-enough",
55 user_code: "WXYZ-BCDF",
56 verification_uri_complete: "https://abso.dev/login/box?code=WXYZ-BCDF",
57 expires_in: 60,
58 interval: 2,
59};
61function clock() {
62 let t = 0;
63 return {
64 sleep: async (ms: number) => {
65 t += ms;
66 },
67 now: () => t,
68 slept: () => t,
69 };
70}
72test("login grant options validate project lists, roles and duration", () => {
73 const request = (...words: string[]) =>
74 loginRequest(
75 parseArgs("login", words, {
76 projects: "string",
77 role: "string",
78 days: "string",
79 }),
80 );
81 assert.equal(request(), undefined);
82 assert.deepEqual(request("--projects", "alpha, beta,alpha", "--days", "30"), {
83 projects: [
84 { project: "alpha", role: "writer" },
85 { project: "beta", role: "writer" },
86 ],
87 days: 30,
88 });
89 assert.deepEqual(request("--projects", "alpha", "--role", "reader"), {
90 projects: [{ project: "alpha", role: "reader" }],
91 });
92 assert.deepEqual(request("--projects", "alpha", "--role", "owner"), {
93 projects: [{ project: "alpha", role: "owner" }],
94 });
95 assert.deepEqual(request("--days", "90"), { days: 90 });
96 for (const words of [
97 ["--role", "writer"],
98 ["--projects", ""],
99 ["--projects", "alpha,"],
100 ["--projects", "../alpha"],
101 ["--projects", "alpha", "--role", "admin"],
102 ["--projects", Array.from({ length: 101 }, (_, i) => `p${i}`).join(",")],
103 ])
104 assert.throws(() => request(...words));
105 for (const value of ["0", "-1", "1.5", "1e1", "Infinity", "100", "abc", ""])
106 assert.throws(() => request("--days", value));
107});
109test("login sends requested grants only at device start and retains the user's actual approval", async () => {
110 const h = home();
111 const seen: Seen = [];
112 const c = clock();
113 const requested = { projects: [{ project: "abso", role: "owner" as const }], days: 90 };
114 const approved = { projects: [{ project: "abso", role: "reader" }] };
115 const got = await login(
116 SERVER,
117 {
118 request: requested,
119 fetch: server(
120 [
121 [200, started],
122 [400, { error: "authorization_pending" }],
123 [200, { box_id: "b_test", box_token: CREDENTIAL, expires_at: EXPIRES, grant: approved }],
124 ],
125 seen,
126 ),
127 sleep: c.sleep,
128 now: c.now,
129 say: () => {},
130 },
131 h,
132 );
133 assert.ok(seen[0]);
134 assert.deepEqual((seen[0].body as Record<string, unknown>).requested_grant, requested);
135 assert.deepEqual(
136 seen.slice(1).map((call) => call.body),
137 [{ device_code: started.device_code }, { device_code: started.device_code }],
138 );
139 assert.deepEqual(got.grant, approved);
140 assert.deepEqual(readBox(SERVER, h)?.grant, approved);
141});
143test("invalid login grant flags fail before a network request through the CLI", async () => {
144 const original = globalThis.fetch;
145 let calls = 0;
146 globalThis.fetch = (async () => {
147 calls++;
148 throw new Error("unexpected request");
149 }) as typeof fetch;
150 try {
151 const result = await main(["login", "--projects", "alpha", "--days", "0", "--no-browser"], {
152 cwd: home(),
153 env: {},
154 write: () => {},
155 });
156 assert.equal(result.exit, 1);
157 assert.match(result.stderr, /--days is from 1 to 90/);
158 assert.equal(calls, 0);
159 } finally {
160 globalThis.fetch = original;
161 }
162});
164test("login shows the code, waits while it's pending, and keeps the credential in the user folder", async () => {
165 const h = home();
166 const seen: Seen = [];
167 const said: string[] = [];
168 const c = clock();
169 const got = await login(
170 `${SERVER}/some/path`,
171 {
172 fetch: server(
173 [
174 [200, started],
175 [400, { error: "authorization_pending" }],
176 [400, { error: "slow_down" }],
177 [200, { box_id: "b_0123abcd", box_token: CREDENTIAL, expires_at: EXPIRES, grant }],
178 ],
179 seen,
180 ),
181 sleep: c.sleep,
182 now: c.now,
183 say: (line) => said.push(line),
184 },
185 h,
186 );
187 assert.equal(got.server, SERVER);
188 assert.deepEqual(
189 seen.map((s) => s.url),
190 [`${SERVER}/login/device`, `${SERVER}/login/token`, `${SERVER}/login/token`, `${SERVER}/login/token`],
191 );
192 assert.deepEqual(seen[1]?.body, { device_code: "device-code-long-enough" });
193 assert.equal(c.slept(), 2000 + 2000 + 7000, "slow_down adds 5 s to the wait");
194 assert.ok(
195 seen.every((s) => s.auth === null),
196 "nothing is sent with login's calls",
197 );
198 assert.deepEqual(said, [
199 "To sign this box in, open https://abso.dev/login/box?code=WXYZ-BCDF and approve the code WXYZ-BCDF.",
200 "Waiting for approval. Ctrl-C stops waiting, and abso stops by itself when the code runs out.",
201 ]);
202 assert.equal(readBox(SERVER, h)?.credential, CREDENTIAL);
203 const files = readdirSync(join(h, ".abso", "boxes"));
204 assert.equal(files.length, 1);
205 assert.ok(readFileSync(join(h, ".abso", "boxes", files[0]!), "utf8").includes(CREDENTIAL));
206 assert.equal(boxText(got, SERVER, 0).includes(CREDENTIAL), false);
207 assert.match(boxText(got, SERVER, 0), /abso \(writer\), game \(reader\)\.\n/);
208 assert.doesNotMatch(boxText(got, SERVER, 0), /agents/);
209 assert.equal(JSON.stringify(boxPublic(got)).includes(CREDENTIAL), false);
210});
212test("login opens the approve page with the code in it, and prints the link and code all the same", async () => {
213 const said: string[] = [];
214 const opened: string[] = [];
215 const c = clock();
216 await login(
217 SERVER,
218 {
219 fetch: server(
220 [
221 [200, started],
222 [200, { box_id: "b_0123abcd", box_token: CREDENTIAL, expires_at: EXPIRES, grant }],
223 ],
224 [],
225 ),
226 sleep: c.sleep,
227 now: c.now,
228 say: (line) => said.push(line),
229 open: (url) => (opened.push(url), true),
230 },
231 home(),
232 );
233 assert.deepEqual(opened, ["https://abso.dev/login/box?code=WXYZ-BCDF"]);
234 assert.deepEqual(said.slice(0, 2), [
235 "Opening the approve page in your browser.",
236 "To sign this box in, open https://abso.dev/login/box?code=WXYZ-BCDF and approve the code WXYZ-BCDF.",
237 ]);
238});
240test("an open that doesn't start says nothing about a browser, and the printed link stands", async () => {
241 const said: string[] = [];
242 const c = clock();
243 await login(
244 SERVER,
245 {
246 fetch: server(
247 [
248 [200, started],
249 [200, { box_id: "b_0123abcd", box_token: CREDENTIAL, expires_at: EXPIRES, grant }],
250 ],
251 [],
252 ),
253 sleep: c.sleep,
254 now: c.now,
255 say: (line) => said.push(line),
256 open: () => false,
257 },
258 home(),
259 );
260 assert.equal(
261 said[0],
262 "To sign this box in, open https://abso.dev/login/box?code=WXYZ-BCDF and approve the code WXYZ-BCDF.",
263 );
264 assert.equal(
265 said.some((l) => l.includes("browser")),
266 false,
267 );
268});
270test("a code that's turned down or runs out says so and keeps nothing", async () => {
271 const h = home();
272 const c = clock();
273 const io = { sleep: c.sleep, now: c.now, say: () => {} };
274 await assert.rejects(
275 login(
276 SERVER,
277 {
278 ...io,
279 fetch: server(
280 [
281 [200, started],
282 [400, { error: "access_denied" }],
283 ],
284 [],
285 ),
286 },
287 h,
288 ),
289 /was turned down/,
290 );
291 await assert.rejects(
292 login(
293 SERVER,
294 {
295 ...io,
296 fetch: server(
297 [
298 [200, started],
299 [400, { error: "expired_token" }],
300 ],
301 [],
302 ),
303 },
304 h,
305 ),
306 /ran out\. Run abso login again/,
307 );
308 await assert.rejects(
309 login(
310 SERVER,
311 {
312 ...io,
313 fetch: server(
314 [
315 [200, { ...started, expires_in: 3 }],
316 [400, { error: "authorization_pending" }],
317 [400, { error: "authorization_pending" }],
318 ],
319 [],
320 ),
321 },
322 h,
323 ),
324 /in time\. Run abso login again/,
325 );
326 assert.equal(readBox(SERVER, h), undefined);
327});
329test("login says it's still waiting about once a minute, and stops in the end whatever the server says", async () => {
330 const c = clock();
331 const said: string[] = [];
332 const pending = Array.from({ length: 2000 }, (): [number, unknown] => [400, { error: "authorization_pending" }]);
333 await assert.rejects(
334 login(
335 SERVER,
336 {
337 fetch: server([[200, { ...started, expires_in: 10 ** 9, interval: 5 }], ...pending], []),
338 sleep: c.sleep,
339 now: c.now,
340 say: (line) => said.push(line),
341 },
342 home(),
343 ),
344 /nobody approved the code WXYZ-BCDF in time\. Run abso login again\./,
345 );
346 assert.equal(c.slept(), 30 * 60 * 1000, "a server that says never still gets an end");
347 const still = said.filter((line) => line === "Still waiting for the code WXYZ-BCDF to be approved.");
348 assert.equal(still.length, 30);
349 assert.equal(said.length, 2 + 30);
350});
352test("a key is minted with the box credential, sent only to the box's own server", async () => {
353 const seen: Seen = [];
354 const minted = await mintKey(
355 record,
356 "abso",
357 "tester-1",
358 server([[200, { key: "abso_sk_x", id: "k_0123abcd" }]], seen),
359 );
360 assert.deepEqual(minted, { key: "abso_sk_x", id: "k_0123abcd" });
361 assert.equal(seen[0]?.url.startsWith(`${SERVER}/`), true);
362 assert.equal(seen[0]?.auth, `Box ${CREDENTIAL}`);
363 await assert.rejects(
364 mintKey(record, "secret-project", "a", server([[403, { error: `outside the grant ${CREDENTIAL}` }]], [])),
365 (e: Error) => /refused \(403\)/.test(e.message) && !e.message.includes(CREDENTIAL),
366 );
367});
369test("a box's sign-in is kept per server, and logout forgets it even when the server is down", async () => {
370 const h = home();
371 writeBox(record, h);
372 assert.equal(readBox("https://abso.example", h), undefined, "another server's box isn't this one");
373 assert.match(boxText(undefined, SERVER), /isn't signed in/);
374 const down = (async () => {
375 throw new Error("offline");
376 }) as typeof fetch;
377 assert.equal(await logout(readBox(SERVER, h)!, down, h), false);
378 assert.equal(readBox(SERVER, h), undefined);
379 assert.equal(forgetBox(SERVER, h), false);
380});
382test("join and init pick the server in the one order: --server, the folder's, ABSO_SERVER, then prod", () => {
383 const h = home();
384 const outside = home();
385 const args = (server?: string) => ({ positionals: [], flags: new Map(server ? [["server", server]] : []) });
386 const none = { env: {}, cwd: outside };
387 assert.equal(serverFrom(args(), none), "https://api.abso.dev", "nothing named: prod");
388 writeBox({ ...record, expiresAt: Date.now() + 1e6 }, h);
389 assert.deepEqual(signedInServers(h), [SERVER]);
390 assert.equal(serverFrom(args(), none), "https://api.abso.dev", "a sign-in elsewhere doesn't pick the server");
391 assert.deepEqual(signedInServers(h, Date.now() + 2e6), [], "an expired sign-in doesn't count");
392 assert.equal(serverFrom(args(), { ...none, env: { ABSO_SERVER: "https://env.example" } }), "https://env.example");
393 assert.equal(
394 serverFrom(args("https://flag.example"), { ...none, env: { ABSO_SERVER: "https://env.example" } }),
395 "https://flag.example",
396 );
397 assert.equal(serverFrom(args(SERVER), none), SERVER, "--server is used as given");
398});
400test("join with no --agent takes the box's name, skips names this box holds, and moves past a taken one", async () => {
401 const seen: Seen = [];
402 const fetcher = server(
403 [
404 [200, { box_id: record.id, agents: [{ project: "abso", agent: "snow", key_id: "k_0" }] }],
405 [409, { error: "that agent name is already in use in this project; pick a new one" }],
406 [200, { key: "abso_sk_new", id: "k_3" }],
407 ],
408 seen,
409 );
410 const got = await mintFreeName(record, "abso", "snow", fetcher);
411 assert.deepEqual(got, { key: "abso_sk_new", id: "k_3", agent: "snow-3" });
412 assert.deepEqual(
413 seen.map((s) => [new URL(s.url).pathname, (s.body as { agent?: string } | null)?.agent ?? null]),
414 [
415 ["/box", null],
416 ["/box/agent-key", "snow-2"],
417 ["/box/agent-key", "snow-3"],
418 ],
419 "snow is this box's already: never minted again, which would replace its key",
420 );
421});