@coffre/conformance 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,14 +1,52 @@
1
1
  import { i as defaultGitHubAccount, n as DevIdp } from "./idp-DJlqS-JW.js";
2
- import { join, resolve } from "node:path";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
3
4
  import { inspect, parseArgs } from "node:util";
4
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
5
5
  import { spawn } from "node:child_process";
6
6
  import { createHash, createHmac, createPrivateKey, hkdfSync, randomBytes, randomUUID, sign } from "node:crypto";
7
7
  import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
8
8
  import { tmpdir } from "node:os";
9
+ import { setTimeout } from "node:timers/promises";
9
10
  import { DatabaseSync } from "node:sqlite";
10
11
  import pg from "pg";
11
12
  import { postgresConnection } from "@coffre/db/connect";
13
+ //#region src/database.ts
14
+ async function postgres(url) {
15
+ const client = new pg.Client(postgresConnection(url));
16
+ await client.connect();
17
+ return {
18
+ engine: "postgres",
19
+ query: async (statement, params = []) => (await client.query(statement, params)).rows,
20
+ exec: async (statements) => void await client.query(statements),
21
+ close: () => client.end()
22
+ };
23
+ }
24
+ /** A SQLite file, perhaps open in another process: it waits out their locks. */
25
+ function sqlite(file) {
26
+ const db = new DatabaseSync(file, { timeout: 5e3 });
27
+ return {
28
+ engine: "sqlite",
29
+ query: async (statement, params = []) => db.prepare(statement).all(...params),
30
+ exec: async (statements) => db.exec(statements),
31
+ close: async () => db.close()
32
+ };
33
+ }
34
+ async function using(open, use) {
35
+ const sql = await open;
36
+ try {
37
+ return await use(sql);
38
+ } finally {
39
+ await sql.close();
40
+ }
41
+ }
42
+ //#endregion
43
+ //#region src/fixtures.ts
44
+ const KEYS = {
45
+ VAULT_KEY_ID: "vault-conformance-1",
46
+ VAULT_KEY: "Y29mZnJlLWxvY2FsLWRldi1rZWstMzItYnl0ZXMhISE=",
47
+ APP_KEY: "Y29mZnJlLWxvY2FsLWF1ZGl0LWNoYWluLWtleS0zMmI="
48
+ };
49
+ //#endregion
12
50
  //#region ../client/dist/index.js
13
51
  /** The API's error shape, `{ error, message }`, with the HTTP status. */
14
52
  const COFFRE_ERROR = Symbol.for("@coffre/client:CoffreError");
@@ -163,73 +201,13 @@ set: (member, access) => call("PATCH /access/:member", { member }, access) },
163
201
  },
164
202
  audit: {
165
203
  list: (query = {}) => call("GET /audit", {}, query),
166
- verify: () => call("GET /audit/verification", {})
204
+ verify: () => call("GET /audit/verification", {}),
205
+ /** What an escrowed key is checked against: public material, owners and root admins only. */
206
+ keys: () => call("GET /audit/keys", {})
167
207
  }
168
208
  };
169
209
  }
170
210
  //#endregion
171
- //#region src/browser.ts
172
- var Browser = class {
173
- origin;
174
- #jar = /* @__PURE__ */ new Map();
175
- constructor(origin) {
176
- this.origin = origin;
177
- }
178
- /** Whether coffre left this browser a cookie. */
179
- get hasCookies() {
180
- return this.#jar.size > 0;
181
- }
182
- /**
183
- * A request as the browser makes it, cookies included, redirects not
184
- * followed. Nothing else is added: a caller playing another site's page
185
- * sets its own `origin`.
186
- */
187
- async fetch(path, init = {}) {
188
- const request = typeof path === "string" ? new Request(new URL(path, this.origin), init) : path;
189
- const ours = new URL(request.url).origin === this.origin;
190
- if (ours && this.#jar.size > 0) request.headers.set("cookie", [...this.#jar].map(([name, value]) => `${name}=${value}`).join("; "));
191
- const response = await fetch(request, { redirect: "manual" });
192
- if (ours) for (const cookie of response.headers.getSetCookie()) {
193
- const [pair = ""] = cookie.split(";");
194
- const at = pair.indexOf("=");
195
- const value = pair.slice(at + 1);
196
- if (value === "" || /max-age=0/i.test(cookie)) this.#jar.delete(pair.slice(0, at));
197
- else this.#jar.set(pair.slice(0, at), value);
198
- }
199
- return response;
200
- }
201
- /** A call one of coffre's pages makes: JSON, from its own origin. */
202
- send(method, path, body) {
203
- return this.fetch(path, {
204
- method,
205
- headers: {
206
- origin: this.origin,
207
- "sec-fetch-site": "same-origin",
208
- "content-type": "application/json"
209
- },
210
- body: body === void 0 ? void 0 : JSON.stringify(body)
211
- });
212
- }
213
- /** The API as this browser's pages call it. */
214
- client() {
215
- return createClient({
216
- url: this.origin,
217
- transport: (request) => {
218
- request.headers.set("origin", this.origin);
219
- request.headers.set("sec-fetch-site", "same-origin");
220
- return this.fetch(request);
221
- }
222
- });
223
- }
224
- };
225
- /** The API as the CLI or a service calls it, with a bearer token. */
226
- function bearer(origin, token) {
227
- return createClient({
228
- url: origin,
229
- headers: () => ({ authorization: `Bearer ${token}` })
230
- });
231
- }
232
- //#endregion
233
211
  //#region src/report.ts
234
212
  /** A check that failed: what went wrong, and what was seen instead. */
235
213
  var Failure = class extends Error {
@@ -259,26 +237,19 @@ async function until(what, probe, seconds, alive = () => true) {
259
237
  for (let i = 0; i < seconds * 10; i++) {
260
238
  if (!alive()) throw new Failure(`a process exited while waiting for ${what}`);
261
239
  if (await probe().catch(() => false)) return;
262
- await setTimeout$1(100);
240
+ await setTimeout(100);
263
241
  }
264
242
  throw new Failure(`timed out waiting for ${what}`);
265
243
  }
266
244
  var Report = class {
267
245
  #results = [];
268
246
  #width;
269
- #quiet;
270
- /** `quiet`: keep the lines rather than print them, for a check made of checks to sum up. */
271
- constructor(width = 19, quiet = false) {
247
+ constructor(width = 19) {
272
248
  this.#width = width;
273
- this.#quiet = quiet;
274
249
  }
275
250
  get failed() {
276
251
  return this.#results.filter((result) => result.status === "FAIL").map((result) => result.name);
277
252
  }
278
- /** Each check's name, what came of it, and its line. */
279
- get results() {
280
- return this.#results;
281
- }
282
253
  /**
283
254
  * Run one check, and print what came of it. `needs` holds what earlier
284
255
  * checks produced: if any is missing, this one is skipped rather than run
@@ -307,10 +278,8 @@ var Report = class {
307
278
  #print(name, status, line, detail) {
308
279
  this.#results.push({
309
280
  name,
310
- status,
311
- line
281
+ status
312
282
  });
313
- if (this.#quiet) return;
314
283
  const text = ` ${status.padEnd(5)} ${name.padEnd(this.#width)} ${line}`;
315
284
  if (status !== "FAIL") {
316
285
  console.log(text);
@@ -327,478 +296,277 @@ var Report = class {
327
296
  }
328
297
  };
329
298
  //#endregion
330
- //#region src/routes.ts
331
- function getCalls({ places, secrets, members, services }) {
332
- const first = places[0];
333
- return {
334
- "GET /me": [{ params: {} }],
335
- "GET /projects": [{ params: {} }],
336
- "GET /secrets/:project/:environment": places.map((params) => ({ params })),
337
- "GET /secrets/:project/:environment/:key/versions": secrets.map((params) => ({ params })),
338
- "GET /members": [{ params: {} }, ...first === void 0 ? [] : [{
339
- params: {},
340
- input: { path: `${first.project}/${first.environment}` }
341
- }]],
342
- "GET /members/:member": members.map((member) => ({ params: { member } })),
343
- "GET /members/:member/tokens": services.map((member) => ({ params: { member } })),
344
- "GET /sessions": [{ params: {} }],
345
- "GET /identities": [{ params: {} }],
346
- "GET /device-logins/:code": [{ params: { code: "BCDF-GHJK" } }],
347
- "GET /syncs/providers": [{ params: {} }],
348
- "GET /syncs/:project/:environment": places.map((params) => ({ params })),
349
- "GET /audit": [{
350
- params: {},
351
- input: { limit: 500 }
352
- }, {
353
- params: {},
354
- input: {
355
- limit: 500,
356
- detail: "1"
357
- }
358
- }],
359
- "GET /audit/verification": [{ params: {} }]
360
- };
361
- }
362
- /** Each GET call as a URL, with its parameters and query filled in. */
363
- function getUrls(origin, calls) {
364
- const urls = [];
365
- for (const [key, asks] of Object.entries(calls)) for (const { params, input } of asks) urls.push({
366
- key,
367
- url: address(origin, key, params, input)
368
- });
369
- return urls;
370
- }
371
- /** Every route, whatever its method. */
372
- const EVERY_ROUTE = {
373
- "GET /me": true,
374
- "GET /projects": true,
375
- "PUT /projects/:project": true,
376
- "PATCH /projects/:project": true,
377
- "PUT /projects/:project/:environment": true,
378
- "PATCH /projects/:project/:environment": true,
379
- "GET /secrets/:project/:environment": true,
380
- "PATCH /secrets/:project/:environment": true,
381
- "PATCH /secrets/:project/:environment/:key": true,
382
- "GET /secrets/:project/:environment/:key/versions": true,
383
- "POST /secrets/:project/:environment/:key/restore": true,
384
- "POST /reveals": true,
385
- "GET /members": true,
386
- "GET /members/:member": true,
387
- "PUT /members/:member": true,
388
- "DELETE /members/:member": true,
389
- "GET /members/:member/tokens": true,
390
- "POST /members/:member/tokens": true,
391
- "DELETE /members/:member/tokens/:id": true,
392
- "PATCH /access/:member": true,
393
- "GET /sessions": true,
394
- "DELETE /sessions/:id": true,
395
- "GET /identities": true,
396
- "DELETE /identities/:id": true,
397
- "GET /device-logins/:code": true,
398
- "POST /device-logins/:code": true,
399
- "GET /syncs/providers": true,
400
- "GET /syncs/:project/:environment": true,
401
- "POST /syncs/:project/:environment": true,
402
- "PATCH /syncs/by-id/:id": true,
403
- "DELETE /syncs/by-id/:id": true,
404
- "POST /syncs/by-id/:id/runs": true,
405
- "GET /audit": true,
406
- "GET /audit/verification": true
407
- };
408
- /**
409
- * Every route as a method and a URL, each parameter a made-up value: what
410
- * a caller with no right to any of them would send.
411
- */
412
- function everyRoute(origin) {
413
- return Object.keys(EVERY_ROUTE).map((key) => {
414
- const [method, pattern] = key.split(" ");
415
- return {
416
- key,
417
- method,
418
- url: `${origin}/api${pattern.replace(/:(\w+)/g, (_, name) => encodeURIComponent(name === "member" ? "token:conformance-nobody" : "conformance-nobody"))}`
299
+ //#region src/harness.ts
300
+ const ROOT_ADMIN = "root@conformance.example";
301
+ async function boot(kind, at, options) {
302
+ const { port } = options;
303
+ const dir = resolve(at);
304
+ const origin = `http://127.0.0.1:${port}`;
305
+ for (const taken of [
306
+ port,
307
+ port + 1,
308
+ port + 2
309
+ ]) if (await fetch(`http://127.0.0.1:${taken}/`).then(() => true, () => false)) throw new Failure(`port ${taken} is taken; pass --port for a free run of three`);
310
+ if (kind === "workers" && (options.postgres === void 0 || options.runtime === void 0 || options.vaultRuntime === void 0)) throw new Failure("workers run on Postgres: pass --postgres <owner URL>, --runtime <coffre_runtime URL> and --vault-runtime <coffre_vault_runtime URL>");
311
+ const scratch = mkdtempSync(join(tmpdir(), `coffre-conformance-${kind}-`));
312
+ const shell = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("COFFRE_")));
313
+ const children = [];
314
+ const output = (tail = Infinity) => children.map((entry) => `--- ${entry.name}\n${Buffer.concat(entry.output).toString("utf8").slice(-tail)}`).join("\n");
315
+ const logs = () => output(4e3);
316
+ const alive = () => !children.some((entry) => entry.daemon && entry.exited);
317
+ function start(name, command, args, env, daemon = true) {
318
+ const child = spawn(command, args, {
319
+ cwd: dir,
320
+ env: {
321
+ ...shell,
322
+ ...env
323
+ },
324
+ detached: true,
325
+ stdio: [
326
+ "ignore",
327
+ "pipe",
328
+ "pipe"
329
+ ]
330
+ });
331
+ const entry = {
332
+ name,
333
+ child,
334
+ daemon,
335
+ exited: false,
336
+ output: []
419
337
  };
420
- });
421
- }
422
- function address(origin, key, params, input) {
423
- const path = key.slice(4).replace(/:(\w+)/g, (_, name) => encodeURIComponent(params[name]));
424
- const url = new URL(`${origin}/api${path}`);
425
- for (const [name, value] of Object.entries(input ?? {})) url.searchParams.set(name, String(value));
426
- return url.href;
427
- }
428
- //#endregion
429
- //#region src/checks/surface.ts
430
- async function health(deployment) {
431
- const { origin } = deployment;
432
- const live = await fetch(`${origin}/livez`);
433
- expect(live.ok, `/livez answered ${live.status}`);
434
- if (deployment.beforeFirstBeat) {
435
- const early = await fetch(`${origin}/readyz`);
436
- expect(early.status === 503, `/readyz answered ${early.status} before any heartbeat`, await early.text());
437
- await deployment.scheduled();
438
- }
439
- await until("/readyz", async () => (await fetch(`${origin}/readyz`)).ok, 20);
440
- const ready = await (await fetch(`${origin}/readyz`)).json();
441
- expect(ready.checkpointed === true, "/readyz passed without a checkpoint covering the heartbeat", ready);
442
- return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
443
- }
444
- /** An instance someone else runs: up, and its scheduled job beating. */
445
- async function reachable(origin) {
446
- const live = await fetch(`${origin}/livez`);
447
- expect(live.ok, `/livez answered ${live.status}`);
448
- const ready = await fetch(`${origin}/readyz`);
449
- expect(ready.ok, `/readyz answered ${ready.status}: is the scheduled job running?`, await ready.text());
450
- return "/livez and /readyz";
451
- }
452
- async function headers(origin) {
453
- const anonymous = await fetch(`${origin}/api/me`);
454
- expect(anonymous.status === 401, `/api/me answered ${anonymous.status} to no one`);
455
- securityHeaders(anonymous, "a refusal");
456
- const login = await fetch(`${origin}/login`);
457
- expect(login.status === 200, `/login answered ${login.status}`);
458
- const csp = securityHeaders(login, "/login");
459
- const html = await login.text();
460
- const nonce = /'nonce-([^']+)'/.exec(csp)[1];
461
- expect(html.includes(`nonce="${nonce}"`), "/login's scripts do not carry the policy's nonce");
462
- expect(!securityHeaders(await fetch(`${origin}/login`), "/login").includes(`'nonce-${nonce}'`), "two pages were served with the same nonce");
463
- const asset = /\/_coffre\/assets\/[\w.-]+\.js/.exec(html)?.[0];
464
- expect(asset !== void 0, "/login loads no script from /_coffre/assets/", html.slice(0, 2e3));
465
- const script = await fetch(`${origin}${asset}`);
466
- expect(script.ok && /javascript/.test(script.headers.get("content-type") ?? ""), `${asset} answered ${script.status} ${script.headers.get("content-type")}`);
467
- const allowed = (await fetch(`${origin}/api/me`, { headers: { origin: "https://attacker.example" } })).headers.get("access-control-allow-origin");
468
- expect(allowed === null, `the API allows another origin to read it: ${allowed}`);
469
- return `a fresh CSP nonce per page, frames refused, nosniff; no CORS; ${asset} served`;
470
- }
471
- function securityHeaders(response, what) {
472
- const csp = response.headers.get("content-security-policy") ?? "";
473
- expect(/script-src 'self' 'nonce-[^']+'/.test(csp), `${what}: no nonce-based script-src`, csp);
474
- expect(csp.includes("frame-ancestors 'none'"), `${what}: frames not refused`, csp);
475
- expect(response.headers.get("x-content-type-options") === "nosniff", `${what}: no nosniff`);
476
- expect(response.headers.get("x-frame-options") === "DENY", `${what}: no x-frame-options DENY`);
477
- expect(response.headers.get("cross-origin-resource-policy") === "same-origin", `${what}: other sites may embed it`);
478
- expect(/no-store/.test(response.headers.get("cache-control") ?? ""), `${what}: may be cached`);
479
- if (response.url.startsWith("https:")) {
480
- const hsts = response.headers.get("strict-transport-security") ?? "";
481
- expect(/max-age=\d{7,}/.test(hsts), `${what}: no strict-transport-security for months or more`, hsts);
482
- }
483
- return csp;
484
- }
485
- //#endregion
486
- //#region src/checks/live.ts
487
- /** The page anyone may open. Every other page sends no one to /login. */
488
- const OPEN_PAGES = ["/login"];
489
- /** The pages behind sign-in, whatever the instance holds. */
490
- const CLOSED_PAGES = [
491
- "/",
492
- "/account",
493
- "/access",
494
- "/audit",
495
- "/auth/device",
496
- "/settings",
497
- "/projects",
498
- "/users",
499
- "/tokens",
500
- "/unregistered"
501
- ];
502
- /** A made-up place and member, which no instance has. */
503
- const NOWHERE = {
504
- project: "conformance-nowhere",
505
- environment: "none"
506
- };
507
- const NOBODY = "token:conformance-nobody";
508
- /** Parse `<project>/<environment>/<KEY>=<value>`, or the path alone with the value given apart. */
509
- function parseCanary(text, value) {
510
- const at = text.indexOf("=");
511
- const path = at === -1 ? text : text.slice(0, at);
512
- const given = at === -1 ? value : text.slice(at + 1);
513
- const parts = path.split("/");
514
- if (parts.length !== 3 || parts.some((part) => part === "")) throw new Error(`the canary is <project>/<environment>/<KEY>, not "${path}"`);
515
- if (given === void 0 || given === "") throw new Error("the canary has no value: pass it after =, on stdin, or in COFFRE_CONFORMANCE_CANARY");
516
- const [project, environment, key] = parts;
517
- return {
518
- project,
519
- environment,
520
- key,
521
- value: given
522
- };
523
- }
524
- /** The checks anyone can run: no sign-in, nothing written. `health` false when the caller checked it already. */
525
- async function anonymousChecks(report, origin, options) {
526
- if (options.health) await report.check("health", {}, () => reachable(origin));
527
- await report.check("headers", {}, () => headers(origin));
528
- await report.check("anonymous api", {}, () => anonymousApi(origin));
529
- await report.check("forged cross-site", {}, () => forgedCrossSite(origin));
530
- await report.check("sign-in info", {}, () => signinInfo(origin));
531
- await report.check("anonymous answers", {}, () => anonymousAnswers(origin));
532
- }
533
- /** The checks with a service token that reads the canary, and audits its project. `prefix` names them apart, run twice. */
534
- async function tokenChecks(report, origin, setup, prefix = "") {
535
- const api = setup.token === void 0 ? void 0 : bearer(origin, setup.token);
536
- const token = await report.check(`${prefix}token`, {
537
- api,
538
- canary: setup.canary
539
- }, ({ api, canary }) => whoIsToken(origin, api, canary));
540
- const needs = {
541
- api,
542
- canary: setup.canary,
543
- token,
544
- secret: setup.token
545
- };
546
- await report.check(`${prefix}token reveal`, needs, ({ api, canary, token }) => tokenReveal(api, canary, token));
547
- await report.check(`${prefix}token scan`, needs, ({ canary, secret }) => tokenScan(origin, secret, canary));
548
- await report.check(`${prefix}token scope`, needs, ({ api, canary }) => tokenScope(api, canary));
549
- await report.check(`${prefix}token verification`, { api }, ({ api }) => tokenVerification(api));
550
- }
551
- /** Every route, whatever its method, turns away a caller with no credential, and says nothing else. */
552
- async function anonymousApi(origin) {
553
- const routes = everyRoute(origin);
554
- for (const { key, method, url } of routes) {
555
- const response = await fetch(url, {
556
- method,
557
- headers: { "content-type": "application/json" },
558
- body: method === "GET" ? void 0 : "{}"
338
+ child.stdout.on("data", (chunk) => entry.output.push(chunk));
339
+ child.stderr.on("data", (chunk) => entry.output.push(chunk));
340
+ child.once("exit", () => entry.exited = true);
341
+ child.once("error", (error) => {
342
+ entry.output.push(Buffer.from(`${error.message}\n`));
343
+ entry.exited = true;
559
344
  });
560
- const text = await response.text();
561
- expect(response.status === 401, `${key} answered ${response.status} to no one`, text);
562
- expect(onlyRefusal(text), `${key} refused no one with more than a refusal`, text);
345
+ children.push(entry);
346
+ return entry;
563
347
  }
564
- return `${routes.length} routes, every method: 401, and nothing but the refusal`;
565
- }
566
- /**
567
- * A change sent with a session cookie from another site's page is refused
568
- * before the cookie is even looked at, so a made-up one shows it: a real
569
- * cookie would get the same answer. Behind Cloudflare Access the same holds
570
- * for its cookie and assertion.
571
- */
572
- async function forgedCrossSite(origin) {
573
- const changes = everyRoute(origin).filter((route) => route.method !== "GET");
574
- const forged = {
575
- cookie: "coffre_session=conformance-forged; __Host-coffre_session=conformance-forged; CF_Authorization=conformance-forged",
576
- "cf-access-jwt-assertion": "conformance-forged",
577
- origin: "https://attacker.example",
578
- "sec-fetch-site": "cross-site",
579
- "content-type": "application/json"
580
- };
581
- for (const { key, method, url } of [...changes, {
582
- key: "POST /auth/signout",
583
- method: "POST",
584
- url: `${origin}/auth/signout`
585
- }]) {
586
- const response = await fetch(url, {
587
- method,
588
- headers: forged,
589
- body: "{}",
590
- redirect: "manual"
591
- });
592
- const text = await response.text();
593
- expect(response.status === 403, `${key} from another site answered ${response.status}`, text);
348
+ async function run(command, args) {
349
+ const entry = start(args[0] ?? command, command, args, {}, false);
350
+ if (await new Promise((done) => {
351
+ entry.child.once("exit", done);
352
+ entry.child.once("error", done);
353
+ }) !== 0) throw new Failure(`${command} ${args.join(" ")} failed`, Buffer.concat(entry.output).toString("utf8"));
594
354
  }
595
- return `${changes.length + 1} changes, sign-out included, from another site with a session cookie: 403`;
596
- }
597
- /** `GET /api/auth` names how to sign in, and nothing more. */
598
- async function signinInfo(origin) {
599
- const response = await fetch(`${origin}/api/auth`);
600
- expect(response.ok, `/api/auth answered ${response.status}`);
601
- const info = await response.json();
602
- expect(sameKeys(info, ["access", "signin"]), "/api/auth says more than how to sign in", info);
603
- expect(info.signin === null !== (info.access === null), "/api/auth names neither or both ways in", info);
604
- if (info.access !== null) {
605
- expect(sameKeys(info.access, ["assertion"]) && info.access.assertion === false, "/api/auth says more of Access than whether it vouched", info);
606
- return "Cloudflare Access, and nothing more";
355
+ function bin(name) {
356
+ const path = join(dir, "node_modules/.bin", name);
357
+ if (!existsSync(path)) throw new Failure(`${path} is missing: install ${dir} first`);
358
+ return path;
607
359
  }
608
- const signin = info.signin;
609
- expect(sameKeys(signin, [
610
- "note",
611
- "providers",
612
- "title"
613
- ]), "/api/auth says more of its sign-in than a page needs", signin);
614
- for (const provider of signin.providers) expect(sameKeys(provider, [
615
- "brand",
616
- "id",
617
- "label"
618
- ]), `/api/auth says more of ${provider.id} than its button`, provider);
619
- return `coffre's sign-in through ${signin.providers.map((provider) => provider.id).join(", ")}, and nothing more`;
620
- }
621
- /**
622
- * Nothing that could be a stored value in what no one is shown. Without a
623
- * canary this is a best effort: the API's refusals are checked to be only
624
- * refusals above, every closed page must send no one to /login with an
625
- * empty body, and the open pages must carry no credential coffre issues.
626
- */
627
- async function anonymousAnswers(origin) {
628
- const pages = [
629
- ...CLOSED_PAGES,
630
- `/projects/${NOWHERE.project}`,
631
- `/projects/${NOWHERE.project}/${NOWHERE.environment}`
632
- ];
633
- for (const path of pages) {
634
- let at = path;
635
- for (let hop = 0; at !== "/login"; hop++) {
636
- const response = await fetch(`${origin}${at}`, { redirect: "manual" });
637
- const text = await response.text();
638
- const to = new URL(response.headers.get("location") ?? at, origin);
639
- expect(hop < 3 && response.status >= 300 && response.status < 400 && to.origin === origin, `${at} answered no one ${response.status}${response.headers.has("location") ? ` to ${to.href}` : ""}, not a redirect on to /login`, text.slice(0, 2e3));
640
- expect(text.trim().length < 512, `${at} sent no one a body with its redirect`, text.slice(0, 2e3));
641
- at = to.pathname;
642
- }
643
- }
644
- for (const path of OPEN_PAGES) {
645
- const response = await fetch(`${origin}${path}`, { redirect: "manual" });
646
- const text = await response.text();
647
- expect(response.status === 200, `${path} answered ${response.status}`);
648
- const issued = /coffre_(svc|cli|web)_[A-Za-z0-9_-]{20,}/.exec(text);
649
- expect(issued === null, `${path} carries a credential coffre issues`, issued?.[0]);
650
- }
651
- return `best effort, without a canary: ${pages.length} closed pages send no one to /login with nothing else; /login carries no credential`;
652
- }
653
- /** The token is a service's, and reads the canary's environment. */
654
- async function whoIsToken(origin, api, canary) {
655
- if ((await (await fetch(`${origin}/api/auth`)).json()).signin === null) throw new Skip("behind Cloudflare Access, coffre issues no service tokens: the token's checks need coffre's own sign-in");
656
- const me = await api.me();
657
- expect(me.principal.type === "service", `the token is ${me.principal.type}:${me.principal.id}'s, not a service's`);
658
- const member = `token:${me.principal.id}`;
659
- const place = `${canary.project}/${canary.environment}`;
660
- expect(me.environments.find((env) => `${env.project}/${env.environment}` === place)?.permissions.includes("secret.read"), `${member} cannot read ${place}`, me.environments);
661
- const { keys } = await api.secrets.list(place);
662
- expect(keys.some((key) => key.key === canary.key), `${place} holds no ${canary.key}`, keys.map((key) => key.key));
663
- return {
664
- detail: `${member}, reading ${place}`,
665
- value: { member }
360
+ const idp = new DevIdp();
361
+ idp.listenPort = port + 1;
362
+ await idp.start();
363
+ const github = {
364
+ GITHUB_CLIENT_ID: "coffre-local",
365
+ GITHUB_CLIENT_SECRET: "coffre-local-secret",
366
+ GITHUB_URL: `${idp.origin}/github`,
367
+ GITHUB_API_URL: `${idp.origin}/github/api`
666
368
  };
667
- }
668
- /** Reveal the canary once, and find its `secret.read` in the audit log, by the reveal's request. */
669
- async function tokenReveal(api, canary, token) {
670
- const path = `${canary.project}/${canary.environment}`;
671
- const { operationId, values } = await api.secrets.reveal(`${path}/${canary.key}`);
672
- expect(values[canary.key] === canary.value, `${path}/${canary.key} is not the value given as the canary`);
673
- let entries;
369
+ let cleanup = async () => {};
370
+ async function stop() {
371
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
372
+ for (const { child, exited } of children) if (!exited) try {
373
+ process.kill(-child.pid, signal);
374
+ } catch {}
375
+ await setTimeout(500);
376
+ }
377
+ await idp.stop().catch(() => {});
378
+ await cleanup().catch(() => {});
379
+ rmSync(scratch, {
380
+ recursive: true,
381
+ force: true
382
+ });
383
+ }
674
384
  try {
675
- ({entries} = await api.audit.list({
676
- path,
677
- actor: token.member,
678
- limit: 50
679
- }));
385
+ const deployment = kind === "workers" ? await startWorkers() : await startNode();
386
+ await until(`${origin}/livez`, async () => (await fetch(`${origin}/livez`)).ok, 120, alive);
387
+ return deployment;
680
388
  } catch (error) {
681
- if (error instanceof CoffreError && error.status === 403) throw new Skip(`the token holds no audit.read on ${canary.project}, so the reveal's entry cannot be looked for`);
389
+ const seen = logs();
390
+ await stop();
391
+ if (error instanceof Failure) throw new Failure(error.message, `${error.detail ?? ""}\n${seen}`.trim());
682
392
  throw error;
683
393
  }
684
- const read = entries.filter((entry) => entry.operationId === operationId);
685
- expect(read.length === 1, `the reveal is logged ${read.length} times, not once`, entries.slice(0, 5));
686
- const [entry] = read;
687
- expect(entry.action === "secret.read" && entry.decision === "allow" && entry.key === canary.key && entry.requestId !== null, "the reveal's entry is not an allowed read of the canary, under a request", entry);
688
- return `one secret.read of ${canary.key}, entry ${entry.seq}, under request ${entry.requestId}`;
394
+ async function startWorkers() {
395
+ const name = `coffre_conformance_${randomBytes(4).toString("hex")}`;
396
+ const owner = withDatabase(options.postgres, name);
397
+ const runtime = withDatabase(options.runtime, name);
398
+ const vaultRuntime = withDatabase(options.vaultRuntime, name);
399
+ await using(postgres(withDatabase(options.postgres, "postgres")), (sql) => sql.exec(`CREATE DATABASE ${name}`));
400
+ cleanup = () => using(postgres(withDatabase(options.postgres, "postgres")), (sql) => sql.exec(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`));
401
+ await run(bin("coffre-server"), ["migrate", owner]);
402
+ const state = join(scratch, "state");
403
+ start("wrangler", bin("wrangler"), [
404
+ "dev",
405
+ ...[
406
+ "-c",
407
+ "app/wrangler.jsonc",
408
+ "-c",
409
+ "vault/wrangler.jsonc"
410
+ ],
411
+ ...[
412
+ "--ip",
413
+ "127.0.0.1",
414
+ "--port",
415
+ String(port),
416
+ "--inspector-port",
417
+ String(port + 2)
418
+ ],
419
+ ...[
420
+ "--persist-to",
421
+ state,
422
+ "--show-interactive-dev-session=false"
423
+ ],
424
+ ...[
425
+ "--var",
426
+ `GITHUB_URL:${github.GITHUB_URL}`,
427
+ "--var",
428
+ `GITHUB_API_URL:${github.GITHUB_API_URL}`
429
+ ]
430
+ ], {
431
+ PUBLIC_URL: origin,
432
+ GITHUB_CLIENT_ID: github.GITHUB_CLIENT_ID,
433
+ GITHUB_CLIENT_SECRET: github.GITHUB_CLIENT_SECRET,
434
+ APP_KEY: KEYS.APP_KEY,
435
+ VAULT_KEY_ID: KEYS.VAULT_KEY_ID,
436
+ VAULT_KEY: KEYS.VAULT_KEY,
437
+ ROOT_ADMINS: ROOT_ADMIN,
438
+ CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE: runtime,
439
+ CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_VAULT_HYPERDRIVE: vaultRuntime,
440
+ WRANGLER_SEND_METRICS: "false"
441
+ });
442
+ return {
443
+ kind,
444
+ origin,
445
+ idp,
446
+ rootAdmin: ROOT_ADMIN,
447
+ beforeFirstBeat: true,
448
+ async scheduled(options = {}) {
449
+ const response = await fetch(`${origin}/cdn-cgi/local/scheduled?cron=*/5+*+*+*+*`);
450
+ if (!response.ok && !options.allowFailure) throw new Failure(`the scheduled handler answered ${response.status}`, `${await response.text()}\n${logs()}`);
451
+ },
452
+ database: () => postgres(owner),
453
+ runtime: () => postgres(runtime),
454
+ vaultRuntime: () => postgres(vaultRuntime),
455
+ databaseFile: null,
456
+ output,
457
+ stop
458
+ };
459
+ }
460
+ async function startNode() {
461
+ const database = join(scratch, "coffre.db");
462
+ const socket = join(scratch, "vault.sock");
463
+ await run(bin("coffre-server"), ["migrate", `file:${database}`]);
464
+ start("vault", process.execPath, ["src/vault.ts"], {
465
+ VAULT_SOCKET: socket,
466
+ DATABASE_URL: `file:${database}`,
467
+ VAULT_KEY_ID: KEYS.VAULT_KEY_ID,
468
+ VAULT_KEY: KEYS.VAULT_KEY,
469
+ ROOT_ADMINS: ROOT_ADMIN
470
+ });
471
+ await until("the vault socket", async () => existsSync(socket), 30, alive);
472
+ const startServer = () => start("server", process.execPath, ["src/server.ts"], {
473
+ PORT: String(port),
474
+ PUBLIC_URL: origin,
475
+ DATABASE_URL: `file:${database}`,
476
+ VAULT_SOCKET: socket,
477
+ APP_KEY: KEYS.APP_KEY,
478
+ ...github
479
+ });
480
+ let server = startServer();
481
+ return {
482
+ kind,
483
+ origin,
484
+ idp,
485
+ rootAdmin: ROOT_ADMIN,
486
+ beforeFirstBeat: false,
487
+ async scheduled() {
488
+ const exited = new Promise((done) => server.child.once("exit", done));
489
+ server.daemon = false;
490
+ process.kill(-server.child.pid, "SIGTERM");
491
+ await exited;
492
+ server = startServer();
493
+ await until("the restarted server", async () => (await fetch(`${origin}/livez`)).ok, 30, alive);
494
+ },
495
+ database: async () => sqlite(database),
496
+ runtime: null,
497
+ vaultRuntime: null,
498
+ databaseFile: database,
499
+ output,
500
+ stop
501
+ };
502
+ }
689
503
  }
690
- /**
691
- * The canary's value, in any answer to a GET route as the token or as no
692
- * one, or in any page. The reveal is the only answer allowed to carry it.
693
- */
694
- async function tokenScan(origin, token, canary) {
695
- const me = await bearer(origin, token).me();
696
- const member = `token:${me.principal.id}`;
697
- const listed = me.environments.map(({ project, environment }) => ({
698
- project,
699
- environment
700
- }));
701
- const calls = getCalls({
702
- places: [...listed, NOWHERE],
703
- secrets: [{
704
- project: canary.project,
705
- environment: canary.environment,
706
- key: canary.key
707
- }, {
708
- ...NOWHERE,
709
- key: "NONE"
710
- }],
711
- members: [
712
- member,
713
- NOBODY,
714
- "user:nobody@conformance.example"
715
- ],
716
- services: [member, NOBODY]
717
- });
718
- const forms = [
719
- canary.value,
720
- Buffer.from(canary.value).toString("base64"),
721
- Buffer.from(canary.value).toString("hex")
722
- ];
723
- const leaks = [];
724
- const callers = [["the token", { authorization: `Bearer ${token}` }], ["no one", {}]];
725
- let answers = 0;
726
- const look = async (what, url, headers) => {
727
- const text = await (await fetch(url, {
728
- headers,
729
- redirect: "manual"
730
- })).text();
731
- answers++;
732
- if (forms.some((form) => text.includes(form))) leaks.push(what);
733
- };
734
- for (const { key, url } of getUrls(origin, calls)) for (const [name, headers] of callers) await look(`${key} as ${name}`, url, headers);
735
- const pages = [
736
- ...OPEN_PAGES,
737
- ...CLOSED_PAGES,
738
- ...listed.flatMap(({ project, environment }) => [`/projects/${project}`, `/projects/${project}/${environment}`])
739
- ];
740
- for (const path of new Set(pages)) for (const [name, headers] of callers) await look(`the page ${path} as ${name}`, `${origin}${path}`, headers);
741
- expect(leaks.length === 0, "the canary's value was found outside its reveal", leaks);
742
- return `${answers} answers from ${Object.keys(calls).length} GET routes and ${new Set(pages).size} pages, as the token and as no one: no value`;
504
+ function withDatabase(url, database) {
505
+ const parsed = new URL(url);
506
+ parsed.pathname = `/${database}`;
507
+ return parsed.href;
743
508
  }
744
- /** The token reaches the canary's project and nothing else: not another environment, project or member. */
745
- async function tokenScope(api, canary) {
746
- const { projects } = await api.projects.list();
747
- const seen = projects.map((project) => project.slug);
748
- expect(seen.length === 1 && seen[0] === canary.project, `the token sees ${seen.join(", ") || "no project"}, not only ${canary.project}`);
749
- const me = await api.me();
750
- const own = `${canary.project}/${canary.environment}`;
751
- const reads = me.environments.filter((env) => env.permissions.includes("secret.read")).map((env) => `${env.project}/${env.environment}`);
752
- expect(reads.length === 1 && reads[0] === own, `the token reads ${reads.join(", ")}, not only ${own}`);
753
- const more = [...new Set(me.environments.flatMap((env) => env.permissions))].filter((permission) => permission !== "secret.read" && permission !== "audit.read");
754
- expect(more.length === 0, `the token holds more than reading: ${more.join(", ")}`);
755
- const others = projects[0].environments.map((env) => `${canary.project}/${env.slug}`).filter((path) => path !== own);
756
- const nowhere = `${NOWHERE.project}/${NOWHERE.environment}`;
757
- let refusals = 0;
758
- for (const path of [...others, nowhere]) {
759
- await refused(`the token listed ${path}`, api.secrets.list(path));
760
- await refused(`the token revealed ${path}`, api.secrets.reveal(path));
761
- await refused(`the token read ${path}'s syncs`, api.syncs.list(path));
762
- refusals += 3;
509
+ //#endregion
510
+ //#region src/browser.ts
511
+ var Browser = class {
512
+ origin;
513
+ #jar = /* @__PURE__ */ new Map();
514
+ constructor(origin) {
515
+ this.origin = origin;
763
516
  }
764
- await refused(`the token read ${nowhere}'s audit`, api.audit.list({
765
- path: nowhere,
766
- limit: 1
767
- }));
768
- await refused("the token listed the members", api.members.list());
769
- await refused(`the token read ${NOBODY}`, api.members.get(NOBODY));
770
- refusals += 3;
771
- try {
772
- const { entries } = await api.audit.list({ limit: 500 });
773
- const outside = entries.filter((entry) => entry.project !== null && entry.project !== canary.project);
774
- expect(outside.length === 0, `the token reads audit entries about ${[...new Set(outside.map((entry) => entry.project))].join(", ")}`);
775
- } catch (error) {
776
- if (!(error instanceof CoffreError && error.status === 403)) throw error;
517
+ /** Whether coffre left this browser a cookie. */
518
+ get hasCookies() {
519
+ return this.#jar.size > 0;
777
520
  }
778
- const elsewhere = others.length === 0 ? "no other environment" : `${others.length} other environment${others.length === 1 ? "" : "s"}`;
779
- return `only ${own}; ${refusals} reads elsewhere refused: ${elsewhere} of ${canary.project}, a made-up place, the members`;
780
- }
781
- async function tokenVerification(api) {
782
- let verified;
783
- try {
784
- verified = await api.audit.verify();
785
- } catch (error) {
786
- if (error instanceof CoffreError && error.status === 403) throw new Skip("verification is for owners and root admins, which this token is not: not checked");
787
- throw error;
521
+ /**
522
+ * A request as the browser makes it, cookies included, redirects not
523
+ * followed. Nothing else is added: a caller playing another site's page
524
+ * sets its own `origin`.
525
+ */
526
+ async fetch(path, init = {}) {
527
+ const request = typeof path === "string" ? new Request(new URL(path, this.origin), init) : path;
528
+ const ours = new URL(request.url).origin === this.origin;
529
+ if (ours && this.#jar.size > 0) request.headers.set("cookie", [...this.#jar].map(([name, value]) => `${name}=${value}`).join("; "));
530
+ const response = await fetch(request, { redirect: "manual" });
531
+ if (ours) for (const cookie of response.headers.getSetCookie()) {
532
+ const [pair = ""] = cookie.split(";");
533
+ const at = pair.indexOf("=");
534
+ const value = pair.slice(at + 1);
535
+ if (value === "" || /max-age=0/i.test(cookie)) this.#jar.delete(pair.slice(0, at));
536
+ else this.#jar.set(pair.slice(0, at), value);
537
+ }
538
+ return response;
788
539
  }
789
- expect(verified.ok, "the audit log does not verify", verified);
790
- return `${verified.entries} entries verify, through entry ${verified.through}`;
791
- }
792
- /** `{ error, message }` and nothing else. */
793
- function onlyRefusal(text) {
794
- try {
795
- return sameKeys(JSON.parse(text), ["error", "message"]);
796
- } catch {
797
- return false;
540
+ /** A call one of coffre's pages makes: JSON, from its own origin. */
541
+ send(method, path, body) {
542
+ return this.fetch(path, {
543
+ method,
544
+ headers: {
545
+ origin: this.origin,
546
+ "sec-fetch-site": "same-origin",
547
+ "content-type": "application/json"
548
+ },
549
+ body: body === void 0 ? void 0 : JSON.stringify(body)
550
+ });
798
551
  }
799
- }
800
- function sameKeys(value, keys) {
801
- return typeof value === "object" && value !== null && JSON.stringify(Object.keys(value).sort()) === JSON.stringify(keys);
552
+ /** The API as this browser's pages call it. */
553
+ client() {
554
+ return createClient({
555
+ url: this.origin,
556
+ transport: (request) => {
557
+ request.headers.set("origin", this.origin);
558
+ request.headers.set("sec-fetch-site", "same-origin");
559
+ return this.fetch(request);
560
+ }
561
+ });
562
+ }
563
+ };
564
+ /** The API as the CLI or a service calls it, with a bearer token. */
565
+ function bearer(origin, token) {
566
+ return createClient({
567
+ url: origin,
568
+ headers: () => ({ authorization: `Bearer ${token}` })
569
+ });
802
570
  }
803
571
  //#endregion
804
572
  //#region src/checks/people.ts
@@ -818,7 +586,7 @@ function canary() {
818
586
  * password, and back. The error is the one coffre sent the browser back to
819
587
  * /login with.
820
588
  */
821
- async function signIn$1(deployment, browser, email) {
589
+ async function signIn(deployment, browser, email) {
822
590
  const leave = await browser.fetch("/auth/signin/github");
823
591
  const authorize = new URL(leave.headers.get("location") ?? "", deployment.origin);
824
592
  expect(leave.status === 302 && authorize.origin === deployment.idp.origin, "sign-in did not send the browser to GitHub", `${leave.status} ${leave.headers.get("location")}`);
@@ -841,7 +609,7 @@ async function signIn$1(deployment, browser, email) {
841
609
  }
842
610
  async function signInAdmin(deployment) {
843
611
  const browser = new Browser(deployment.origin);
844
- const signed = await signIn$1(deployment, browser, deployment.rootAdmin);
612
+ const signed = await signIn(deployment, browser, deployment.rootAdmin);
845
613
  expect(signed.ok, `the root admin was refused: ${"error" in signed ? signed.error : ""}`);
846
614
  const api = browser.client();
847
615
  const me = await api.me();
@@ -857,7 +625,7 @@ async function signInAdmin(deployment) {
857
625
  value: admin
858
626
  };
859
627
  }
860
- async function setUp$1(admin) {
628
+ async function setUp(admin) {
861
629
  await admin.api.projects.create(PROJECT, { name: "Conformance" });
862
630
  for (const [path, name] of [
863
631
  [DEV, "Development"],
@@ -918,7 +686,7 @@ async function personas(deployment, admin) {
918
686
  await admin.api.members.add(member);
919
687
  await admin.api.access.set(member, access);
920
688
  const browser = new Browser(deployment.origin);
921
- const signed = await signIn$1(deployment, browser, email);
689
+ const signed = await signIn(deployment, browser, email);
922
690
  expect(signed.ok, `${email} was refused: ${"error" in signed ? signed.error : ""}`);
923
691
  return {
924
692
  email,
@@ -947,613 +715,59 @@ async function personas(deployment, admin) {
947
715
  cli: bearer(deployment.origin, cliToken),
948
716
  cliToken
949
717
  },
950
- service: {
951
- member: SERVICE,
952
- token: issued.token,
953
- api: bearer(deployment.origin, issued.token)
954
- },
955
- stranger: {
956
- email: "stranger@conformance.example",
957
- browser: new Browser(deployment.origin)
958
- },
959
- bulk
960
- }
961
- };
962
- }
963
- /** `coffre login`: a device code, approved in a signed-in browser, for a CLI session. */
964
- async function deviceLogin(deployment, browser) {
965
- const json = { "content-type": "application/json" };
966
- const started = await fetch(`${deployment.origin}/api/auth/device`, {
967
- method: "POST",
968
- headers: json,
969
- body: JSON.stringify({ client_label: "coffre-conformance" })
970
- });
971
- expect(started.ok, `the device login did not start: ${started.status}`, await started.clone().text());
972
- const device = await started.json();
973
- await browser.client().deviceLogins.decide(device.user_code, true);
974
- const polled = await fetch(`${deployment.origin}/api/auth/device/token`, {
975
- method: "POST",
976
- headers: json,
977
- body: JSON.stringify({ device_code: device.device_code })
978
- });
979
- const session = await polled.json();
980
- expect(polled.ok && session.access_token, `the approved device login gave no token: ${polled.status}`, session);
981
- return session.access_token;
982
- }
983
- /**
984
- * A page's worth of API calls at once, as the pages fire them on a load,
985
- * right after sign-in, while the vault is fresh: every one answers. A call
986
- * that waited on another's work in the vault would be cancelled on
987
- * Cloudflare as hung, and the page would read the 503 or 401 as signed out.
988
- */
989
- async function pageLoad(person) {
990
- const paths = [
991
- "/api/me",
992
- "/api/sessions",
993
- "/api/projects",
994
- "/api/members",
995
- "/api/audit",
996
- "/api/identities",
997
- "/api/me",
998
- "/api/projects"
999
- ];
1000
- const failed = (await Promise.all(paths.map(async (path) => [path, (await person.browser.fetch(path)).status]))).filter(([, status]) => status !== 200);
1001
- expect(failed.length === 0, "a call of the page load did not answer 200", failed.map(([path, status]) => `${path}: ${status}`).join(", "));
1002
- return `${paths.length} calls at once, each answered`;
1003
- }
1004
- //#endregion
1005
- //#region src/checks/probe.ts
1006
- /** The probe's own place on an instance, made the first time, and found after. Nothing else is touched. */
1007
- const PROBE = {
1008
- project: "conformance",
1009
- environment: "live",
1010
- service: "token:conformance-probe",
1011
- key: "SIGN_IN_CANARY"
1012
- };
1013
- /** A device login, approved by `approve`, polled until it is, as `coffre login` polls. */
1014
- async function deviceSignIn(origin, approve) {
1015
- const json = { "content-type": "application/json" };
1016
- const started = await fetch(`${origin}/api/auth/device`, {
1017
- method: "POST",
1018
- headers: json,
1019
- body: JSON.stringify({ client_label: "coffre-conformance probe" })
1020
- });
1021
- expect(started.ok, `${origin} did not start a device login: ${started.status}`);
1022
- const device = await started.json();
1023
- await approve({
1024
- url: device.verification_uri_complete,
1025
- code: device.user_code
1026
- });
1027
- const deadline = Date.now() + device.expires_in * 1e3;
1028
- let wait = Math.max(device.interval, 1) * 1e3;
1029
- for (let first = true; Date.now() < deadline; first = false) {
1030
- if (!first) await new Promise((resolve) => setTimeout(resolve, wait));
1031
- const polled = await fetch(`${origin}/api/auth/device/token`, {
1032
- method: "POST",
1033
- headers: json,
1034
- body: JSON.stringify({ device_code: device.device_code })
1035
- }).catch(() => null);
1036
- if (polled === null) continue;
1037
- const answer = await polled.json().catch(() => ({}));
1038
- if (polled.ok && answer.access_token !== void 0) return answer.access_token;
1039
- if (polled.status === 429 || answer.error === "slow_down") wait += 5e3;
1040
- else if (answer.error === "access_denied") throw new Failure("the device login was declined in the browser: nothing was made");
1041
- else if (answer.error === "expired_token") break;
1042
- else if (answer.error !== "authorization_pending") throw new Failure(`the device login failed: ${answer.error ?? polled.status}`);
1043
- }
1044
- throw new Failure("the device login expired before it was approved: nothing was made");
1045
- }
1046
- /** End a session, as `coffre logout` does. One already ended is ended. */
1047
- async function endSession(origin, token) {
1048
- const response = await fetch(`${origin}/api/auth/logout`, {
1049
- method: "POST",
1050
- headers: {
1051
- authorization: `Bearer ${token}`,
1052
- "content-type": "application/json"
1053
- }
1054
- });
1055
- expect(response.ok || response.status === 401, `${origin} did not end the session: ${response.status}`);
1056
- }
1057
- /** Signed in, as an owner or a root admin, or stopped, the session ended, before anything is made. */
1058
- async function signIn(origin, approve) {
1059
- const token = await deviceSignIn(origin, approve);
1060
- const api = bearer(origin, token);
1061
- const me = await api.me();
1062
- const who = me.principal.id;
1063
- if (me.instanceRole === "user") {
1064
- await endSession(origin, token);
1065
- throw new Failure(`${who} is neither an owner nor a root admin of ${origin}: the probe made nothing, and ended the session`);
1066
- }
1067
- return {
1068
- detail: `${who}, ${me.instanceRole === "owner" ? "an owner" : "a root admin"}, through a device login`,
1069
- value: {
1070
- token,
1071
- api,
1072
- who
1073
- }
1074
- };
1075
- }
1076
- /** Make what is missing of the probe's place, and the service's two grants; then a fresh canary, and a fresh credential. */
1077
- async function setUp(api, issued) {
1078
- const place = `${PROBE.project}/${PROBE.environment}`;
1079
- const made = [];
1080
- const { projects } = await api.projects.list();
1081
- const project = projects.find(({ slug }) => slug === PROBE.project);
1082
- expect(project?.archivedAt == null, `${PROBE.project} is archived: unarchive it, or the probe has nowhere to run`);
1083
- if (project === void 0) {
1084
- await api.projects.create(PROBE.project, { name: "Conformance" });
1085
- made.push(`the project ${PROBE.project}`);
1086
- }
1087
- const environment = project?.environments.find(({ slug }) => slug === PROBE.environment);
1088
- expect(environment?.details?.archivedAt == null, `${place} is archived: unarchive it, or the probe has nowhere to run`);
1089
- if (environment === void 0) {
1090
- await api.environments.create(place, { name: "Live" });
1091
- made.push(`the environment ${place}`);
1092
- }
1093
- if ((await api.members.add(PROBE.service)).created) made.push(`the service ${PROBE.service}`);
1094
- const { changes } = await api.access.set(PROBE.service, {
1095
- [place]: "viewer",
1096
- [PROBE.project]: "auditor"
1097
- });
1098
- const granted = Object.entries(changes).filter(([, change]) => change !== "unchanged");
1099
- if (granted.length > 0) made.push(`its grants on ${granted.map(([where]) => where).join(" and ")}`);
1100
- const value = canary();
1101
- await api.secrets.set(place, { [PROBE.key]: value });
1102
- const credential = await api.tokens.issue(PROBE.service, {
1103
- label: "coffre-conformance probe, one run",
1104
- expiresInDays: 1
1105
- });
1106
- issued.push({
1107
- member: PROBE.service,
1108
- id: credential.id
1109
- });
1110
- return {
1111
- detail: `${made.length === 0 ? "all found" : `made ${made.join(", ")}`}; a fresh ${place}/${PROBE.key} and a fresh credential for ${PROBE.service}`,
1112
- value: {
1113
- token: credential.token,
1114
- canary: {
1115
- project: PROBE.project,
1116
- environment: PROBE.environment,
1117
- key: PROBE.key,
1118
- value
1119
- },
1120
- made
1121
- }
1122
- };
1123
- }
1124
- /** What the whole audit chain says, read by the owner, which a token cannot be. */
1125
- async function verification$1(api) {
1126
- const verified = await api.audit.verify();
1127
- expect(verified.ok, "the audit log does not verify", verified);
1128
- return `the whole chain verifies, as the signed-in owner: ${verified.entries} entries, through entry ${verified.through}`;
1129
- }
1130
- /**
1131
- * The signed-in tier: sign in, set up, the token tier, verification as the
1132
- * owner; and, however it ends, a Ctrl-C included, the credential revoked and
1133
- * the session ended. `prefix` names its checks apart from the local run's
1134
- * own. Returns the session's credential, ended, for the local run to check.
1135
- */
1136
- async function signedInChecks(report, origin, approve, prefix = "") {
1137
- const session = await report.check(`${prefix}sign-in`, {}, () => signIn(origin, approve));
1138
- if (session === void 0) return void 0;
1139
- const issued = [];
1140
- let ended = null;
1141
- const end = () => ended ??= cleanUp(origin, session, issued);
1142
- const interrupted = (code) => () => void end().finally(() => process.exit(code));
1143
- const onInt = interrupted(130);
1144
- const onTerm = interrupted(143);
1145
- process.once("SIGINT", onInt);
1146
- process.once("SIGTERM", onTerm);
1147
- let live;
1148
- try {
1149
- live = await report.check(`${prefix}probe setup`, {}, () => setUp(session.api, issued));
1150
- await tokenChecks(report, origin, live ?? {}, prefix);
1151
- await report.check(`${prefix}owner verification`, {}, () => verification$1(session.api));
1152
- } finally {
1153
- process.off("SIGINT", onInt);
1154
- process.off("SIGTERM", onTerm);
1155
- await report.check(`${prefix}clean-up`, {}, end);
1156
- }
1157
- return live === void 0 ? void 0 : {
1158
- session: session.token,
1159
- credential: live.token,
1160
- made: live.made
1161
- };
1162
- }
1163
- /** Revoke what the run issued, end its session, and say what stays. */
1164
- async function cleanUp(origin, session, issued) {
1165
- for (const { member, id } of issued) await session.api.tokens.revoke(member, id);
1166
- const { tokens } = await session.api.tokens.list(PROBE.service).catch(() => ({ tokens: [] }));
1167
- await endSession(origin, session.token);
1168
- const others = tokens.length === 0 ? "no working credential" : `${tokens.length} credential${tokens.length === 1 ? "" : "s"} this run did not issue, left as they are`;
1169
- return `${issued.length === 0 ? "nothing issued" : "the credential revoked"}, the session ended. Staying: ${PROBE.project}/${PROBE.environment} and its ${PROBE.key}, ${PROBE.service} with ${others}, and this run's entries in the audit log`;
1170
- }
1171
- /** Open `url` in this machine's browser, if it has one: on a server, the printed address serves. */
1172
- function openBrowser(url) {
1173
- const [command, ...args] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? [
1174
- "cmd",
1175
- "/c",
1176
- "start",
1177
- "",
1178
- url
1179
- ] : ["xdg-open", url];
1180
- try {
1181
- const child = spawn(command, args, {
1182
- stdio: "ignore",
1183
- detached: true
1184
- });
1185
- child.on("error", () => {});
1186
- child.unref();
1187
- } catch {}
1188
- }
1189
- /** The local run approves as the person signing in: their own session approves the code, as their browser would. */
1190
- function approvedBy(person) {
1191
- return async ({ code }) => {
1192
- await person.api.deviceLogins.decide(code, true);
1193
- };
1194
- }
1195
- /** What the probe must leave as it was: every member and their grants, but its service; every project and environment. */
1196
- async function everythingElse(api) {
1197
- const { members } = await api.members.list();
1198
- const { projects } = await api.projects.list();
1199
- return JSON.stringify({
1200
- members: members.filter(({ member }) => member !== PROBE.service),
1201
- projects: projects.map(({ slug, archivedAt, environments }) => ({
1202
- slug,
1203
- archivedAt,
1204
- environments: environments.map(({ slug: env }) => env)
1205
- }))
1206
- });
1207
- }
1208
- /** Signed in as a user, the probe says so, and makes nothing: no service, no session left. Returns what it must leave as it was. */
1209
- async function probeAsUser(origin, user, admin) {
1210
- const before = await everythingElse(admin.api);
1211
- const quiet = new Report(19, true);
1212
- await signedInChecks(quiet, origin, approvedBy(user));
1213
- const [signIn] = quiet.results;
1214
- expect(quiet.results.length === 1 && signIn?.status === "FAIL", "the probe went on past a user", quiet.results);
1215
- expect(signIn.line.includes("is neither an owner nor a root admin") && signIn.line.includes("made nothing"), "the probe did not say plainly why it stopped", signIn.line);
1216
- expect(await admin.api.members.get(PROBE.service).then(() => "there", (error) => error instanceof CoffreError && error.status === 404 ? "absent" : Promise.reject(error)) === "absent", `${PROBE.service} was made for a user`);
1217
- const { sessions } = await user.api.sessions.list();
1218
- expect(!sessions.some(({ label }) => label === "coffre-conformance probe"), "the user's probe session was left open", sessions);
1219
- expect(await everythingElse(admin.api) === before, "the probe changed a member, a grant, a project or an environment for a user");
1220
- return {
1221
- detail: `${user.email}, a user, is told plainly; nothing made, the session ended`,
1222
- value: before
1223
- };
1224
- }
1225
- /** One run of `probe --sign-in`, as the admin: every check of it passes. Its lines, summed up. */
1226
- async function probeRun(origin, admin) {
1227
- const quiet = new Report(19, true);
1228
- const run = await signedInChecks(quiet, origin, approvedBy(admin));
1229
- const failed = quiet.results.filter(({ status }) => status === "FAIL");
1230
- expect(run !== void 0 && failed.length === 0, `the probe failed: ${failed.map(({ name }) => name).join(", ")}`, quiet.results);
1231
- const said = JSON.stringify(quiet.results);
1232
- expect(!said.includes(run.credential) && !said.includes(run.session) && !/coffre-canary-/.test(said), "the probe's lines show its credential, its session or its canary");
1233
- const skipped = quiet.results.filter(({ status }) => status === "skip").map(({ name }) => name);
1234
- return {
1235
- detail: `${quiet.results.length - skipped.length} checks ok${skipped.length === 0 ? "" : `, ${skipped.join(", ")} skipped`}; ${run.made.length === 0 ? "all found" : `made ${run.made.join(", ")}`}`,
1236
- value: run
1237
- };
1238
- }
1239
- /**
1240
- * After two runs: the second found everything the first made; each run's
1241
- * credential and session refuse, and the service holds no credential; the
1242
- * canary an operator keeps beside is as it was; nothing else changed; the
1243
- * runs' reads are in the audit log.
1244
- */
1245
- async function probeLeftovers(origin, admin, runs, before, kept) {
1246
- expect(runs[0].made.includes(`the service ${PROBE.service}`), "the first run did not make its service", runs[0].made);
1247
- expect(runs.slice(1).every(({ made }) => made.length === 0), "a later run made something again", runs.map(({ made }) => made));
1248
- for (const { session, credential } of runs) for (const [what, token] of [["session", session], ["credential", credential]]) await refused(`a run's ${what} still worked after it`, bearer(origin, token).me());
1249
- const { tokens } = await admin.api.tokens.list(PROBE.service);
1250
- expect(tokens.length === 0, `${PROBE.service} still holds ${tokens.length} credential(s)`, tokens);
1251
- const place = `${kept.project}/${kept.environment}`;
1252
- const { values } = await admin.api.secrets.reveal(`${place}/${kept.key}`);
1253
- expect(values[kept.key] === kept.value, `${place}/${kept.key}, kept beside the probe's own, was changed`);
1254
- expect(await everythingElse(admin.api) === before, "the runs changed a member, a grant, a project or an environment besides their own");
1255
- const { entries } = await admin.api.audit.list({
1256
- actor: PROBE.service,
1257
- limit: 50
1258
- });
1259
- expect(entries.length > 0, `the audit log holds no entry by ${PROBE.service}`);
1260
- return `the second run found all; ${runs.length} sessions and credentials refuse; ${PROBE.service} holds none; ${place}/${kept.key} untouched; nothing else changed; ${entries.length} entries by ${PROBE.service} stay`;
1261
- }
1262
- /** What a credential coffre issues, or a canary, looks like in a run's output. */
1263
- const SHOWN = /coffre_(svc|cli|web)_[A-Za-z0-9_-]{8,}|coffre-canary-[0-9a-f]{8,}/;
1264
- /**
1265
- * The command itself, `coffre-conformance probe <url> --sign-in`, as the
1266
- * admin approves it, interrupted mid-run by a Ctrl-C: it exits 130 with its
1267
- * credential revoked and its session ended, and nothing it printed shows
1268
- * either, or its canary.
1269
- */
1270
- async function probeInterrupted(origin, admin) {
1271
- const child = spawn(process.execPath, [
1272
- ...process.execArgv,
1273
- process.argv[1],
1274
- "probe",
1275
- origin,
1276
- "--sign-in"
1277
- ], { stdio: [
1278
- "ignore",
1279
- "pipe",
1280
- "pipe"
1281
- ] });
1282
- let output = "";
1283
- child.stdout.setEncoding("utf8").on("data", (chunk) => output += chunk);
1284
- child.stderr.setEncoding("utf8").on("data", (chunk) => output += chunk);
1285
- const exited = new Promise((resolve) => child.on("exit", (code) => resolve(code)));
1286
- try {
1287
- const waitFor = async (pattern, what) => {
1288
- for (let tries = 0; !pattern.test(output); tries += 1) {
1289
- expect(tries < 600 && child.exitCode === null, `the probe never got to ${what}`, output);
1290
- await setTimeout$1(50);
1291
- }
1292
- return pattern.exec(output);
1293
- };
1294
- const [, code] = await waitFor(/shows the code (\S+)\./, "its device login");
1295
- await admin.api.deviceLogins.decide(code, true);
1296
- await waitFor(/ok {4}token reveal/, "its token checks");
1297
- child.kill("SIGINT");
1298
- const status = await exited;
1299
- expect(status === 130, `the interrupted probe exited ${status}, not 130`, output);
1300
- } finally {
1301
- if (child.exitCode === null) child.kill("SIGKILL");
1302
- }
1303
- const { tokens } = await admin.api.tokens.list(PROBE.service);
1304
- expect(tokens.length === 0, `the interrupted run left ${PROBE.service} ${tokens.length} credential(s)`, tokens);
1305
- const { sessions } = await admin.api.sessions.list();
1306
- expect(!sessions.some(({ label }) => label === "coffre-conformance probe"), "the interrupted run's session was left open", sessions);
1307
- expect(!SHOWN.test(output), "the probe printed a credential or a canary", SHOWN.exec(output)?.[0]);
1308
- return "Ctrl-C mid-run: exit 130, its credential revoked and its session ended; nothing it printed shows either, or its canary";
1309
- }
1310
- //#endregion
1311
- //#region src/database.ts
1312
- async function postgres(url) {
1313
- const client = new pg.Client(postgresConnection(url));
1314
- await client.connect();
1315
- return {
1316
- engine: "postgres",
1317
- query: async (statement, params = []) => (await client.query(statement, params)).rows,
1318
- exec: async (statements) => void await client.query(statements),
1319
- close: () => client.end()
1320
- };
1321
- }
1322
- /** A SQLite file, perhaps open in another process: it waits out their locks. */
1323
- function sqlite(file) {
1324
- const db = new DatabaseSync(file, { timeout: 5e3 });
1325
- return {
1326
- engine: "sqlite",
1327
- query: async (statement, params = []) => db.prepare(statement).all(...params),
1328
- exec: async (statements) => db.exec(statements),
1329
- close: async () => db.close()
1330
- };
1331
- }
1332
- async function using(open, use) {
1333
- const sql = await open;
1334
- try {
1335
- return await use(sql);
1336
- } finally {
1337
- await sql.close();
1338
- }
1339
- }
1340
- //#endregion
1341
- //#region src/fixtures.ts
1342
- const KEYS = {
1343
- VAULT_KEY_ID: "vault-conformance-1",
1344
- VAULT_KEY: "Y29mZnJlLWxvY2FsLWRldi1rZWstMzItYnl0ZXMhISE=",
1345
- APP_KEY: "Y29mZnJlLWxvY2FsLWF1ZGl0LWNoYWluLWtleS0zMmI="
1346
- };
1347
- //#endregion
1348
- //#region src/harness.ts
1349
- const ROOT_ADMIN = "root@conformance.example";
1350
- async function boot(kind, at, options) {
1351
- const { port } = options;
1352
- const dir = resolve(at);
1353
- const origin = `http://127.0.0.1:${port}`;
1354
- for (const taken of [
1355
- port,
1356
- port + 1,
1357
- port + 2
1358
- ]) if (await fetch(`http://127.0.0.1:${taken}/`).then(() => true, () => false)) throw new Failure(`port ${taken} is taken; pass --port for a free run of three`);
1359
- if (kind === "workers" && (options.postgres === void 0 || options.runtime === void 0 || options.vaultRuntime === void 0)) throw new Failure("workers run on Postgres: pass --postgres <owner URL>, --runtime <coffre_runtime URL> and --vault-runtime <coffre_vault_runtime URL>");
1360
- const scratch = mkdtempSync(join(tmpdir(), `coffre-conformance-${kind}-`));
1361
- const shell = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("COFFRE_")));
1362
- const children = [];
1363
- const output = (tail = Infinity) => children.map((entry) => `--- ${entry.name}\n${Buffer.concat(entry.output).toString("utf8").slice(-tail)}`).join("\n");
1364
- const logs = () => output(4e3);
1365
- const alive = () => !children.some((entry) => entry.daemon && entry.exited);
1366
- function start(name, command, args, env, daemon = true) {
1367
- const child = spawn(command, args, {
1368
- cwd: dir,
1369
- env: {
1370
- ...shell,
1371
- ...env
1372
- },
1373
- detached: true,
1374
- stdio: [
1375
- "ignore",
1376
- "pipe",
1377
- "pipe"
1378
- ]
1379
- });
1380
- const entry = {
1381
- name,
1382
- child,
1383
- daemon,
1384
- exited: false,
1385
- output: []
1386
- };
1387
- child.stdout.on("data", (chunk) => entry.output.push(chunk));
1388
- child.stderr.on("data", (chunk) => entry.output.push(chunk));
1389
- child.once("exit", () => entry.exited = true);
1390
- child.once("error", (error) => {
1391
- entry.output.push(Buffer.from(`${error.message}\n`));
1392
- entry.exited = true;
1393
- });
1394
- children.push(entry);
1395
- return entry;
1396
- }
1397
- async function run(command, args) {
1398
- const entry = start(args[0] ?? command, command, args, {}, false);
1399
- if (await new Promise((done) => {
1400
- entry.child.once("exit", done);
1401
- entry.child.once("error", done);
1402
- }) !== 0) throw new Failure(`${command} ${args.join(" ")} failed`, Buffer.concat(entry.output).toString("utf8"));
1403
- }
1404
- function bin(name) {
1405
- const path = join(dir, "node_modules/.bin", name);
1406
- if (!existsSync(path)) throw new Failure(`${path} is missing: install ${dir} first`);
1407
- return path;
1408
- }
1409
- const idp = new DevIdp();
1410
- idp.listenPort = port + 1;
1411
- await idp.start();
1412
- const github = {
1413
- GITHUB_CLIENT_ID: "coffre-local",
1414
- GITHUB_CLIENT_SECRET: "coffre-local-secret",
1415
- GITHUB_URL: `${idp.origin}/github`,
1416
- GITHUB_API_URL: `${idp.origin}/github/api`
1417
- };
1418
- let cleanup = async () => {};
1419
- async function stop() {
1420
- for (const signal of ["SIGTERM", "SIGKILL"]) {
1421
- for (const { child, exited } of children) if (!exited) try {
1422
- process.kill(-child.pid, signal);
1423
- } catch {}
1424
- await setTimeout$1(500);
1425
- }
1426
- await idp.stop().catch(() => {});
1427
- await cleanup().catch(() => {});
1428
- rmSync(scratch, {
1429
- recursive: true,
1430
- force: true
1431
- });
1432
- }
1433
- try {
1434
- const deployment = kind === "workers" ? await startWorkers() : await startNode();
1435
- await until(`${origin}/livez`, async () => (await fetch(`${origin}/livez`)).ok, 120, alive);
1436
- return deployment;
1437
- } catch (error) {
1438
- const seen = logs();
1439
- await stop();
1440
- if (error instanceof Failure) throw new Failure(error.message, `${error.detail ?? ""}\n${seen}`.trim());
1441
- throw error;
1442
- }
1443
- async function startWorkers() {
1444
- const name = `coffre_conformance_${randomBytes(4).toString("hex")}`;
1445
- const owner = withDatabase(options.postgres, name);
1446
- const runtime = withDatabase(options.runtime, name);
1447
- const vaultRuntime = withDatabase(options.vaultRuntime, name);
1448
- await using(postgres(withDatabase(options.postgres, "postgres")), (sql) => sql.exec(`CREATE DATABASE ${name}`));
1449
- cleanup = () => using(postgres(withDatabase(options.postgres, "postgres")), (sql) => sql.exec(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`));
1450
- await run(bin("coffre-server"), ["migrate", owner]);
1451
- const state = join(scratch, "state");
1452
- start("wrangler", bin("wrangler"), [
1453
- "dev",
1454
- ...[
1455
- "-c",
1456
- "app/wrangler.jsonc",
1457
- "-c",
1458
- "vault/wrangler.jsonc"
1459
- ],
1460
- ...[
1461
- "--ip",
1462
- "127.0.0.1",
1463
- "--port",
1464
- String(port),
1465
- "--inspector-port",
1466
- String(port + 2)
1467
- ],
1468
- ...[
1469
- "--persist-to",
1470
- state,
1471
- "--show-interactive-dev-session=false"
1472
- ],
1473
- ...[
1474
- "--var",
1475
- `GITHUB_URL:${github.GITHUB_URL}`,
1476
- "--var",
1477
- `GITHUB_API_URL:${github.GITHUB_API_URL}`
1478
- ]
1479
- ], {
1480
- PUBLIC_URL: origin,
1481
- GITHUB_CLIENT_ID: github.GITHUB_CLIENT_ID,
1482
- GITHUB_CLIENT_SECRET: github.GITHUB_CLIENT_SECRET,
1483
- APP_KEY: KEYS.APP_KEY,
1484
- VAULT_KEY_ID: KEYS.VAULT_KEY_ID,
1485
- VAULT_KEY: KEYS.VAULT_KEY,
1486
- ROOT_ADMINS: ROOT_ADMIN,
1487
- CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE: runtime,
1488
- CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_VAULT_HYPERDRIVE: vaultRuntime,
1489
- WRANGLER_SEND_METRICS: "false"
1490
- });
1491
- return {
1492
- kind,
1493
- origin,
1494
- idp,
1495
- rootAdmin: ROOT_ADMIN,
1496
- beforeFirstBeat: true,
1497
- async scheduled(options = {}) {
1498
- const response = await fetch(`${origin}/cdn-cgi/local/scheduled?cron=*/5+*+*+*+*`);
1499
- if (!response.ok && !options.allowFailure) throw new Failure(`the scheduled handler answered ${response.status}`, `${await response.text()}\n${logs()}`);
1500
- },
1501
- database: () => postgres(owner),
1502
- runtime: () => postgres(runtime),
1503
- vaultRuntime: () => postgres(vaultRuntime),
1504
- databaseFile: null,
1505
- output,
1506
- stop
1507
- };
1508
- }
1509
- async function startNode() {
1510
- const database = join(scratch, "coffre.db");
1511
- const socket = join(scratch, "vault.sock");
1512
- await run(bin("coffre-server"), ["migrate", `file:${database}`]);
1513
- start("vault", process.execPath, ["src/vault.ts"], {
1514
- VAULT_SOCKET: socket,
1515
- DATABASE_URL: `file:${database}`,
1516
- VAULT_KEY_ID: KEYS.VAULT_KEY_ID,
1517
- VAULT_KEY: KEYS.VAULT_KEY,
1518
- ROOT_ADMINS: ROOT_ADMIN
1519
- });
1520
- await until("the vault socket", async () => existsSync(socket), 30, alive);
1521
- const startServer = () => start("server", process.execPath, ["src/server.ts"], {
1522
- PORT: String(port),
1523
- PUBLIC_URL: origin,
1524
- DATABASE_URL: `file:${database}`,
1525
- VAULT_SOCKET: socket,
1526
- APP_KEY: KEYS.APP_KEY,
1527
- ...github
1528
- });
1529
- let server = startServer();
1530
- return {
1531
- kind,
1532
- origin,
1533
- idp,
1534
- rootAdmin: ROOT_ADMIN,
1535
- beforeFirstBeat: false,
1536
- async scheduled() {
1537
- const exited = new Promise((done) => server.child.once("exit", done));
1538
- server.daemon = false;
1539
- process.kill(-server.child.pid, "SIGTERM");
1540
- await exited;
1541
- server = startServer();
1542
- await until("the restarted server", async () => (await fetch(`${origin}/livez`)).ok, 30, alive);
1543
- },
1544
- database: async () => sqlite(database),
1545
- runtime: null,
1546
- vaultRuntime: null,
1547
- databaseFile: database,
1548
- output,
1549
- stop
1550
- };
1551
- }
718
+ service: {
719
+ member: SERVICE,
720
+ token: issued.token,
721
+ api: bearer(deployment.origin, issued.token)
722
+ },
723
+ stranger: {
724
+ email: "stranger@conformance.example",
725
+ browser: new Browser(deployment.origin)
726
+ },
727
+ bulk
728
+ }
729
+ };
1552
730
  }
1553
- function withDatabase(url, database) {
1554
- const parsed = new URL(url);
1555
- parsed.pathname = `/${database}`;
1556
- return parsed.href;
731
+ /** `coffre login`: a device code, approved in a signed-in browser, for a CLI session. */
732
+ async function deviceLogin(deployment, browser) {
733
+ const json = { "content-type": "application/json" };
734
+ const started = await fetch(`${deployment.origin}/api/auth/device`, {
735
+ method: "POST",
736
+ headers: json,
737
+ body: JSON.stringify({ client_label: "coffre-conformance" })
738
+ });
739
+ expect(started.ok, `the device login did not start: ${started.status}`, await started.clone().text());
740
+ const device = await started.json();
741
+ await browser.client().deviceLogins.decide(device.user_code, true);
742
+ const polled = await fetch(`${deployment.origin}/api/auth/device/token`, {
743
+ method: "POST",
744
+ headers: json,
745
+ body: JSON.stringify({ device_code: device.device_code })
746
+ });
747
+ const session = await polled.json();
748
+ expect(polled.ok && session.access_token, `the approved device login gave no token: ${polled.status}`, session);
749
+ return session.access_token;
750
+ }
751
+ /**
752
+ * A page's worth of API calls at once, as the pages fire them on a load,
753
+ * right after sign-in, while the vault is fresh: every one answers. A call
754
+ * that waited on another's work in the vault would be cancelled on
755
+ * Cloudflare as hung, and the page would read the 503 or 401 as signed out.
756
+ */
757
+ async function pageLoad(person) {
758
+ const paths = [
759
+ "/api/me",
760
+ "/api/sessions",
761
+ "/api/projects",
762
+ "/api/members",
763
+ "/api/audit",
764
+ "/api/identities",
765
+ "/api/me",
766
+ "/api/projects"
767
+ ];
768
+ const failed = (await Promise.all(paths.map(async (path) => [path, (await person.browser.fetch(path)).status]))).filter(([, status]) => status !== 200);
769
+ expect(failed.length === 0, "a call of the page load did not answer 200", failed.map(([path, status]) => `${path}: ${status}`).join(", "));
770
+ return `${paths.length} calls at once, each answered`;
1557
771
  }
1558
772
  //#endregion
1559
773
  //#region src/checks/storage.ts
@@ -1700,7 +914,7 @@ async function member(deployment, { admin }, name) {
1700
914
  await admin.api.members.add(principal);
1701
915
  await admin.api.access.set(principal, { [DEV]: "viewer" });
1702
916
  const browser = new Browser(deployment.origin);
1703
- expect((await signIn$1(deployment, browser, email)).ok, "the fixture member could not sign in");
917
+ expect((await signIn(deployment, browser, email)).ok, "the fixture member could not sign in");
1704
918
  return {
1705
919
  email,
1706
920
  member: principal,
@@ -1907,7 +1121,7 @@ async function forgedIdentity(deployment, people) {
1907
1121
  };
1908
1122
  await insertRow(sql, "identities", forged);
1909
1123
  try {
1910
- await signIn$1(deployment, browser, email).catch(() => {});
1124
+ await signIn(deployment, browser, email).catch(() => {});
1911
1125
  expect((await browser.fetch("/api/me")).status === 401, "an owner-forged identity minted a session");
1912
1126
  await reported(deployment, forged.id);
1913
1127
  } finally {
@@ -1996,7 +1210,7 @@ async function editedGeneration(deployment, people) {
1996
1210
  //#endregion
1997
1211
  //#region src/checks/access.ts
1998
1212
  async function membersOnly(deployment, { stranger }) {
1999
- const attempt = await signIn$1(deployment, stranger.browser, stranger.email);
1213
+ const attempt = await signIn(deployment, stranger.browser, stranger.email);
2000
1214
  expect(!attempt.ok, "someone never admitted signed in");
2001
1215
  expect(!stranger.browser.hasCookies, "the refused sign-in left the browser a cookie");
2002
1216
  expect((await stranger.browser.fetch("/api/me")).status === 401, "the refused sign-in left a session");
@@ -2113,7 +1327,7 @@ async function offboarding(deployment, { admin, leaver, service }, canaries) {
2113
1327
  expect(same(exposed, Object.keys(valuesIn(canaries, DEV)).map((key) => `${DEV}/${key}`).sort()), "the offboarding report does not name what they read", report.exposed);
2114
1328
  expect((await leaver.browser.fetch("/api/me")).status === 401, "a removed member's browser session still works");
2115
1329
  await refused("a removed member's CLI session read secrets", leaver.cli.secrets.list(DEV));
2116
- expect(!(await signIn$1(deployment, leaver.browser, leaver.email)).ok, "a removed member signed in again");
1330
+ expect(!(await signIn(deployment, leaver.browser, leaver.email)).ok, "a removed member signed in again");
2117
1331
  await admin.api.members.remove(service.member);
2118
1332
  await refused("a removed service's token read secrets", service.api.secrets.reveal(DEV));
2119
1333
  await admin.api.members.add(leaver.member);
@@ -2124,7 +1338,7 @@ async function offboarding(deployment, { admin, leaver, service }, canaries) {
2124
1338
  await refused("re-admission revived the CLI session", leaver.cli.secrets.reveal(DEV));
2125
1339
  await refused("re-admission revived the service token", service.api.secrets.reveal(DEV));
2126
1340
  expect(!(await pollDevice(deployment, device.device_code)).ok, "re-admission revived the old device approval");
2127
- expect((await signIn$1(deployment, leaver.browser, leaver.email)).ok, "a fresh provider callback could not sign the re-admitted member in");
1341
+ expect((await signIn(deployment, leaver.browser, leaver.email)).ok, "a fresh provider callback could not sign the re-admitted member in");
2128
1342
  await admin.api.members.remove(leaver.member);
2129
1343
  await admin.api.members.remove(service.member);
2130
1344
  return `the report names ${exposed.length} values; re-admission revives no old session, token or approval; a fresh provider callback works`;
@@ -2673,6 +1887,55 @@ async function middleCut(deployment, { admin }) {
2673
1887
  return `entries ${seq} and ${seq + 1}, before the latest signed prefix, cut: checkpoint log_broken, readiness red; restored and recovered`;
2674
1888
  }
2675
1889
  //#endregion
1890
+ //#region ../client/dist/routes.js
1891
+ function getCalls({ places, secrets, members, services }) {
1892
+ const first = places[0];
1893
+ return {
1894
+ "GET /me": [{ params: {} }],
1895
+ "GET /projects": [{ params: {} }],
1896
+ "GET /secrets/:project/:environment": places.map((params) => ({ params })),
1897
+ "GET /secrets/:project/:environment/:key/versions": secrets.map((params) => ({ params })),
1898
+ "GET /members": [{ params: {} }, ...first === void 0 ? [] : [{
1899
+ params: {},
1900
+ input: { path: `${first.project}/${first.environment}` }
1901
+ }]],
1902
+ "GET /members/:member": members.map((member) => ({ params: { member } })),
1903
+ "GET /members/:member/tokens": services.map((member) => ({ params: { member } })),
1904
+ "GET /sessions": [{ params: {} }],
1905
+ "GET /identities": [{ params: {} }],
1906
+ "GET /device-logins/:code": [{ params: { code: "BCDF-GHJK" } }],
1907
+ "GET /syncs/providers": [{ params: {} }],
1908
+ "GET /syncs/:project/:environment": places.map((params) => ({ params })),
1909
+ "GET /audit": [{
1910
+ params: {},
1911
+ input: { limit: 500 }
1912
+ }, {
1913
+ params: {},
1914
+ input: {
1915
+ limit: 500,
1916
+ detail: "1"
1917
+ }
1918
+ }],
1919
+ "GET /audit/verification": [{ params: {} }],
1920
+ "GET /audit/keys": [{ params: {} }]
1921
+ };
1922
+ }
1923
+ /** Each GET call as a URL, with its parameters and query filled in. */
1924
+ function getUrls(origin, calls) {
1925
+ const urls = [];
1926
+ for (const [key, asks] of Object.entries(calls)) for (const { params, input } of asks) urls.push({
1927
+ key,
1928
+ url: address(origin, key, params, input)
1929
+ });
1930
+ return urls;
1931
+ }
1932
+ function address(origin, key, params, input) {
1933
+ const path = key.slice(4).replace(/:(\w+)/g, (_, name) => encodeURIComponent(params[name]));
1934
+ const url = new URL(`${origin}/api${path}`);
1935
+ for (const [name, value] of Object.entries(input ?? {})) url.searchParams.set(name, String(value));
1936
+ return url.href;
1937
+ }
1938
+ //#endregion
2676
1939
  //#region src/checks/canaries.ts
2677
1940
  function calls(people) {
2678
1941
  const places = [
@@ -2807,15 +2070,294 @@ function files(path) {
2807
2070
  return Buffer.concat([path, `${path}-wal`].filter((file) => existsSync(file)).map((file) => readFileSync(file)));
2808
2071
  }
2809
2072
  //#endregion
2073
+ //#region src/checks/cli.ts
2074
+ /** What `coffre verify instance` makes and finds on an instance, as an owner: its own place, service and key. */
2075
+ const PROBE = {
2076
+ project: "conformance",
2077
+ environment: "live",
2078
+ service: "token:conformance-probe",
2079
+ key: "SIGN_IN_CANARY"
2080
+ };
2081
+ /** What a credential coffre issues, or a canary, looks like in a run's output. */
2082
+ const SHOWN = /coffre_(svc|cli|web)_[A-Za-z0-9_-]{8,}|coffre-canary-[0-9a-f]{8,}/;
2083
+ /** The CLI's entry, as its package ships it: built, as a deployment installs it. */
2084
+ function entry() {
2085
+ const main = join(dirname(createRequire(import.meta.url).resolve("@coffre/cli/package.json")), "dist", "main.js");
2086
+ if (!existsSync(main)) throw new Failure("@coffre/cli is not built: run `pnpm build` at the root of the coffre repository");
2087
+ return main;
2088
+ }
2089
+ /** The CLI with a home of its own, where `coffre login` keeps its session: one person's terminal. */
2090
+ var Cli = class {
2091
+ origin;
2092
+ home;
2093
+ constructor(origin) {
2094
+ this.origin = origin;
2095
+ this.home = mkdtempSync(join(tmpdir(), "coffre-conformance-cli-"));
2096
+ }
2097
+ start(args, env = {}, input) {
2098
+ const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("COFFRE_") && name !== "NODE_OPTIONS"));
2099
+ const child = spawn(process.execPath, [entry(), ...args], {
2100
+ env: {
2101
+ ...inherited,
2102
+ HOME: this.home,
2103
+ NO_COLOR: "1",
2104
+ ...env
2105
+ },
2106
+ stdio: [
2107
+ "pipe",
2108
+ "pipe",
2109
+ "pipe"
2110
+ ]
2111
+ });
2112
+ let output = "";
2113
+ child.stdout.setEncoding("utf8").on("data", (chunk) => output += chunk);
2114
+ child.stderr.setEncoding("utf8").on("data", (chunk) => output += chunk);
2115
+ child.stdin.end(input ?? "");
2116
+ return {
2117
+ output: () => output,
2118
+ exited: new Promise((resolve) => child.on("exit", (code) => resolve(code))),
2119
+ kill: (signal) => child.kill(signal),
2120
+ waitFor: async (pattern, what) => {
2121
+ for (let tries = 0; !pattern.test(output); tries += 1) {
2122
+ if (tries >= 1200 || child.exitCode !== null) {
2123
+ child.kill("SIGKILL");
2124
+ throw new Failure(`coffre never got to ${what}`, output);
2125
+ }
2126
+ await setTimeout(50);
2127
+ }
2128
+ return pattern.exec(output);
2129
+ }
2130
+ };
2131
+ }
2132
+ async run(args, env = {}, input) {
2133
+ const running = this.start(args, env, input);
2134
+ return {
2135
+ code: await running.exited,
2136
+ output: running.output()
2137
+ };
2138
+ }
2139
+ /** The session `coffre login` keeps here, for this run to check it is still signed in. */
2140
+ session() {
2141
+ const store = JSON.parse(readFileSync(join(this.home, ".coffre", "credentials.json"), "utf8"));
2142
+ const token = store.instances[this.origin]?.token;
2143
+ expect(token !== void 0, `no session for ${this.origin} in the CLI's credentials`, Object.keys(store.instances));
2144
+ return token;
2145
+ }
2146
+ remove() {
2147
+ rmSync(this.home, {
2148
+ recursive: true,
2149
+ force: true
2150
+ });
2151
+ }
2152
+ };
2153
+ /** `coffre login`, approved by `person` in their browser, as they would: the CLI's own session. */
2154
+ async function cliLogin(cli, person) {
2155
+ const login = cli.start([
2156
+ "login",
2157
+ cli.origin,
2158
+ "--no-browser"
2159
+ ]);
2160
+ const [, code] = await login.waitFor(/shows the code\s+(\S+)/, "its device login");
2161
+ await person.api.deviceLogins.decide(code, true);
2162
+ const status = await login.exited;
2163
+ expect(status === 0, `coffre login exited ${status}`, login.output());
2164
+ await bearer(cli.origin, cli.session()).me();
2165
+ return {
2166
+ detail: `${person.email}, through \`coffre login\` approved in the browser`,
2167
+ value: cli
2168
+ };
2169
+ }
2170
+ /** The marks a run printed, by check: `✓`, `✗` or `–`. */
2171
+ function marks(output) {
2172
+ const lines = [...output.matchAll(/^ {2}([✓✗–]) (\S.{18}) /gm)];
2173
+ return Object.fromEntries(lines.map(([, mark, name]) => [name.trim(), mark]));
2174
+ }
2175
+ /** The token's run, from CI: as no one, then as the token, which is no owner and skips verification. */
2176
+ async function verifyWithToken(cli, live) {
2177
+ const { canary } = live;
2178
+ const run = await cli.run([
2179
+ "verify",
2180
+ "instance",
2181
+ cli.origin,
2182
+ "--canary",
2183
+ `${canary.project}/${canary.environment}/${canary.key}`
2184
+ ], {
2185
+ COFFRE_TOKEN: live.token,
2186
+ COFFRE_CONFORMANCE_CANARY: canary.value
2187
+ });
2188
+ const seen = marks(run.output);
2189
+ expect(run.code === 0, `coffre verify instance with a token exited ${run.code}`, run.output);
2190
+ expect(seen["token verification"] === "–", "a token that is no owner did not skip verification", run.output);
2191
+ expect(!run.output.includes(live.token) && !run.output.includes(canary.value), "the run printed its token or its canary", run.output);
2192
+ return `${Object.values(seen).filter((mark) => mark === "✓").length} checks ok as no one and as the token, its verification skipped; neither the token nor the canary shown`;
2193
+ }
2194
+ /** What a run as an owner must leave as it was: every member and their grants, but its service; every project and environment. */
2195
+ async function everythingElse(api) {
2196
+ const { members } = await api.members.list();
2197
+ const { projects } = await api.projects.list();
2198
+ return JSON.stringify({
2199
+ members: members.filter(({ member }) => member !== PROBE.service),
2200
+ projects: projects.map(({ slug, archivedAt, environments }) => ({
2201
+ slug,
2202
+ archivedAt,
2203
+ environments: environments.map(({ slug: env }) => env)
2204
+ }))
2205
+ });
2206
+ }
2207
+ /** Signed in as a user, the run says so, and makes nothing; their session stays. Returns what it must leave as it was. */
2208
+ async function verifyAsUser(cli, user, admin) {
2209
+ const before = await everythingElse(admin.api);
2210
+ const run = await cli.run(["verify", "instance"]);
2211
+ expect(run.code === 1, `coffre verify instance as a user exited ${run.code}, not 1`, run.output);
2212
+ expect(marks(run.output).owner === "✗", "the run went on past a user", run.output);
2213
+ expect(/is neither an owner nor a root admin of \S+: nothing was made/.test(run.output), "the run did not say plainly why it stopped", run.output);
2214
+ expect(await admin.api.members.get(PROBE.service).then(() => "there", (error) => error instanceof CoffreError && error.status === 404 ? "absent" : Promise.reject(error)) === "absent", `${PROBE.service} was made for a user`);
2215
+ await bearer(cli.origin, cli.session()).me();
2216
+ expect(await everythingElse(admin.api) === before, "the run changed a member, a grant, a project or an environment for a user");
2217
+ return {
2218
+ detail: `${user.email}, a user, is told plainly; nothing made, the session still signed in`,
2219
+ value: before
2220
+ };
2221
+ }
2222
+ /** One run as the admin, with their `coffre login` session: every check passes, none skipped, and the session stays. Returns its setup's line. */
2223
+ async function verifyAsOwner(cli) {
2224
+ const session = cli.session();
2225
+ const run = await cli.run(["verify", "instance"]);
2226
+ const seen = marks(run.output);
2227
+ expect(run.code === 0, `coffre verify instance as the admin exited ${run.code}`, run.output);
2228
+ const skipped = Object.entries(seen).filter(([, mark]) => mark !== "✓").map(([name]) => name);
2229
+ expect(skipped.length === 0, `the run skipped ${skipped.join(", ")}`, run.output);
2230
+ expect(!SHOWN.test(run.output) && !run.output.includes(session), "the run printed a credential, the session or its canary", SHOWN.exec(run.output)?.[0]);
2231
+ expect(/your session stays/.test(run.output), "the run did not say the session stays", run.output);
2232
+ await bearer(cli.origin, session).me();
2233
+ const setup = /^ {2}✓ setup +(.*)$/m.exec(run.output)?.[1] ?? "";
2234
+ return {
2235
+ detail: `${Object.keys(seen).length} checks ok, the session still signed in; ${setup.split(";")[0]}`,
2236
+ value: setup
2237
+ };
2238
+ }
2239
+ /**
2240
+ * `coffre verify instance` interrupted mid-run by a Ctrl-C: it exits 130
2241
+ * with its credential revoked, the session still signed in, and nothing it
2242
+ * printed shows either, or its canary.
2243
+ */
2244
+ async function verifyInterrupted(cli, admin) {
2245
+ const session = cli.session();
2246
+ const running = cli.start(["verify", "instance"]);
2247
+ try {
2248
+ await running.waitFor(/✓ token reveal/, "its token checks");
2249
+ running.kill("SIGINT");
2250
+ const status = await running.exited;
2251
+ expect(status === 130, `the interrupted run exited ${status}, not 130`, running.output());
2252
+ } finally {
2253
+ running.kill("SIGKILL");
2254
+ }
2255
+ const { tokens } = await admin.api.tokens.list(PROBE.service);
2256
+ expect(tokens.length === 0, `the interrupted run left ${PROBE.service} ${tokens.length} credential(s)`, tokens);
2257
+ await bearer(cli.origin, session).me();
2258
+ expect(!SHOWN.test(running.output()), "the run printed a credential or a canary", SHOWN.exec(running.output())?.[0]);
2259
+ return "Ctrl-C mid-run: exit 130, its credential revoked, the session still signed in; nothing it printed shows either, or its canary";
2260
+ }
2261
+ /**
2262
+ * After the runs: the second found everything the first made; the service
2263
+ * holds no credential; the session is the one `coffre login` made, still
2264
+ * signed in; the canary an operator keeps beside is as it was; nothing
2265
+ * else changed; the runs' reads are in the audit log.
2266
+ */
2267
+ async function verifyLeftovers(cli, admin, setups, before, kept) {
2268
+ expect(setups[0].includes(`the service ${PROBE.service}`), "the first run did not make its service", setups[0]);
2269
+ expect(setups.slice(1).every((line) => line.startsWith("all found")), "a later run made something again", setups);
2270
+ const { tokens } = await admin.api.tokens.list(PROBE.service);
2271
+ expect(tokens.length === 0, `${PROBE.service} still holds ${tokens.length} credential(s)`, tokens);
2272
+ const { sessions } = await bearer(cli.origin, cli.session()).sessions.list();
2273
+ const current = sessions.filter(({ current }) => current);
2274
+ expect(current.length === 1 && current[0].kind === "cli", "the CLI's session is not the one it was", sessions);
2275
+ const place = `${kept.project}/${kept.environment}`;
2276
+ const { values } = await admin.api.secrets.reveal(`${place}/${kept.key}`);
2277
+ expect(values[kept.key] === kept.value, `${place}/${kept.key}, kept beside the run's own, was changed`);
2278
+ expect(await everythingElse(admin.api) === before, "the runs changed a member, a grant, a project or an environment besides their own");
2279
+ const { entries } = await admin.api.audit.list({
2280
+ actor: PROBE.service,
2281
+ limit: 50
2282
+ });
2283
+ expect(entries.length > 0, `the audit log holds no entry by ${PROBE.service}`);
2284
+ return `the second run found all; ${PROBE.service} holds no credential; the CLI's session signed in; ${place}/${kept.key} untouched; nothing else changed; ${entries.length} entries by ${PROBE.service} stay`;
2285
+ }
2286
+ /**
2287
+ * `coffre verify keys`, with the admin's session: this deployment's keys
2288
+ * pass, from the environment; a wrong vault key fails and the right app key
2289
+ * passes, from stdin; a malformed app key fails. No key is ever printed.
2290
+ */
2291
+ async function verifyKeys(cli) {
2292
+ const wrong = Buffer.alloc(32, 7).toString("base64");
2293
+ const runs = [
2294
+ {
2295
+ env: {
2296
+ COFFRE_VAULT_KEY: KEYS.VAULT_KEY,
2297
+ COFFRE_APP_KEY: KEYS.APP_KEY,
2298
+ COFFRE_VAULT_KEY_ID: KEYS.VAULT_KEY_ID
2299
+ },
2300
+ code: 0,
2301
+ vault: "✓",
2302
+ app: "✓"
2303
+ },
2304
+ {
2305
+ input: `${wrong}\n${KEYS.APP_KEY}\n`,
2306
+ code: 1,
2307
+ vault: "✗",
2308
+ app: "✓",
2309
+ said: /✗ vault key +not this instance's vault key/
2310
+ },
2311
+ {
2312
+ env: {
2313
+ COFFRE_VAULT_KEY: KEYS.VAULT_KEY,
2314
+ COFFRE_APP_KEY: "not-a-key"
2315
+ },
2316
+ code: 1,
2317
+ vault: "✓",
2318
+ app: "✗",
2319
+ said: /✗ app key +not an app key/
2320
+ }
2321
+ ];
2322
+ for (const { env, input, code, vault, app, said } of runs) {
2323
+ const run = await cli.run(["verify", "keys"], env, input);
2324
+ const seen = marks(run.output);
2325
+ expect(run.code === code && seen["vault key"] === vault && seen["app key"] === app, `coffre verify keys exited ${run.code}`, run.output);
2326
+ if (said !== void 0) expect(said.test(run.output), "it did not say which key is not right", run.output);
2327
+ for (const key of [
2328
+ KEYS.VAULT_KEY,
2329
+ KEYS.APP_KEY,
2330
+ wrong,
2331
+ "not-a-key"
2332
+ ]) expect(!run.output.includes(key), "a key was printed", run.output);
2333
+ }
2334
+ return "this deployment's keys pass, vault ID included; a wrong vault key and a malformed app key are each named; no key shown";
2335
+ }
2336
+ //#endregion
2337
+ //#region src/checks/surface.ts
2338
+ async function health(deployment) {
2339
+ const { origin } = deployment;
2340
+ const live = await fetch(`${origin}/livez`);
2341
+ expect(live.ok, `/livez answered ${live.status}`);
2342
+ if (deployment.beforeFirstBeat) {
2343
+ const early = await fetch(`${origin}/readyz`);
2344
+ expect(early.status === 503, `/readyz answered ${early.status} before any heartbeat`, await early.text());
2345
+ await deployment.scheduled();
2346
+ }
2347
+ await until("/readyz", async () => (await fetch(`${origin}/readyz`)).ok, 20);
2348
+ const ready = await (await fetch(`${origin}/readyz`)).json();
2349
+ expect(ready.checkpointed === true, "/readyz passed without a checkpoint covering the heartbeat", ready);
2350
+ return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
2351
+ }
2352
+ //#endregion
2810
2353
  //#region src/suite.ts
2811
2354
  /** The names of the checks that failed. */
2812
2355
  async function conform(deployment, options) {
2813
2356
  const report = new Report();
2814
2357
  await report.check("health", {}, () => health(deployment));
2815
- await anonymousChecks(report, deployment.origin, { health: false });
2816
2358
  const admin = await report.check("sign-in", {}, () => signInAdmin(deployment));
2817
2359
  await report.check("page load", { admin }, ({ admin }) => pageLoad(admin));
2818
- const canaries = await report.check("setup", { admin }, ({ admin }) => setUp$1(admin));
2360
+ const canaries = await report.check("setup", { admin }, ({ admin }) => setUp(admin));
2819
2361
  const people = await report.check("personas", {
2820
2362
  admin,
2821
2363
  canaries
@@ -2833,31 +2375,45 @@ async function conform(deployment, options) {
2833
2375
  admin,
2834
2376
  canaries
2835
2377
  }, ({ admin, canaries }) => setUpLive(admin, canaries));
2836
- await tokenChecks(report, deployment.origin, live ?? {});
2837
- const origin = deployment.origin;
2838
- const before = await report.check("probe as a user", {
2839
- admin,
2840
- people
2841
- }, ({ admin, people }) => probeAsUser(origin, people.reader, admin));
2842
- const first = await report.check("probe --sign-in", {
2843
- admin,
2844
- before
2845
- }, ({ admin }) => probeRun(origin, admin));
2846
- const second = await report.check("probe again", {
2847
- admin,
2848
- first
2849
- }, ({ admin }) => probeRun(origin, admin));
2850
- await report.check("probe interrupted", {
2851
- admin,
2852
- second
2853
- }, ({ admin }) => probeInterrupted(origin, admin));
2854
- await report.check("probe leftovers", {
2855
- admin,
2856
- before,
2857
- first,
2858
- second,
2859
- live
2860
- }, ({ admin, before, first, second, live }) => probeLeftovers(origin, admin, [first, second], before, live.canary));
2378
+ const clis = [
2379
+ new Cli(deployment.origin),
2380
+ new Cli(deployment.origin),
2381
+ new Cli(deployment.origin)
2382
+ ];
2383
+ try {
2384
+ await report.check("verify with a token", { live }, ({ live }) => verifyWithToken(clis[0], live));
2385
+ const user = await report.check("login as a user", { people }, ({ people }) => cliLogin(clis[1], people.reader));
2386
+ const before = await report.check("verify as a user", {
2387
+ admin,
2388
+ people,
2389
+ user
2390
+ }, ({ admin, people, user }) => verifyAsUser(user, people.reader, admin));
2391
+ const owner = await report.check("login as the admin", {
2392
+ admin,
2393
+ before
2394
+ }, ({ admin }) => cliLogin(clis[2], admin));
2395
+ const first = await report.check("verify as the admin", { owner }, ({ owner }) => verifyAsOwner(owner));
2396
+ const second = await report.check("verify again", {
2397
+ owner,
2398
+ first
2399
+ }, ({ owner }) => verifyAsOwner(owner));
2400
+ await report.check("verify interrupted", {
2401
+ admin,
2402
+ owner,
2403
+ second
2404
+ }, ({ admin, owner }) => verifyInterrupted(owner, admin));
2405
+ await report.check("verify leftovers", {
2406
+ admin,
2407
+ owner,
2408
+ before,
2409
+ first,
2410
+ second,
2411
+ live
2412
+ }, ({ admin, owner, before, first, second, live }) => verifyLeftovers(owner, admin, [first, second], before, live.canary));
2413
+ await report.check("verify keys", { owner }, ({ owner }) => verifyKeys(owner));
2414
+ } finally {
2415
+ for (const cli of clis) cli.remove();
2416
+ }
2861
2417
  await report.check("offboarding", all, ({ people, canaries }) => offboarding(deployment, people, canaries));
2862
2418
  await report.check("bulk limit", { people }, ({ people }) => bulkLimit$1(people, options.bulkLimit));
2863
2419
  await report.check("checkpoints", { people }, ({ people }) => checkpoints(deployment, people));
@@ -2889,27 +2445,12 @@ async function conform(deployment, options) {
2889
2445
  await report.check("tail deleted", { people }, ({ people }) => deletedTail(deployment, people));
2890
2446
  return report.failed;
2891
2447
  }
2892
- /**
2893
- * What can be checked of an instance someone else runs: as no one, and with
2894
- * a token that reads a canary when given one, or, with `signIn`, as an owner
2895
- * who signs the probe in and lets it set up its own token. With a token,
2896
- * nothing is written but the audit log's entries for the token's reads.
2897
- */
2898
- async function probe(origin, live) {
2899
- const report = new Report();
2900
- await anonymousChecks(report, origin, { health: true });
2901
- if (live.signIn !== void 0) await signedInChecks(report, origin, live.signIn);
2902
- else if (live.token !== void 0) await tokenChecks(report, origin, live);
2903
- return report.failed;
2904
- }
2905
2448
  //#endregion
2906
2449
  //#region src/main.ts
2907
2450
  const USAGE = `usage:
2908
2451
  coffre-conformance workers [<dir>] --postgres <owner URL> --runtime <coffre_runtime URL>
2909
2452
  --vault-runtime <coffre_vault_runtime URL> [options]
2910
2453
  coffre-conformance node [<dir>] [options]
2911
- coffre-conformance probe <url> [--token <service token> --canary <project>/<env>/<KEY>[=<value>]]
2912
- coffre-conformance probe <url> --sign-in
2913
2454
 
2914
2455
  <dir> the deployment, as \`coffre init\` wrote it (default: here)
2915
2456
  --port <n> coffre's port; the IdP gets the next, wrangler's inspector the one after (3082)
@@ -2919,27 +2460,8 @@ const USAGE = `usage:
2919
2460
  --vault-runtime <url>
2920
2461
  workers: the same server as coffre_vault_runtime, the login the vault runs as
2921
2462
 
2922
- probe checks a running instance from outside:
2923
- as no one health, headers, every route refusing no one, changes from
2924
- another site refused, /api/auth, nothing like a value shown
2925
- with --token a service token that reads the canary's environment and
2926
- holds auditor on its project: its value nowhere but its
2927
- reveal, the reveal audited, nothing else in reach
2928
- --token or COFFRE_TOKEN
2929
- --canary the value after =, or in COFFRE_CONFORMANCE_CANARY, or on
2930
- stdin, so it stays out of the shell's history
2931
- with --sign-in an owner approves a device login in the browser, as for
2932
- \`coffre login\`; the probe finds or makes conformance/live
2933
- and token:conformance-probe, issues it a credential, writes
2934
- a fresh canary, runs the token's checks, then verifies the
2935
- whole audit log as the owner. The credential is revoked and
2936
- the session ended however the run ends; neither it nor the
2937
- canary is ever shown
2938
-
2939
- Each run with a token adds a few entries to the instance's audit log, which
2940
- is append-only, so they stay: the canary's read, and the reads it was refused.
2941
- It changes nothing else. A run with --sign-in leaves its project, environment
2942
- and service for the next, and writes its canary and its grants.`;
2463
+ To check an instance that is running already, from outside, use the CLI:
2464
+ \`coffre verify instance\`.`;
2943
2465
  const { values, positionals } = parseArgs({
2944
2466
  allowPositionals: true,
2945
2467
  options: {
@@ -2954,12 +2476,6 @@ const { values, positionals } = parseArgs({
2954
2476
  postgres: { type: "string" },
2955
2477
  runtime: { type: "string" },
2956
2478
  "vault-runtime": { type: "string" },
2957
- token: { type: "string" },
2958
- canary: { type: "string" },
2959
- "sign-in": {
2960
- type: "boolean",
2961
- default: false
2962
- },
2963
2479
  help: {
2964
2480
  type: "boolean",
2965
2481
  short: "h"
@@ -2968,46 +2484,7 @@ const { values, positionals } = parseArgs({
2968
2484
  });
2969
2485
  const [command, target] = positionals;
2970
2486
  if (values.help || command === void 0) exit(values.help ? 0 : 2, USAGE);
2971
- if (command === "probe") {
2972
- if (target === void 0) exit(2, USAGE);
2973
- const origin = new URL(target).origin;
2974
- if (values["sign-in"]) {
2975
- if (values.token !== void 0 || values.canary !== void 0) exit(2, "--sign-in sets up its own token and canary: no --token or --canary with it");
2976
- console.log(`coffre-conformance: probing ${origin}, as no one and signed in`);
2977
- console.log(` (it keeps ${PROBE.project}/${PROBE.environment} and ${PROBE.service} for the next run, and its reads stay in the audit log, for good)`);
2978
- const failed = await probe(origin, { signIn: ({ url, code }) => {
2979
- console.log(`\n Approve the probe's sign-in, as an owner, at\n\n ${url}\n\n and check that it shows the code ${code}. Waiting for you…\n`);
2980
- if (process.stdout.isTTY) openBrowser(url);
2981
- } });
2982
- exit(failed.length === 0 ? 0 : 1, summary(failed));
2983
- }
2984
- const token = values.token ?? process.env.COFFRE_TOKEN;
2985
- let canary;
2986
- if (token !== void 0) {
2987
- if (values.canary === void 0) exit(2, "with a token, name its canary: --canary <project>/<environment>/<KEY>[=<value>]");
2988
- try {
2989
- canary = parseCanary(values.canary, values.canary.includes("=") ? void 0 : await canaryValue());
2990
- } catch (error) {
2991
- exit(2, error instanceof Error ? error.message : String(error));
2992
- }
2993
- }
2994
- console.log(`coffre-conformance: probing ${origin}${token === void 0 ? ", as no one" : ", as no one and with a token"}`);
2995
- if (token !== void 0) console.log(" (the token's reads add a few entries to the instance's audit log, for good)");
2996
- const failed = await probe(origin, {
2997
- token,
2998
- canary
2999
- });
3000
- exit(failed.length === 0 ? 0 : 1, summary(failed));
3001
- }
3002
- /** The canary's value from the environment, or the first line of stdin when it is piped. */
3003
- async function canaryValue() {
3004
- const given = process.env.COFFRE_CONFORMANCE_CANARY;
3005
- if (given !== void 0 && given !== "") return given;
3006
- if (process.stdin.isTTY) return void 0;
3007
- let text = "";
3008
- for await (const chunk of process.stdin) text += String(chunk);
3009
- return text.split(/\r?\n/)[0];
3010
- }
2487
+ if (command === "probe") exit(2, "coffre-conformance probe is now `coffre verify instance`, in the coffre CLI: npx @coffre/cli verify instance");
3011
2488
  if (command !== "workers" && command !== "node") exit(2, USAGE);
3012
2489
  const kind = command;
3013
2490
  const dir = resolve(target ?? ".");