@coffre/conformance 0.1.5 → 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 } 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 {
@@ -318,517 +296,6 @@ var Report = class {
318
296
  }
319
297
  };
320
298
  //#endregion
321
- //#region src/routes.ts
322
- function getCalls({ places, secrets, members, services }) {
323
- const first = places[0];
324
- return {
325
- "GET /me": [{ params: {} }],
326
- "GET /projects": [{ params: {} }],
327
- "GET /secrets/:project/:environment": places.map((params) => ({ params })),
328
- "GET /secrets/:project/:environment/:key/versions": secrets.map((params) => ({ params })),
329
- "GET /members": [{ params: {} }, ...first === void 0 ? [] : [{
330
- params: {},
331
- input: { path: `${first.project}/${first.environment}` }
332
- }]],
333
- "GET /members/:member": members.map((member) => ({ params: { member } })),
334
- "GET /members/:member/tokens": services.map((member) => ({ params: { member } })),
335
- "GET /sessions": [{ params: {} }],
336
- "GET /identities": [{ params: {} }],
337
- "GET /device-logins/:code": [{ params: { code: "BCDF-GHJK" } }],
338
- "GET /syncs/providers": [{ params: {} }],
339
- "GET /syncs/:project/:environment": places.map((params) => ({ params })),
340
- "GET /audit": [{
341
- params: {},
342
- input: { limit: 500 }
343
- }, {
344
- params: {},
345
- input: {
346
- limit: 500,
347
- detail: "1"
348
- }
349
- }],
350
- "GET /audit/verification": [{ params: {} }]
351
- };
352
- }
353
- /** Each GET call as a URL, with its parameters and query filled in. */
354
- function getUrls(origin, calls) {
355
- const urls = [];
356
- for (const [key, asks] of Object.entries(calls)) for (const { params, input } of asks) urls.push({
357
- key,
358
- url: address(origin, key, params, input)
359
- });
360
- return urls;
361
- }
362
- /** Every route, whatever its method. */
363
- const EVERY_ROUTE = {
364
- "GET /me": true,
365
- "GET /projects": true,
366
- "PUT /projects/:project": true,
367
- "PATCH /projects/:project": true,
368
- "PUT /projects/:project/:environment": true,
369
- "PATCH /projects/:project/:environment": true,
370
- "GET /secrets/:project/:environment": true,
371
- "PATCH /secrets/:project/:environment": true,
372
- "PATCH /secrets/:project/:environment/:key": true,
373
- "GET /secrets/:project/:environment/:key/versions": true,
374
- "POST /secrets/:project/:environment/:key/restore": true,
375
- "POST /reveals": true,
376
- "GET /members": true,
377
- "GET /members/:member": true,
378
- "PUT /members/:member": true,
379
- "DELETE /members/:member": true,
380
- "GET /members/:member/tokens": true,
381
- "POST /members/:member/tokens": true,
382
- "DELETE /members/:member/tokens/:id": true,
383
- "PATCH /access/:member": true,
384
- "GET /sessions": true,
385
- "DELETE /sessions/:id": true,
386
- "GET /identities": true,
387
- "DELETE /identities/:id": true,
388
- "GET /device-logins/:code": true,
389
- "POST /device-logins/:code": true,
390
- "GET /syncs/providers": true,
391
- "GET /syncs/:project/:environment": true,
392
- "POST /syncs/:project/:environment": true,
393
- "PATCH /syncs/by-id/:id": true,
394
- "DELETE /syncs/by-id/:id": true,
395
- "POST /syncs/by-id/:id/runs": true,
396
- "GET /audit": true,
397
- "GET /audit/verification": true
398
- };
399
- /**
400
- * Every route as a method and a URL, each parameter a made-up value: what
401
- * a caller with no right to any of them would send.
402
- */
403
- function everyRoute(origin) {
404
- return Object.keys(EVERY_ROUTE).map((key) => {
405
- const [method, pattern] = key.split(" ");
406
- return {
407
- key,
408
- method,
409
- url: `${origin}/api${pattern.replace(/:(\w+)/g, (_, name) => encodeURIComponent(name === "member" ? "token:conformance-nobody" : "conformance-nobody"))}`
410
- };
411
- });
412
- }
413
- function address(origin, key, params, input) {
414
- const path = key.slice(4).replace(/:(\w+)/g, (_, name) => encodeURIComponent(params[name]));
415
- const url = new URL(`${origin}/api${path}`);
416
- for (const [name, value] of Object.entries(input ?? {})) url.searchParams.set(name, String(value));
417
- return url.href;
418
- }
419
- //#endregion
420
- //#region src/checks/surface.ts
421
- async function health(deployment) {
422
- const { origin } = deployment;
423
- const live = await fetch(`${origin}/livez`);
424
- expect(live.ok, `/livez answered ${live.status}`);
425
- if (deployment.beforeFirstBeat) {
426
- const early = await fetch(`${origin}/readyz`);
427
- expect(early.status === 503, `/readyz answered ${early.status} before any heartbeat`, await early.text());
428
- await deployment.scheduled();
429
- }
430
- await until("/readyz", async () => (await fetch(`${origin}/readyz`)).ok, 20);
431
- const ready = await (await fetch(`${origin}/readyz`)).json();
432
- expect(ready.checkpointed === true, "/readyz passed without a checkpoint covering the heartbeat", ready);
433
- return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
434
- }
435
- /** An instance someone else runs: up, and its scheduled job beating. */
436
- async function reachable(origin) {
437
- const live = await fetch(`${origin}/livez`);
438
- expect(live.ok, `/livez answered ${live.status}`);
439
- const ready = await fetch(`${origin}/readyz`);
440
- expect(ready.ok, `/readyz answered ${ready.status}: is the scheduled job running?`, await ready.text());
441
- return "/livez and /readyz";
442
- }
443
- async function headers(origin) {
444
- const anonymous = await fetch(`${origin}/api/me`);
445
- expect(anonymous.status === 401, `/api/me answered ${anonymous.status} to no one`);
446
- securityHeaders(anonymous, "a refusal");
447
- const login = await fetch(`${origin}/login`);
448
- expect(login.status === 200, `/login answered ${login.status}`);
449
- const csp = securityHeaders(login, "/login");
450
- const html = await login.text();
451
- const nonce = /'nonce-([^']+)'/.exec(csp)[1];
452
- expect(html.includes(`nonce="${nonce}"`), "/login's scripts do not carry the policy's nonce");
453
- expect(!securityHeaders(await fetch(`${origin}/login`), "/login").includes(`'nonce-${nonce}'`), "two pages were served with the same nonce");
454
- const asset = /\/_coffre\/assets\/[\w.-]+\.js/.exec(html)?.[0];
455
- expect(asset !== void 0, "/login loads no script from /_coffre/assets/", html.slice(0, 2e3));
456
- const script = await fetch(`${origin}${asset}`);
457
- expect(script.ok && /javascript/.test(script.headers.get("content-type") ?? ""), `${asset} answered ${script.status} ${script.headers.get("content-type")}`);
458
- const allowed = (await fetch(`${origin}/api/me`, { headers: { origin: "https://attacker.example" } })).headers.get("access-control-allow-origin");
459
- expect(allowed === null, `the API allows another origin to read it: ${allowed}`);
460
- return `a fresh CSP nonce per page, frames refused, nosniff; no CORS; ${asset} served`;
461
- }
462
- function securityHeaders(response, what) {
463
- const csp = response.headers.get("content-security-policy") ?? "";
464
- expect(/script-src 'self' 'nonce-[^']+'/.test(csp), `${what}: no nonce-based script-src`, csp);
465
- expect(csp.includes("frame-ancestors 'none'"), `${what}: frames not refused`, csp);
466
- expect(response.headers.get("x-content-type-options") === "nosniff", `${what}: no nosniff`);
467
- expect(response.headers.get("x-frame-options") === "DENY", `${what}: no x-frame-options DENY`);
468
- expect(response.headers.get("cross-origin-resource-policy") === "same-origin", `${what}: other sites may embed it`);
469
- expect(/no-store/.test(response.headers.get("cache-control") ?? ""), `${what}: may be cached`);
470
- if (response.url.startsWith("https:")) {
471
- const hsts = response.headers.get("strict-transport-security") ?? "";
472
- expect(/max-age=\d{7,}/.test(hsts), `${what}: no strict-transport-security for months or more`, hsts);
473
- }
474
- return csp;
475
- }
476
- //#endregion
477
- //#region src/checks/live.ts
478
- /** The page anyone may open. Every other page sends no one to /login. */
479
- const OPEN_PAGES = ["/login"];
480
- /** The pages behind sign-in, whatever the instance holds. */
481
- const CLOSED_PAGES = [
482
- "/",
483
- "/account",
484
- "/access",
485
- "/audit",
486
- "/auth/device",
487
- "/settings",
488
- "/projects",
489
- "/users",
490
- "/tokens",
491
- "/unregistered"
492
- ];
493
- /** A made-up place and member, which no instance has. */
494
- const NOWHERE = {
495
- project: "conformance-nowhere",
496
- environment: "none"
497
- };
498
- const NOBODY = "token:conformance-nobody";
499
- /** Parse `<project>/<environment>/<KEY>=<value>`, or the path alone with the value given apart. */
500
- function parseCanary(text, value) {
501
- const at = text.indexOf("=");
502
- const path = at === -1 ? text : text.slice(0, at);
503
- const given = at === -1 ? value : text.slice(at + 1);
504
- const parts = path.split("/");
505
- if (parts.length !== 3 || parts.some((part) => part === "")) throw new Error(`the canary is <project>/<environment>/<KEY>, not "${path}"`);
506
- if (given === void 0 || given === "") throw new Error("the canary has no value: pass it after =, on stdin, or in COFFRE_CONFORMANCE_CANARY");
507
- const [project, environment, key] = parts;
508
- return {
509
- project,
510
- environment,
511
- key,
512
- value: given
513
- };
514
- }
515
- /** The checks anyone can run: no sign-in, nothing written. `health` false when the caller checked it already. */
516
- async function anonymousChecks(report, origin, options) {
517
- if (options.health) await report.check("health", {}, () => reachable(origin));
518
- await report.check("headers", {}, () => headers(origin));
519
- await report.check("anonymous api", {}, () => anonymousApi(origin));
520
- await report.check("forged cross-site", {}, () => forgedCrossSite(origin));
521
- await report.check("sign-in info", {}, () => signinInfo(origin));
522
- await report.check("anonymous answers", {}, () => anonymousAnswers(origin));
523
- }
524
- /** The checks with a service token that reads the canary, and audits its project. */
525
- async function tokenChecks(report, origin, setup) {
526
- const api = setup.token === void 0 ? void 0 : bearer(origin, setup.token);
527
- const token = await report.check("token", {
528
- api,
529
- canary: setup.canary
530
- }, ({ api, canary }) => whoIsToken(origin, api, canary));
531
- const needs = {
532
- api,
533
- canary: setup.canary,
534
- token,
535
- secret: setup.token
536
- };
537
- await report.check("token reveal", needs, ({ api, canary, token }) => tokenReveal(api, canary, token));
538
- await report.check("token scan", needs, ({ canary, secret }) => tokenScan(origin, secret, canary));
539
- await report.check("token scope", needs, ({ api, canary }) => tokenScope(api, canary));
540
- await report.check("token verification", { api }, ({ api }) => tokenVerification(api));
541
- }
542
- /** Every route, whatever its method, turns away a caller with no credential, and says nothing else. */
543
- async function anonymousApi(origin) {
544
- const routes = everyRoute(origin);
545
- for (const { key, method, url } of routes) {
546
- const response = await fetch(url, {
547
- method,
548
- headers: { "content-type": "application/json" },
549
- body: method === "GET" ? void 0 : "{}"
550
- });
551
- const text = await response.text();
552
- expect(response.status === 401, `${key} answered ${response.status} to no one`, text);
553
- expect(onlyRefusal(text), `${key} refused no one with more than a refusal`, text);
554
- }
555
- return `${routes.length} routes, every method: 401, and nothing but the refusal`;
556
- }
557
- /**
558
- * A change sent with a session cookie from another site's page is refused
559
- * before the cookie is even looked at, so a made-up one shows it: a real
560
- * cookie would get the same answer. Behind Cloudflare Access the same holds
561
- * for its cookie and assertion.
562
- */
563
- async function forgedCrossSite(origin) {
564
- const changes = everyRoute(origin).filter((route) => route.method !== "GET");
565
- const forged = {
566
- cookie: "coffre_session=conformance-forged; __Host-coffre_session=conformance-forged; CF_Authorization=conformance-forged",
567
- "cf-access-jwt-assertion": "conformance-forged",
568
- origin: "https://attacker.example",
569
- "sec-fetch-site": "cross-site",
570
- "content-type": "application/json"
571
- };
572
- for (const { key, method, url } of [...changes, {
573
- key: "POST /auth/signout",
574
- method: "POST",
575
- url: `${origin}/auth/signout`
576
- }]) {
577
- const response = await fetch(url, {
578
- method,
579
- headers: forged,
580
- body: "{}",
581
- redirect: "manual"
582
- });
583
- const text = await response.text();
584
- expect(response.status === 403, `${key} from another site answered ${response.status}`, text);
585
- }
586
- return `${changes.length + 1} changes, sign-out included, from another site with a session cookie: 403`;
587
- }
588
- /** `GET /api/auth` names how to sign in, and nothing more. */
589
- async function signinInfo(origin) {
590
- const response = await fetch(`${origin}/api/auth`);
591
- expect(response.ok, `/api/auth answered ${response.status}`);
592
- const info = await response.json();
593
- expect(sameKeys(info, ["access", "signin"]), "/api/auth says more than how to sign in", info);
594
- expect(info.signin === null !== (info.access === null), "/api/auth names neither or both ways in", info);
595
- if (info.access !== null) {
596
- expect(sameKeys(info.access, ["assertion"]) && info.access.assertion === false, "/api/auth says more of Access than whether it vouched", info);
597
- return "Cloudflare Access, and nothing more";
598
- }
599
- const signin = info.signin;
600
- expect(sameKeys(signin, [
601
- "note",
602
- "providers",
603
- "title"
604
- ]), "/api/auth says more of its sign-in than a page needs", signin);
605
- for (const provider of signin.providers) expect(sameKeys(provider, [
606
- "brand",
607
- "id",
608
- "label"
609
- ]), `/api/auth says more of ${provider.id} than its button`, provider);
610
- return `coffre's sign-in through ${signin.providers.map((provider) => provider.id).join(", ")}, and nothing more`;
611
- }
612
- /**
613
- * Nothing that could be a stored value in what no one is shown. Without a
614
- * canary this is a best effort: the API's refusals are checked to be only
615
- * refusals above, every closed page must send no one to /login with an
616
- * empty body, and the open pages must carry no credential coffre issues.
617
- */
618
- async function anonymousAnswers(origin) {
619
- const pages = [
620
- ...CLOSED_PAGES,
621
- `/projects/${NOWHERE.project}`,
622
- `/projects/${NOWHERE.project}/${NOWHERE.environment}`
623
- ];
624
- for (const path of pages) {
625
- let at = path;
626
- for (let hop = 0; at !== "/login"; hop++) {
627
- const response = await fetch(`${origin}${at}`, { redirect: "manual" });
628
- const text = await response.text();
629
- const to = new URL(response.headers.get("location") ?? at, origin);
630
- 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));
631
- expect(text.trim().length < 512, `${at} sent no one a body with its redirect`, text.slice(0, 2e3));
632
- at = to.pathname;
633
- }
634
- }
635
- for (const path of OPEN_PAGES) {
636
- const response = await fetch(`${origin}${path}`, { redirect: "manual" });
637
- const text = await response.text();
638
- expect(response.status === 200, `${path} answered ${response.status}`);
639
- const issued = /coffre_(svc|cli|web)_[A-Za-z0-9_-]{20,}/.exec(text);
640
- expect(issued === null, `${path} carries a credential coffre issues`, issued?.[0]);
641
- }
642
- return `best effort, without a canary: ${pages.length} closed pages send no one to /login with nothing else; /login carries no credential`;
643
- }
644
- /** The token is a service's, and reads the canary's environment. */
645
- async function whoIsToken(origin, api, canary) {
646
- 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");
647
- const me = await api.me();
648
- expect(me.principal.type === "service", `the token is ${me.principal.type}:${me.principal.id}'s, not a service's`);
649
- const member = `token:${me.principal.id}`;
650
- const place = `${canary.project}/${canary.environment}`;
651
- expect(me.environments.find((env) => `${env.project}/${env.environment}` === place)?.permissions.includes("secret.read"), `${member} cannot read ${place}`, me.environments);
652
- const { keys } = await api.secrets.list(place);
653
- expect(keys.some((key) => key.key === canary.key), `${place} holds no ${canary.key}`, keys.map((key) => key.key));
654
- return {
655
- detail: `${member}, reading ${place}`,
656
- value: { member }
657
- };
658
- }
659
- /** Reveal the canary once, and find its `secret.read` in the audit log, by the reveal's request. */
660
- async function tokenReveal(api, canary, token) {
661
- const path = `${canary.project}/${canary.environment}`;
662
- const { operationId, values } = await api.secrets.reveal(`${path}/${canary.key}`);
663
- expect(values[canary.key] === canary.value, `${path}/${canary.key} is not the value given as the canary`);
664
- let entries;
665
- try {
666
- ({entries} = await api.audit.list({
667
- path,
668
- actor: token.member,
669
- limit: 50
670
- }));
671
- } catch (error) {
672
- 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`);
673
- throw error;
674
- }
675
- const read = entries.filter((entry) => entry.operationId === operationId);
676
- expect(read.length === 1, `the reveal is logged ${read.length} times, not once`, entries.slice(0, 5));
677
- const [entry] = read;
678
- 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);
679
- return `one secret.read of ${canary.key}, entry ${entry.seq}, under request ${entry.requestId}`;
680
- }
681
- /**
682
- * The canary's value, in any answer to a GET route as the token or as no
683
- * one, or in any page. The reveal is the only answer allowed to carry it.
684
- */
685
- async function tokenScan(origin, token, canary) {
686
- const me = await bearer(origin, token).me();
687
- const member = `token:${me.principal.id}`;
688
- const listed = me.environments.map(({ project, environment }) => ({
689
- project,
690
- environment
691
- }));
692
- const calls = getCalls({
693
- places: [...listed, NOWHERE],
694
- secrets: [{
695
- project: canary.project,
696
- environment: canary.environment,
697
- key: canary.key
698
- }, {
699
- ...NOWHERE,
700
- key: "NONE"
701
- }],
702
- members: [
703
- member,
704
- NOBODY,
705
- "user:nobody@conformance.example"
706
- ],
707
- services: [member, NOBODY]
708
- });
709
- const forms = [
710
- canary.value,
711
- Buffer.from(canary.value).toString("base64"),
712
- Buffer.from(canary.value).toString("hex")
713
- ];
714
- const leaks = [];
715
- const callers = [["the token", { authorization: `Bearer ${token}` }], ["no one", {}]];
716
- let answers = 0;
717
- const look = async (what, url, headers) => {
718
- const text = await (await fetch(url, {
719
- headers,
720
- redirect: "manual"
721
- })).text();
722
- answers++;
723
- if (forms.some((form) => text.includes(form))) leaks.push(what);
724
- };
725
- for (const { key, url } of getUrls(origin, calls)) for (const [name, headers] of callers) await look(`${key} as ${name}`, url, headers);
726
- const pages = [
727
- ...OPEN_PAGES,
728
- ...CLOSED_PAGES,
729
- ...listed.flatMap(({ project, environment }) => [`/projects/${project}`, `/projects/${project}/${environment}`])
730
- ];
731
- for (const path of new Set(pages)) for (const [name, headers] of callers) await look(`the page ${path} as ${name}`, `${origin}${path}`, headers);
732
- expect(leaks.length === 0, "the canary's value was found outside its reveal", leaks);
733
- 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`;
734
- }
735
- /** The token reaches the canary's project and nothing else: not another environment, project or member. */
736
- async function tokenScope(api, canary) {
737
- const { projects } = await api.projects.list();
738
- const seen = projects.map((project) => project.slug);
739
- expect(seen.length === 1 && seen[0] === canary.project, `the token sees ${seen.join(", ") || "no project"}, not only ${canary.project}`);
740
- const me = await api.me();
741
- const own = `${canary.project}/${canary.environment}`;
742
- const reads = me.environments.filter((env) => env.permissions.includes("secret.read")).map((env) => `${env.project}/${env.environment}`);
743
- expect(reads.length === 1 && reads[0] === own, `the token reads ${reads.join(", ")}, not only ${own}`);
744
- const more = [...new Set(me.environments.flatMap((env) => env.permissions))].filter((permission) => permission !== "secret.read" && permission !== "audit.read");
745
- expect(more.length === 0, `the token holds more than reading: ${more.join(", ")}`);
746
- const others = projects[0].environments.map((env) => `${canary.project}/${env.slug}`).filter((path) => path !== own);
747
- const nowhere = `${NOWHERE.project}/${NOWHERE.environment}`;
748
- let refusals = 0;
749
- for (const path of [...others, nowhere]) {
750
- await refused(`the token listed ${path}`, api.secrets.list(path));
751
- await refused(`the token revealed ${path}`, api.secrets.reveal(path));
752
- await refused(`the token read ${path}'s syncs`, api.syncs.list(path));
753
- refusals += 3;
754
- }
755
- await refused(`the token read ${nowhere}'s audit`, api.audit.list({
756
- path: nowhere,
757
- limit: 1
758
- }));
759
- await refused("the token listed the members", api.members.list());
760
- await refused(`the token read ${NOBODY}`, api.members.get(NOBODY));
761
- refusals += 3;
762
- try {
763
- const { entries } = await api.audit.list({ limit: 500 });
764
- const outside = entries.filter((entry) => entry.project !== null && entry.project !== canary.project);
765
- expect(outside.length === 0, `the token reads audit entries about ${[...new Set(outside.map((entry) => entry.project))].join(", ")}`);
766
- } catch (error) {
767
- if (!(error instanceof CoffreError && error.status === 403)) throw error;
768
- }
769
- const elsewhere = others.length === 0 ? "no other environment" : `${others.length} other environment${others.length === 1 ? "" : "s"}`;
770
- return `only ${own}; ${refusals} reads elsewhere refused: ${elsewhere} of ${canary.project}, a made-up place, the members`;
771
- }
772
- async function tokenVerification(api) {
773
- let verified;
774
- try {
775
- verified = await api.audit.verify();
776
- } catch (error) {
777
- if (error instanceof CoffreError && error.status === 403) throw new Skip("verification is for owners and root admins, which this token is not: not checked");
778
- throw error;
779
- }
780
- expect(verified.ok, "the audit log does not verify", verified);
781
- return `${verified.entries} entries verify, through entry ${verified.through}`;
782
- }
783
- /** `{ error, message }` and nothing else. */
784
- function onlyRefusal(text) {
785
- try {
786
- return sameKeys(JSON.parse(text), ["error", "message"]);
787
- } catch {
788
- return false;
789
- }
790
- }
791
- function sameKeys(value, keys) {
792
- return typeof value === "object" && value !== null && JSON.stringify(Object.keys(value).sort()) === JSON.stringify(keys);
793
- }
794
- //#endregion
795
- //#region src/database.ts
796
- async function postgres(url) {
797
- const client = new pg.Client(postgresConnection(url));
798
- await client.connect();
799
- return {
800
- engine: "postgres",
801
- query: async (statement, params = []) => (await client.query(statement, params)).rows,
802
- exec: async (statements) => void await client.query(statements),
803
- close: () => client.end()
804
- };
805
- }
806
- /** A SQLite file, perhaps open in another process: it waits out their locks. */
807
- function sqlite(file) {
808
- const db = new DatabaseSync(file, { timeout: 5e3 });
809
- return {
810
- engine: "sqlite",
811
- query: async (statement, params = []) => db.prepare(statement).all(...params),
812
- exec: async (statements) => db.exec(statements),
813
- close: async () => db.close()
814
- };
815
- }
816
- async function using(open, use) {
817
- const sql = await open;
818
- try {
819
- return await use(sql);
820
- } finally {
821
- await sql.close();
822
- }
823
- }
824
- //#endregion
825
- //#region src/fixtures.ts
826
- const KEYS = {
827
- VAULT_KEY_ID: "vault-conformance-1",
828
- VAULT_KEY: "Y29mZnJlLWxvY2FsLWRldi1rZWstMzItYnl0ZXMhISE=",
829
- APP_KEY: "Y29mZnJlLWxvY2FsLWF1ZGl0LWNoYWluLWtleS0zMmI="
830
- };
831
- //#endregion
832
299
  //#region src/harness.ts
833
300
  const ROOT_ADMIN = "root@conformance.example";
834
301
  async function boot(kind, at, options) {
@@ -1040,6 +507,68 @@ function withDatabase(url, database) {
1040
507
  return parsed.href;
1041
508
  }
1042
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;
516
+ }
517
+ /** Whether coffre left this browser a cookie. */
518
+ get hasCookies() {
519
+ return this.#jar.size > 0;
520
+ }
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;
539
+ }
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
+ });
551
+ }
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
+ });
570
+ }
571
+ //#endregion
1043
572
  //#region src/checks/people.ts
1044
573
  const PROJECT = "conformance";
1045
574
  const DEV = `${PROJECT}/dev`;
@@ -2358,6 +1887,55 @@ async function middleCut(deployment, { admin }) {
2358
1887
  return `entries ${seq} and ${seq + 1}, before the latest signed prefix, cut: checkpoint log_broken, readiness red; restored and recovered`;
2359
1888
  }
2360
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
2361
1939
  //#region src/checks/canaries.ts
2362
1940
  function calls(people) {
2363
1941
  const places = [
@@ -2492,12 +2070,291 @@ function files(path) {
2492
2070
  return Buffer.concat([path, `${path}-wal`].filter((file) => existsSync(file)).map((file) => readFileSync(file)));
2493
2071
  }
2494
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
2495
2353
  //#region src/suite.ts
2496
2354
  /** The names of the checks that failed. */
2497
2355
  async function conform(deployment, options) {
2498
2356
  const report = new Report();
2499
2357
  await report.check("health", {}, () => health(deployment));
2500
- await anonymousChecks(report, deployment.origin, { health: false });
2501
2358
  const admin = await report.check("sign-in", {}, () => signInAdmin(deployment));
2502
2359
  await report.check("page load", { admin }, ({ admin }) => pageLoad(admin));
2503
2360
  const canaries = await report.check("setup", { admin }, ({ admin }) => setUp(admin));
@@ -2518,7 +2375,45 @@ async function conform(deployment, options) {
2518
2375
  admin,
2519
2376
  canaries
2520
2377
  }, ({ admin, canaries }) => setUpLive(admin, canaries));
2521
- await tokenChecks(report, deployment.origin, live ?? {});
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
+ }
2522
2417
  await report.check("offboarding", all, ({ people, canaries }) => offboarding(deployment, people, canaries));
2523
2418
  await report.check("bulk limit", { people }, ({ people }) => bulkLimit$1(people, options.bulkLimit));
2524
2419
  await report.check("checkpoints", { people }, ({ people }) => checkpoints(deployment, people));
@@ -2550,24 +2445,12 @@ async function conform(deployment, options) {
2550
2445
  await report.check("tail deleted", { people }, ({ people }) => deletedTail(deployment, people));
2551
2446
  return report.failed;
2552
2447
  }
2553
- /**
2554
- * What can be checked of an instance someone else runs: as no one, and with
2555
- * a token that reads a canary when given one. Nothing is written but the
2556
- * audit log's entries for the token's reads.
2557
- */
2558
- async function probe(origin, live) {
2559
- const report = new Report();
2560
- await anonymousChecks(report, origin, { health: true });
2561
- if (live.token !== void 0) await tokenChecks(report, origin, live);
2562
- return report.failed;
2563
- }
2564
2448
  //#endregion
2565
2449
  //#region src/main.ts
2566
2450
  const USAGE = `usage:
2567
2451
  coffre-conformance workers [<dir>] --postgres <owner URL> --runtime <coffre_runtime URL>
2568
2452
  --vault-runtime <coffre_vault_runtime URL> [options]
2569
2453
  coffre-conformance node [<dir>] [options]
2570
- coffre-conformance probe <url> [--token <service token> --canary <project>/<env>/<KEY>[=<value>]]
2571
2454
 
2572
2455
  <dir> the deployment, as \`coffre init\` wrote it (default: here)
2573
2456
  --port <n> coffre's port; the IdP gets the next, wrangler's inspector the one after (3082)
@@ -2577,19 +2460,8 @@ const USAGE = `usage:
2577
2460
  --vault-runtime <url>
2578
2461
  workers: the same server as coffre_vault_runtime, the login the vault runs as
2579
2462
 
2580
- probe checks a running instance from outside, and writes nothing to it:
2581
- as no one health, headers, every route refusing no one, changes from
2582
- another site refused, /api/auth, nothing like a value shown
2583
- with --token a service token that reads the canary's environment and
2584
- holds auditor on its project: its value nowhere but its
2585
- reveal, the reveal audited, nothing else in reach
2586
- --token or COFFRE_TOKEN
2587
- --canary the value after =, or in COFFRE_CONFORMANCE_CANARY, or on
2588
- stdin, so it stays out of the shell's history
2589
-
2590
- Each run with a token adds a few entries to the instance's audit log, which
2591
- is append-only, so they stay: the canary's read, and the reads it was refused.
2592
- It changes nothing else.`;
2463
+ To check an instance that is running already, from outside, use the CLI:
2464
+ \`coffre verify instance\`.`;
2593
2465
  const { values, positionals } = parseArgs({
2594
2466
  allowPositionals: true,
2595
2467
  options: {
@@ -2604,8 +2476,6 @@ const { values, positionals } = parseArgs({
2604
2476
  postgres: { type: "string" },
2605
2477
  runtime: { type: "string" },
2606
2478
  "vault-runtime": { type: "string" },
2607
- token: { type: "string" },
2608
- canary: { type: "string" },
2609
2479
  help: {
2610
2480
  type: "boolean",
2611
2481
  short: "h"
@@ -2614,36 +2484,7 @@ const { values, positionals } = parseArgs({
2614
2484
  });
2615
2485
  const [command, target] = positionals;
2616
2486
  if (values.help || command === void 0) exit(values.help ? 0 : 2, USAGE);
2617
- if (command === "probe") {
2618
- if (target === void 0) exit(2, USAGE);
2619
- const origin = new URL(target).origin;
2620
- const token = values.token ?? process.env.COFFRE_TOKEN;
2621
- let canary;
2622
- if (token !== void 0) {
2623
- if (values.canary === void 0) exit(2, "with a token, name its canary: --canary <project>/<environment>/<KEY>[=<value>]");
2624
- try {
2625
- canary = parseCanary(values.canary, values.canary.includes("=") ? void 0 : await canaryValue());
2626
- } catch (error) {
2627
- exit(2, error instanceof Error ? error.message : String(error));
2628
- }
2629
- }
2630
- console.log(`coffre-conformance: probing ${origin}${token === void 0 ? ", as no one" : ", as no one and with a token"}`);
2631
- if (token !== void 0) console.log(" (the token's reads add a few entries to the instance's audit log, for good)");
2632
- const failed = await probe(origin, {
2633
- token,
2634
- canary
2635
- });
2636
- exit(failed.length === 0 ? 0 : 1, summary(failed));
2637
- }
2638
- /** The canary's value from the environment, or the first line of stdin when it is piped. */
2639
- async function canaryValue() {
2640
- const given = process.env.COFFRE_CONFORMANCE_CANARY;
2641
- if (given !== void 0 && given !== "") return given;
2642
- if (process.stdin.isTTY) return void 0;
2643
- let text = "";
2644
- for await (const chunk of process.stdin) text += String(chunk);
2645
- return text.split(/\r?\n/)[0];
2646
- }
2487
+ if (command === "probe") exit(2, "coffre-conformance probe is now `coffre verify instance`, in the coffre CLI: npx @coffre/cli verify instance");
2647
2488
  if (command !== "workers" && command !== "node") exit(2, USAGE);
2648
2489
  const kind = command;
2649
2490
  const dir = resolve(target ?? ".");