@coffre/conformance 0.1.15 → 0.1.16

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/README.md CHANGED
@@ -16,7 +16,8 @@ instance is checked from outside by the CLI, `coffre verify instance`
16
16
  [Against a running instance](https://github.com/erwinkn/coffre/blob/main/docs/conformance.md#against-a-running-instance).
17
17
 
18
18
  `@coffre/conformance/idp` is the stand-in identity provider it signs in
19
- with, which plays GitHub, an OIDC provider and Cloudflare Access.
19
+ with, which plays GitHub, an OIDC provider and Cloudflare Access, and a CI
20
+ platform that signs ID tokens for its runs.
20
21
 
21
22
  Part of [coffre](https://github.com/erwinkn/coffre), a secrets manager you
22
23
  deploy as a small project of your own. Its eight `@coffre/*` packages are
@@ -894,6 +894,143 @@ var OidcProvider = class {
894
894
  }
895
895
  };
896
896
  //#endregion
897
+ //#region src/idp/workloads.ts
898
+ /**
899
+ * A CI platform's ID tokens, as GitHub Actions signs them for a run: an
900
+ * issuer of its own under `/workloads`, with its discovery document and its
901
+ * keys, one RS256 and one ES256, and tokens minted for whatever run a check
902
+ * describes. What coffre's trust bindings and exchange are checked against,
903
+ * through their real code paths: discovery, a key set fetched over HTTP, a
904
+ * signature verified.
905
+ *
906
+ * `GET /workloads/actions` answers as a GitHub runner does a job with
907
+ * `permissions: id-token: write`, to the bearer of `requestToken`. Locally,
908
+ * `POST /workloads/token` mints one, for trying the CLI by hand:
909
+ *
910
+ * COFFRE_ID_TOKEN=$(curl -s -X POST http://127.0.0.1:8081/workloads/token \
911
+ * -d aud=http://127.0.0.1:3000 | jq -r .token)
912
+ */
913
+ var WorkloadIssuer = class {
914
+ #origin;
915
+ /** A job's ACTIONS_ID_TOKEN_REQUEST_TOKEN: the bearer `GET /workloads/actions` wants. */
916
+ requestToken = randomBytes(16).toString("hex");
917
+ #keys = [];
918
+ constructor(origin) {
919
+ this.#origin = origin;
920
+ }
921
+ /** Where the tokens say they come from: `http://127.0.0.1:<port>/workloads`. */
922
+ get issuer() {
923
+ return `${this.#origin()}/workloads`;
924
+ }
925
+ get jwksUrl() {
926
+ return `${this.issuer}/jwks`;
927
+ }
928
+ /** A job's ACTIONS_ID_TOKEN_REQUEST_URL, which already has a query, as GitHub's does. */
929
+ get requestUrl() {
930
+ return `${this.issuer}/actions?api-version=2.0`;
931
+ }
932
+ async start() {
933
+ this.#keys = await Promise.all(["RS256", "ES256"].map(async (alg) => {
934
+ const { privateKey, publicKey } = await generateKeyPair(alg, { extractable: true });
935
+ const kid = `dev-workloads-${alg.toLowerCase()}`;
936
+ return {
937
+ alg,
938
+ kid,
939
+ privateKey,
940
+ jwk: {
941
+ ...await exportJWK(publicKey),
942
+ kid,
943
+ alg,
944
+ use: "sig"
945
+ }
946
+ };
947
+ }));
948
+ }
949
+ /**
950
+ * A run's ID token: GitHub's claims for a push of `deploy.yml` to `main`
951
+ * of `acme/api`, for `audience`, valid five minutes, unless `claims` says
952
+ * otherwise.
953
+ */
954
+ async mint(audience, claims = {}, alg = "RS256") {
955
+ const key = this.#keys.find((candidate) => candidate.alg === alg);
956
+ if (key === void 0) throw new Error("the workload issuer is not started");
957
+ const now = Math.floor(Date.now() / 1e3);
958
+ return new SignJWT({
959
+ ...GITHUB_RUN,
960
+ iss: this.issuer,
961
+ aud: audience,
962
+ iat: now,
963
+ nbf: now - 5,
964
+ exp: now + 300,
965
+ jti: crypto.randomUUID(),
966
+ ...claims
967
+ }).setProtectedHeader({
968
+ alg: key.alg,
969
+ kid: key.kid,
970
+ typ: "JWT"
971
+ }).sign(key.privateKey);
972
+ }
973
+ routes() {
974
+ return [
975
+ {
976
+ method: "GET",
977
+ path: "/workloads/.well-known/openid-configuration",
978
+ handler: async (_req, res) => sendJson(res, 200, {
979
+ issuer: this.issuer,
980
+ jwks_uri: this.jwksUrl,
981
+ subject_types_supported: ["public"],
982
+ response_types_supported: ["id_token"],
983
+ id_token_signing_alg_values_supported: ["RS256", "ES256"],
984
+ claims_supported: Object.keys(GITHUB_RUN)
985
+ })
986
+ },
987
+ {
988
+ method: "GET",
989
+ path: "/workloads/jwks",
990
+ handler: async (_req, res) => sendJson(res, 200, { keys: this.#keys.map((key) => key.jwk) })
991
+ },
992
+ {
993
+ method: "GET",
994
+ path: "/workloads/actions",
995
+ handler: async (req, res, url) => {
996
+ if (req.headers.authorization?.replace(/^bearer /i, "") !== this.requestToken) return sendJson(res, 401, { message: "Bad credentials" });
997
+ const audience = url.searchParams.get("audience");
998
+ if (audience === null) return sendJson(res, 400, { message: "no audience" });
999
+ sendJson(res, 200, {
1000
+ count: 1,
1001
+ value: await this.mint(audience)
1002
+ });
1003
+ }
1004
+ },
1005
+ {
1006
+ method: "POST",
1007
+ path: "/workloads/token",
1008
+ handler: async (req, res) => {
1009
+ const params = await readParams(req);
1010
+ const alg = params?.get("alg") === "ES256" ? "ES256" : "RS256";
1011
+ sendJson(res, 200, { token: await this.mint(params?.get("aud") ?? "http://127.0.0.1:3000", {}, alg) });
1012
+ }
1013
+ }
1014
+ ];
1015
+ }
1016
+ };
1017
+ /** A run of `deploy.yml`, pushed to `main` of `acme/api`, as GitHub's token says it. */
1018
+ const GITHUB_RUN = {
1019
+ sub: "repo:acme/api:ref:refs/heads/main",
1020
+ repository: "acme/api",
1021
+ repository_id: "41532",
1022
+ repository_owner: "acme",
1023
+ repository_owner_id: "9919",
1024
+ workflow_ref: "acme/api/.github/workflows/deploy.yml@refs/heads/main",
1025
+ ref: "refs/heads/main",
1026
+ ref_type: "branch",
1027
+ event_name: "push",
1028
+ run_id: "7001",
1029
+ run_attempt: "1",
1030
+ sha: "3f2a9c1e7b6d5c4a3f2a9c1e7b6d5c4a3f2a9c1e",
1031
+ actor: "ada"
1032
+ };
1033
+ //#endregion
897
1034
  //#region src/idp/idp.ts
898
1035
  /** Built in, so local dev needs no registration step. */
899
1036
  const DEFAULT_CLIENT = Object.freeze({
@@ -927,6 +1064,8 @@ var DevIdp = class {
927
1064
  listenPort = 0;
928
1065
  /** See {@link DevIdpOptions.autoApprove}. */
929
1066
  autoApprove;
1067
+ /** A CI platform's ID tokens, under `/workloads`, for trust bindings. */
1068
+ workloads = new WorkloadIssuer(() => this.origin);
930
1069
  constructor(options = {}) {
931
1070
  this.autoApprove = options.autoApprove ?? false;
932
1071
  this.#clients.set(DEFAULT_CLIENT.clientId, {
@@ -936,7 +1075,11 @@ var DevIdp = class {
936
1075
  });
937
1076
  for (const client of options.clients ?? []) this.registerClient(client);
938
1077
  const authz = new AuthorizationServer(this);
939
- this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes()];
1078
+ this.#routes = [
1079
+ ...new OidcProvider(this, authz).routes(),
1080
+ ...new FakeGitHub(this, authz).routes(),
1081
+ ...this.workloads.routes()
1082
+ ];
940
1083
  }
941
1084
  get origin() {
942
1085
  if (this.#port === 0) throw new Error("DevIdp is not started");
@@ -959,6 +1102,7 @@ var DevIdp = class {
959
1102
  alg: "RS256",
960
1103
  use: "sig"
961
1104
  };
1105
+ await this.workloads.start();
962
1106
  this.#server = createServer((req, res) => {
963
1107
  if (req.url?.startsWith("/dev/mint")) {
964
1108
  const url = new URL(req.url, this.origin);
@@ -1119,4 +1263,4 @@ var DevIdp = class {
1119
1263
  }
1120
1264
  };
1121
1265
  //#endregion
1122
- export { defaultGitHubAccount as i, DevIdp as n, PERSONAS as r, DEFAULT_CLIENT as t };
1266
+ export { PERSONAS as a, WorkloadIssuer as i, DevIdp as n, defaultGitHubAccount as o, GITHUB_RUN as r, DEFAULT_CLIENT as t };
package/dist/idp.d.ts CHANGED
@@ -1,4 +1,65 @@
1
+ import { IncomingMessage, ServerResponse } from "node:http";
1
2
  import { CryptoKey, JWK } from "jose";
3
+ //#region src/idp/http.d.ts
4
+ type Handler = (req: IncomingMessage, res: ServerResponse, url: URL) => Promise<void>;
5
+ interface Route {
6
+ method: 'GET' | 'POST';
7
+ path: string | RegExp;
8
+ handler: Handler;
9
+ }
10
+ //#endregion
11
+ //#region src/idp/workloads.d.ts
12
+ /**
13
+ * A CI platform's ID tokens, as GitHub Actions signs them for a run: an
14
+ * issuer of its own under `/workloads`, with its discovery document and its
15
+ * keys, one RS256 and one ES256, and tokens minted for whatever run a check
16
+ * describes. What coffre's trust bindings and exchange are checked against,
17
+ * through their real code paths: discovery, a key set fetched over HTTP, a
18
+ * signature verified.
19
+ *
20
+ * `GET /workloads/actions` answers as a GitHub runner does a job with
21
+ * `permissions: id-token: write`, to the bearer of `requestToken`. Locally,
22
+ * `POST /workloads/token` mints one, for trying the CLI by hand:
23
+ *
24
+ * COFFRE_ID_TOKEN=$(curl -s -X POST http://127.0.0.1:8081/workloads/token \
25
+ * -d aud=http://127.0.0.1:3000 | jq -r .token)
26
+ */
27
+ export declare class WorkloadIssuer {
28
+ #private;
29
+ /** A job's ACTIONS_ID_TOKEN_REQUEST_TOKEN: the bearer `GET /workloads/actions` wants. */
30
+ readonly requestToken: string;
31
+ constructor(origin: () => string);
32
+ /** Where the tokens say they come from: `http://127.0.0.1:<port>/workloads`. */
33
+ get issuer(): string;
34
+ get jwksUrl(): string;
35
+ /** A job's ACTIONS_ID_TOKEN_REQUEST_URL, which already has a query, as GitHub's does. */
36
+ get requestUrl(): string;
37
+ start(): Promise<void>;
38
+ /**
39
+ * A run's ID token: GitHub's claims for a push of `deploy.yml` to `main`
40
+ * of `acme/api`, for `audience`, valid five minutes, unless `claims` says
41
+ * otherwise.
42
+ */
43
+ mint(audience: string, claims?: Record<string, unknown>, alg?: 'RS256' | 'ES256'): Promise<string>;
44
+ routes(): Route[];
45
+ }
46
+ /** A run of `deploy.yml`, pushed to `main` of `acme/api`, as GitHub's token says it. */
47
+ export declare const GITHUB_RUN: {
48
+ readonly sub: "repo:acme/api:ref:refs/heads/main";
49
+ readonly repository: "acme/api";
50
+ readonly repository_id: "41532";
51
+ readonly repository_owner: "acme";
52
+ readonly repository_owner_id: "9919";
53
+ readonly workflow_ref: "acme/api/.github/workflows/deploy.yml@refs/heads/main";
54
+ readonly ref: "refs/heads/main";
55
+ readonly ref_type: "branch";
56
+ readonly event_name: "push";
57
+ readonly run_id: "7001";
58
+ readonly run_attempt: "1";
59
+ readonly sha: "3f2a9c1e7b6d5c4a3f2a9c1e7b6d5c4a3f2a9c1e";
60
+ readonly actor: "ada";
61
+ };
62
+ //#endregion
2
63
  //#region src/idp/people.d.ts
3
64
  interface Persona {
4
65
  email: string;
@@ -81,6 +142,8 @@ export declare class DevIdp {
81
142
  listenPort: number;
82
143
  /** See {@link DevIdpOptions.autoApprove}. */
83
144
  autoApprove: boolean;
145
+ /** A CI platform's ID tokens, under `/workloads`, for trust bindings. */
146
+ readonly workloads: WorkloadIssuer;
84
147
  constructor(options?: DevIdpOptions);
85
148
  get origin(): string;
86
149
  /** Matches the Cloudflare Access team-domain issuer shape. */
package/dist/idp.js CHANGED
@@ -1,2 +1,2 @@
1
- import { n as DevIdp, r as PERSONAS, t as DEFAULT_CLIENT } from "./idp-DJlqS-JW.js";
2
- export { DEFAULT_CLIENT, DevIdp, PERSONAS };
1
+ import { a as PERSONAS, i as WorkloadIssuer, n as DevIdp, r as GITHUB_RUN, t as DEFAULT_CLIENT } from "./idp-BeOsuZ3p.js";
2
+ export { DEFAULT_CLIENT, DevIdp, GITHUB_RUN, PERSONAS, WorkloadIssuer };
package/dist/main.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as defaultGitHubAccount, n as DevIdp } from "./idp-DJlqS-JW.js";
1
+ import { n as DevIdp, o as defaultGitHubAccount, r as GITHUB_RUN } from "./idp-BeOsuZ3p.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { inspect, parseArgs } from "node:util";
@@ -172,6 +172,22 @@ function createClient(options) {
172
172
  id
173
173
  })
174
174
  },
175
+ /** Trust bindings: which CI runs may sign in as a service, by their platform's ID token. */
176
+ bindings: {
177
+ list: (member) => call("GET /members/:member/bindings", { member }),
178
+ /** The binding as it would be saved, the keys its issuer names, and what it replaces; writes nothing. */
179
+ preview: (member, input) => {
180
+ const [method, route] = address("POST /members/:member/bindings", { member });
181
+ return send(method, `${route}?dryRun=1`, input);
182
+ },
183
+ create: (member, input) => call("POST /members/:member/bindings", { member }, input),
184
+ remove: (member, id) => call("DELETE /members/:member/bindings/:id", {
185
+ member,
186
+ id
187
+ }),
188
+ /** A public GitHub repository's or GitLab project's IDs, which bindings name. */
189
+ lookup: (input) => call("GET /workloads/lookup", {}, input)
190
+ },
175
191
  access: {
176
192
  /** What they should hold at each place; the server applies the difference. `null` revokes. */
177
193
  set: (member, access) => call("PATCH /access/:member", { member }, access) },
@@ -417,7 +433,8 @@ async function boot(kind, at, options) {
417
433
  `GITHUB_URL:${github.GITHUB_URL}`,
418
434
  "--var",
419
435
  `GITHUB_API_URL:${github.GITHUB_API_URL}`
420
- ]
436
+ ],
437
+ ...["--var", "ALLOW_LOOPBACK_ISSUERS_FOR_DEVELOPMENT:true"]
421
438
  ], {
422
439
  PUBLIC_URL: origin,
423
440
  GITHUB_CLIENT_ID: github.GITHUB_CLIENT_ID,
@@ -466,6 +483,7 @@ async function boot(kind, at, options) {
466
483
  DATABASE_URL: `file:${database}`,
467
484
  VAULT_SOCKET: socket,
468
485
  APP_KEY: KEYS.APP_KEY,
486
+ ALLOW_LOOPBACK_ISSUERS_FOR_DEVELOPMENT: "true",
469
487
  ...github
470
488
  });
471
489
  let server = startServer();
@@ -1888,6 +1906,11 @@ function getCalls({ places, secrets, members, services }) {
1888
1906
  }]],
1889
1907
  "GET /members/:member": members.map((member) => ({ params: { member } })),
1890
1908
  "GET /members/:member/tokens": services.map((member) => ({ params: { member } })),
1909
+ "GET /members/:member/bindings": services.map((member) => ({ params: { member } })),
1910
+ "GET /workloads/lookup": [{
1911
+ params: {},
1912
+ input: { github: "acme/api" }
1913
+ }],
1891
1914
  "GET /sessions": [{ params: {} }],
1892
1915
  "GET /identities": [{ params: {} }],
1893
1916
  "GET /device-logins/:code": [{ params: { code: "BCDF-GHJK" } }],
@@ -2335,6 +2358,251 @@ async function health(deployment) {
2335
2358
  return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
2336
2359
  }
2337
2360
  //#endregion
2361
+ //#region src/checks/workloads.ts
2362
+ /** The service the runs sign in as: a viewer on dev. */
2363
+ const RUNNER = "token:conformance-run";
2364
+ /** `coffre trust conformance-run --github acme/api --workflow deploy.yml --branch main`, with the dev IdP as GitHub's issuer. */
2365
+ const DEPLOY = {
2366
+ repository_owner_id: GITHUB_RUN.repository_owner_id,
2367
+ repository_id: GITHUB_RUN.repository_id,
2368
+ workflow_ref: GITHUB_RUN.workflow_ref,
2369
+ ref: GITHUB_RUN.ref,
2370
+ event_name: GITHUB_RUN.event_name
2371
+ };
2372
+ /** Every ID token the checks sent and credential they were given: none may show in the processes' output. */
2373
+ const sent = [];
2374
+ /** A run's ID token from the dev IdP, for this deployment unless `audience` says otherwise. */
2375
+ async function mint(deployment, claims = {}, options = {}) {
2376
+ const token = await deployment.idp.workloads.mint(options.audience ?? deployment.origin, claims, options.alg);
2377
+ sent.push(token);
2378
+ return token;
2379
+ }
2380
+ async function exchange(deployment, token, service = RUNNER) {
2381
+ const response = await fetch(`${deployment.origin}/api/auth/oidc`, {
2382
+ method: "POST",
2383
+ headers: { "content-type": "application/json" },
2384
+ body: JSON.stringify({
2385
+ service,
2386
+ token
2387
+ })
2388
+ });
2389
+ const body = await response.json().catch(() => ({}));
2390
+ if (body.token !== void 0) sent.push(body.token);
2391
+ return {
2392
+ ...body,
2393
+ status: response.status,
2394
+ retryAfter: response.headers.get("retry-after")
2395
+ };
2396
+ }
2397
+ /** What a failure may show of an answer: never its credential. */
2398
+ const shown = ({ status, reason, message }) => ({
2399
+ status,
2400
+ reason,
2401
+ message
2402
+ });
2403
+ /** The other spelling of an ES256 signature, (r, n − s), which verifies the same claims. */
2404
+ function twin(jwt) {
2405
+ const at = jwt.lastIndexOf(".");
2406
+ const signature = Buffer.from(jwt.slice(at + 1), "base64url");
2407
+ const n = 115792089210356248762697446949407573529996955224135760342422259061068512044369n;
2408
+ const s = BigInt(`0x${signature.subarray(32).toString("hex")}`);
2409
+ const flipped = Buffer.from((n - s).toString(16).padStart(64, "0"), "hex");
2410
+ return `${jwt.slice(0, at)}.${Buffer.concat([signature.subarray(0, 32), flipped]).toString("base64url")}`;
2411
+ }
2412
+ /** A viewer on dev, and a binding that trusts deploy.yml pushed to main of acme/api. */
2413
+ async function trustRun(deployment, admin) {
2414
+ await admin.api.members.add(RUNNER);
2415
+ await admin.api.access.set(RUNNER, { [DEV]: "viewer" });
2416
+ const made = await admin.api.bindings.create(RUNNER, {
2417
+ profile: "github",
2418
+ issuer: deployment.idp.workloads.issuer,
2419
+ claims: DEPLOY,
2420
+ label: "conformance"
2421
+ }).catch((error) => {
2422
+ if (error.status === 404) throw new Skip(`this deployment trusts no workloads: ${error.message}`);
2423
+ throw error;
2424
+ });
2425
+ return {
2426
+ detail: `${RUNNER}, viewer on ${DEV}, trusts deploy.yml pushed to main of acme/api, from the dev IdP`,
2427
+ value: made.binding.id
2428
+ };
2429
+ }
2430
+ /**
2431
+ * A run's token buys a credential of five minutes, which reads as the
2432
+ * service; its read is logged with the credential, and the log leads from
2433
+ * it to the run.
2434
+ */
2435
+ async function runSignsIn(deployment, admin, canaries) {
2436
+ const issued = await exchange(deployment, await mint(deployment));
2437
+ const { token } = issued;
2438
+ expect(issued.status === 200 && typeof token === "string" && token.startsWith("coffre_svc_"), "the run's token bought no credential", shown(issued));
2439
+ const lifetime = Date.parse(issued.expiresAt ?? "") - Date.now();
2440
+ expect(lifetime > 0 && lifetime <= 305e3, `the credential lives ${Math.round(lifetime / 1e3)} s, not five minutes`);
2441
+ const { values } = await bearer(deployment.origin, token).secrets.reveal(`${DEV}/API_KEY`);
2442
+ expect(values.API_KEY === canaries[`${DEV}/API_KEY`], "the credential did not read the value as the service");
2443
+ const { entries } = await admin.api.audit.list({
2444
+ actor: RUNNER,
2445
+ detail: "1"
2446
+ });
2447
+ const exchanged = entries.find((entry) => entry.action === "token.exchange");
2448
+ const read = entries.find((entry) => entry.author === "vault" && entry.action === "secret.read" && entry.key === "API_KEY");
2449
+ expect(exchanged !== void 0 && read !== void 0, "the exchange or the read is not in the log", entries.map((entry) => entry.action));
2450
+ const credentialId = exchanged.metadata.credentialId;
2451
+ expect(typeof credentialId === "string", "the exchange did not log its credential", exchanged.metadata);
2452
+ expect(read.metadata.credentialId === credentialId, "the vault's entry for the read does not name the credential", read.metadata);
2453
+ expect(read.run?.exchangeSeq === exchanged.seq && read.run.claims.run_id === GITHUB_RUN.run_id && read.run.claims.repository === GITHUB_RUN.repository, "the read does not lead to its run", read.run);
2454
+ return {
2455
+ detail: `a five-minute credential for run ${GITHUB_RUN.run_id} of ${GITHUB_RUN.repository}; its read is logged with it, and leads to the run`,
2456
+ value: token
2457
+ };
2458
+ }
2459
+ /** A token buys one credential, in either spelling of its signature. */
2460
+ async function spentOnce(deployment) {
2461
+ const token = await mint(deployment);
2462
+ expect((await exchange(deployment, token)).status === 200, "a fresh token was refused");
2463
+ const again = await exchange(deployment, token);
2464
+ expect(again.status === 401 && again.reason === "replayed", "a token was taken twice", shown(again));
2465
+ const signed = await mint(deployment, {}, { alg: "ES256" });
2466
+ expect((await exchange(deployment, signed)).status === 200, "a fresh ES256 token was refused");
2467
+ const respelled = await exchange(deployment, twin(signed));
2468
+ expect(respelled.status === 401 && respelled.reason === "replayed", "an ES256 token was taken again, its signature's twin in place of its own", shown(respelled));
2469
+ return "taken once each: an RS256 token sent again, and an ES256 token's (r, n − s) twin, refused as replayed";
2470
+ }
2471
+ /** Tokens for another instance, expired, or from a run the binding does not name: refused, for a reason, and not logged. */
2472
+ async function runsRefused(deployment, admin) {
2473
+ const now = Math.floor(Date.now() / 1e3);
2474
+ const feature = "refs/heads/feature";
2475
+ const cases = [
2476
+ [
2477
+ "for another instance",
2478
+ await mint(deployment, {}, { audience: "https://secrets.elsewhere.example" }),
2479
+ "audience"
2480
+ ],
2481
+ [
2482
+ "expired",
2483
+ await mint(deployment, {
2484
+ iat: now - 600,
2485
+ nbf: now - 600,
2486
+ exp: now - 120
2487
+ }),
2488
+ "expired"
2489
+ ],
2490
+ [
2491
+ "from a feature branch",
2492
+ await mint(deployment, {
2493
+ ref: feature,
2494
+ workflow_ref: GITHUB_RUN.workflow_ref.replace(/@.*/, `@${feature}`),
2495
+ sub: `repo:acme/api:ref:${feature}`
2496
+ }),
2497
+ "no_match"
2498
+ ],
2499
+ [
2500
+ "from a pull request",
2501
+ await mint(deployment, { event_name: "pull_request" }),
2502
+ "no_match"
2503
+ ],
2504
+ [
2505
+ "from another repository",
2506
+ await mint(deployment, {
2507
+ repository_id: "1",
2508
+ repository: "acme/fork"
2509
+ }),
2510
+ "no_match"
2511
+ ]
2512
+ ];
2513
+ const before = (await admin.api.audit.list({
2514
+ actor: RUNNER,
2515
+ detail: "1"
2516
+ })).entries.filter((entry) => entry.action === "token.exchange").length;
2517
+ for (const [what, token, reason] of cases) {
2518
+ const answer = await exchange(deployment, token);
2519
+ expect(answer.status === 401 && answer.reason === reason, `a token ${what} was not refused as ${reason}`, shown(answer));
2520
+ expect(!answer.message?.includes(GITHUB_RUN.ref), `the refusal of a token ${what} said what the binding expects`, answer.message);
2521
+ }
2522
+ const stranger = await exchange(deployment, await mint(deployment), "token:conformance-nobody");
2523
+ expect(stranger.status === 401 && stranger.reason === "no_match", "a token was taken for a service no binding names", shown(stranger));
2524
+ const after = (await admin.api.audit.list({
2525
+ actor: RUNNER,
2526
+ detail: "1"
2527
+ })).entries.filter((entry) => entry.action === "token.exchange").length;
2528
+ expect(after === before, `${after - before} refused exchanges were logged as exchanges`);
2529
+ return `${cases.length + 1} refused, each for its reason, none saying what the binding expects, none logged: ${cases.map(([what]) => what).join(", ")}, for another service`;
2530
+ }
2531
+ /**
2532
+ * The CLI, as a CI job runs it: on GitHub Actions, with the runner's
2533
+ * token endpoint and nothing else; elsewhere, with the token in
2534
+ * COFFRE_ID_TOKEN. It keeps the credential in memory, and prints neither.
2535
+ */
2536
+ async function cliSignsIn(deployment, canaries) {
2537
+ const issuer = deployment.idp.workloads;
2538
+ const cli = new Cli(deployment.origin);
2539
+ try {
2540
+ const base = {
2541
+ COFFRE_API_URL: deployment.origin,
2542
+ COFFRE_SERVICE: RUNNER
2543
+ };
2544
+ const given = await mint(deployment);
2545
+ const runs = {
2546
+ "on GitHub Actions": {
2547
+ ...base,
2548
+ ACTIONS_ID_TOKEN_REQUEST_URL: issuer.requestUrl,
2549
+ ACTIONS_ID_TOKEN_REQUEST_TOKEN: issuer.requestToken
2550
+ },
2551
+ "with COFFRE_ID_TOKEN": {
2552
+ ...base,
2553
+ COFFRE_ID_TOKEN: given
2554
+ }
2555
+ };
2556
+ for (const [where, env] of Object.entries(runs)) {
2557
+ const run = await cli.run(["get", `${DEV}/API_KEY`], env);
2558
+ expect(run.code === 0, `coffre get ${where} exited ${run.code}`, run.output);
2559
+ expect(run.output.trim() === canaries[`${DEV}/API_KEY`], `coffre get ${where} did not print the value`);
2560
+ expect(!run.output.includes(given) && !run.output.includes(issuer.requestToken) && !/coffre_svc_/.test(run.output), `coffre get ${where} printed a token`);
2561
+ }
2562
+ expect(!existsSync(join(cli.home, ".coffre", "credentials.json")), "the CLI kept a credential on disk");
2563
+ return `\`coffre get\` as ${RUNNER}, on GitHub Actions and with COFFRE_ID_TOKEN; no token printed, nothing written`;
2564
+ } finally {
2565
+ cli.remove();
2566
+ }
2567
+ }
2568
+ /** Removing the binding ends the credentials it issued at once, and the next run gets none. */
2569
+ async function runUnbound(deployment, admin, bindingId, credential) {
2570
+ const me = (token) => fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${token}` } }).then((response) => response.status);
2571
+ expect(await me(credential) === 200, "the credential did not work before its binding was removed");
2572
+ await admin.api.bindings.remove(RUNNER, bindingId);
2573
+ expect(await me(credential) === 401, "the credential still worked once its binding was removed");
2574
+ const next = await exchange(deployment, await mint(deployment));
2575
+ expect(next.status === 401 && next.reason === "no_match", "a run was let in once its binding was removed", shown(next));
2576
+ const { bindings } = await admin.api.bindings.list(RUNNER);
2577
+ expect(bindings.length === 0, "the removed binding is still listed", bindings);
2578
+ return "its credential refused at once, and the next run refused as no binding matching";
2579
+ }
2580
+ /**
2581
+ * One address may exchange only so often: tokens that would be refused
2582
+ * anyway still count, before anything about them is read. Fixed windows
2583
+ * of a minute, so the 429 may wait for the next one.
2584
+ */
2585
+ async function exchangesLimited(deployment) {
2586
+ const most = 200;
2587
+ for (let sent = 1; sent <= most; sent++) {
2588
+ const answer = await exchange(deployment, "not.a.token");
2589
+ if (answer.status === 429) {
2590
+ expect(answer.reason === "busy" && answer.retryAfter === "60", "the 429 did not say to wait a minute", shown(answer));
2591
+ return `a 429 after ${sent} malformed tokens from one address, and Retry-After: 60`;
2592
+ }
2593
+ expect(answer.status === 401 && answer.reason === "malformed", "a malformed token was not refused as malformed", shown(answer));
2594
+ }
2595
+ throw new Error(`${most} exchanges from one address, and none was turned away`);
2596
+ }
2597
+ /** No ID token the checks sent, nor credential they were given, in what the deployment's processes printed. */
2598
+ async function tokensUnlogged(deployment) {
2599
+ const output = deployment.output();
2600
+ const found = sent.filter((token) => token.split(".").slice(1).some((part) => output.includes(part)) || token.startsWith("coffre_") && output.includes(token));
2601
+ expect(found.length === 0, `${found.length} of the tokens and credentials the checks used are in the processes' output`);
2602
+ expect(!/coffre_svc_[A-Za-z0-9_-]{8,}/.test(output), "a service credential is in the processes' output");
2603
+ return `${sent.length} ID tokens and credentials, none in the processes' output`;
2604
+ }
2605
+ //#endregion
2338
2606
  //#region src/suite.ts
2339
2607
  /** The names of the checks that failed. */
2340
2608
  async function conform(deployment, options) {
@@ -2401,6 +2669,28 @@ async function conform(deployment, options) {
2401
2669
  }
2402
2670
  await report.check("offboarding", all, ({ people, canaries }) => offboarding(deployment, people, canaries));
2403
2671
  await report.check("bulk limit", { people }, ({ people }) => bulkLimit$1(people, options.bulkLimit));
2672
+ const binding = await report.check("trust a run", { admin }, ({ admin }) => trustRun(deployment, admin));
2673
+ const credential = await report.check("run signs in", {
2674
+ admin,
2675
+ canaries,
2676
+ binding
2677
+ }, ({ admin, canaries }) => runSignsIn(deployment, admin, canaries));
2678
+ await report.check("run token spent", { binding }, () => spentOnce(deployment));
2679
+ await report.check("runs refused", {
2680
+ admin,
2681
+ binding
2682
+ }, ({ admin }) => runsRefused(deployment, admin));
2683
+ await report.check("run signs in by CLI", {
2684
+ canaries,
2685
+ binding
2686
+ }, ({ canaries }) => cliSignsIn(deployment, canaries));
2687
+ await report.check("run unbound", {
2688
+ admin,
2689
+ binding,
2690
+ credential
2691
+ }, ({ admin, binding, credential }) => runUnbound(deployment, admin, binding, credential));
2692
+ await report.check("exchanges limited", { binding }, () => exchangesLimited(deployment));
2693
+ await report.check("tokens unlogged", { binding }, () => tokensUnlogged(deployment));
2404
2694
  await report.check("checkpoints", { people }, ({ people }) => checkpoints(deployment, people));
2405
2695
  await report.check("keys behind writes", { people }, ({ people }) => writesAgree(deployment));
2406
2696
  await report.check("no audit, no value", all, ({ people, canaries }) => noAuditNoValue(deployment, people, canaries));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/conformance",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "Checks a coffre deployment from outside: what it must never do, whatever code it runs.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,8 +31,8 @@
31
31
  "dependencies": {
32
32
  "jose": "6.2.3",
33
33
  "pg": "8.16.3",
34
- "@coffre/cli": "0.1.15",
35
- "@coffre/db": "0.1.15"
34
+ "@coffre/cli": "0.1.16",
35
+ "@coffre/db": "0.1.16"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "26.1.1",
@@ -40,7 +40,7 @@
40
40
  "oauth4webapi": "3.8.8",
41
41
  "tsdown": "0.23.0",
42
42
  "typescript": "5.9.3",
43
- "@coffre/client": "0.1.15"
43
+ "@coffre/client": "0.1.16"
44
44
  },
45
45
  "scripts": {
46
46
  "build": "tsdown",
@@ -0,0 +1,218 @@
1
+ // A CI run signing in as a service with the ID token its platform signs
2
+ // for it, through a trust binding an owner made (docs/design/oidc.md). The
3
+ // dev IdP plays GitHub Actions under /workloads: discovery, keys over
4
+ // HTTP, a runner's token endpoint, and a token for whatever run a check
5
+ // describes. What the exchange must never do: take a token twice, in
6
+ // either spelling of its signature; take one for another instance, expired,
7
+ // or from a run the binding does not name; keep a credential working once
8
+ // its binding is gone; or take more exchanges from one address than its
9
+ // limit.
10
+ import { existsSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ import { bearer } from '../browser.ts';
14
+ import type { Deployment } from '../harness.ts';
15
+ import { GITHUB_RUN } from '../idp/index.ts';
16
+ import { expect, Skip } from '../report.ts';
17
+ import { Cli } from './cli.ts';
18
+ import { DEV, type Canaries, type Person } from './people.ts';
19
+
20
+ /** The service the runs sign in as: a viewer on dev. */
21
+ export const RUNNER = 'token:conformance-run';
22
+
23
+ /** `coffre trust conformance-run --github acme/api --workflow deploy.yml --branch main`, with the dev IdP as GitHub's issuer. */
24
+ const DEPLOY = {
25
+ repository_owner_id: GITHUB_RUN.repository_owner_id,
26
+ repository_id: GITHUB_RUN.repository_id,
27
+ workflow_ref: GITHUB_RUN.workflow_ref,
28
+ ref: GITHUB_RUN.ref,
29
+ event_name: GITHUB_RUN.event_name,
30
+ };
31
+
32
+ /** Every ID token the checks sent and credential they were given: none may show in the processes' output. */
33
+ const sent: string[] = [];
34
+
35
+ /** A run's ID token from the dev IdP, for this deployment unless `audience` says otherwise. */
36
+ async function mint(deployment: Deployment, claims: Record<string, unknown> = {}, options: { alg?: 'RS256' | 'ES256'; audience?: string } = {}): Promise<string> {
37
+ const token = await deployment.idp.workloads.mint(options.audience ?? deployment.origin, claims, options.alg);
38
+ sent.push(token);
39
+ return token;
40
+ }
41
+
42
+ /** What `POST /api/auth/oidc` answered, without the credential it may hold. */
43
+ type Answer = { status: number; reason?: string; message?: string; retryAfter: string | null };
44
+
45
+ async function exchange(deployment: Deployment, token: string, service = RUNNER): Promise<Answer & { token?: string; expiresAt?: string }> {
46
+ const response = await fetch(`${deployment.origin}/api/auth/oidc`, {
47
+ method: 'POST',
48
+ headers: { 'content-type': 'application/json' },
49
+ body: JSON.stringify({ service, token }),
50
+ });
51
+ const body = (await response.json().catch(() => ({}))) as { token?: string; expiresAt?: string; reason?: string; message?: string };
52
+ if (body.token !== undefined) sent.push(body.token);
53
+ return { ...body, status: response.status, retryAfter: response.headers.get('retry-after') };
54
+ }
55
+
56
+ /** What a failure may show of an answer: never its credential. */
57
+ const shown = ({ status, reason, message }: Answer) => ({ status, reason, message });
58
+
59
+ /** The other spelling of an ES256 signature, (r, n − s), which verifies the same claims. */
60
+ function twin(jwt: string): string {
61
+ const at = jwt.lastIndexOf('.');
62
+ const signature = Buffer.from(jwt.slice(at + 1), 'base64url');
63
+ const n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
64
+ const s = BigInt(`0x${signature.subarray(32).toString('hex')}`);
65
+ const flipped = Buffer.from((n - s).toString(16).padStart(64, '0'), 'hex');
66
+ return `${jwt.slice(0, at)}.${Buffer.concat([signature.subarray(0, 32), flipped]).toString('base64url')}`;
67
+ }
68
+
69
+ /** A viewer on dev, and a binding that trusts deploy.yml pushed to main of acme/api. */
70
+ export async function trustRun(deployment: Deployment, admin: Person) {
71
+ await admin.api.members.add(RUNNER);
72
+ await admin.api.access.set(RUNNER, { [DEV]: 'viewer' });
73
+ const made = await admin.api.bindings
74
+ .create(RUNNER, { profile: 'github', issuer: deployment.idp.workloads.issuer, claims: DEPLOY, label: 'conformance' })
75
+ .catch((error: { status?: number; message?: string }) => {
76
+ if (error.status === 404) throw new Skip(`this deployment trusts no workloads: ${error.message}`);
77
+ throw error;
78
+ });
79
+ return { detail: `${RUNNER}, viewer on ${DEV}, trusts deploy.yml pushed to main of acme/api, from the dev IdP`, value: made.binding.id };
80
+ }
81
+
82
+ /**
83
+ * A run's token buys a credential of five minutes, which reads as the
84
+ * service; its read is logged with the credential, and the log leads from
85
+ * it to the run.
86
+ */
87
+ export async function runSignsIn(deployment: Deployment, admin: Person, canaries: Canaries) {
88
+ const issued = await exchange(deployment, await mint(deployment));
89
+ const { token } = issued;
90
+ expect(issued.status === 200 && typeof token === 'string' && token.startsWith('coffre_svc_'), "the run's token bought no credential", shown(issued));
91
+ const lifetime = Date.parse(issued.expiresAt ?? '') - Date.now();
92
+ expect(lifetime > 0 && lifetime <= 5 * 60_000 + 5_000, `the credential lives ${Math.round(lifetime / 1000)} s, not five minutes`);
93
+ const { values } = await bearer(deployment.origin, token).secrets.reveal(`${DEV}/API_KEY`);
94
+ expect(values.API_KEY === canaries[`${DEV}/API_KEY`], 'the credential did not read the value as the service');
95
+
96
+ const { entries } = await admin.api.audit.list({ actor: RUNNER, detail: '1' });
97
+ const exchanged = entries.find((entry) => entry.action === 'token.exchange');
98
+ const read = entries.find((entry) => entry.author === 'vault' && entry.action === 'secret.read' && entry.key === 'API_KEY');
99
+ expect(exchanged !== undefined && read !== undefined, 'the exchange or the read is not in the log', entries.map((entry) => entry.action));
100
+ const credentialId = exchanged.metadata.credentialId;
101
+ expect(typeof credentialId === 'string', 'the exchange did not log its credential', exchanged.metadata);
102
+ expect(read.metadata.credentialId === credentialId, "the vault's entry for the read does not name the credential", read.metadata);
103
+ expect(
104
+ read.run?.exchangeSeq === exchanged.seq && read.run.claims.run_id === GITHUB_RUN.run_id && read.run.claims.repository === GITHUB_RUN.repository,
105
+ 'the read does not lead to its run',
106
+ read.run,
107
+ );
108
+ return {
109
+ detail: `a five-minute credential for run ${GITHUB_RUN.run_id} of ${GITHUB_RUN.repository}; its read is logged with it, and leads to the run`,
110
+ value: token,
111
+ };
112
+ }
113
+
114
+ /** A token buys one credential, in either spelling of its signature. */
115
+ export async function spentOnce(deployment: Deployment): Promise<string> {
116
+ const token = await mint(deployment);
117
+ expect((await exchange(deployment, token)).status === 200, 'a fresh token was refused');
118
+ const again = await exchange(deployment, token);
119
+ expect(again.status === 401 && again.reason === 'replayed', 'a token was taken twice', shown(again));
120
+ const signed = await mint(deployment, {}, { alg: 'ES256' });
121
+ expect((await exchange(deployment, signed)).status === 200, 'a fresh ES256 token was refused');
122
+ const respelled = await exchange(deployment, twin(signed));
123
+ expect(respelled.status === 401 && respelled.reason === 'replayed', "an ES256 token was taken again, its signature's twin in place of its own", shown(respelled));
124
+ return "taken once each: an RS256 token sent again, and an ES256 token's (r, n − s) twin, refused as replayed";
125
+ }
126
+
127
+ /** Tokens for another instance, expired, or from a run the binding does not name: refused, for a reason, and not logged. */
128
+ export async function runsRefused(deployment: Deployment, admin: Person): Promise<string> {
129
+ const now = Math.floor(Date.now() / 1000);
130
+ const feature = 'refs/heads/feature';
131
+ const cases = [
132
+ ['for another instance', await mint(deployment, {}, { audience: 'https://secrets.elsewhere.example' }), 'audience'],
133
+ ['expired', await mint(deployment, { iat: now - 600, nbf: now - 600, exp: now - 120 }), 'expired'],
134
+ ['from a feature branch', await mint(deployment, { ref: feature, workflow_ref: GITHUB_RUN.workflow_ref.replace(/@.*/, `@${feature}`), sub: `repo:acme/api:ref:${feature}` }), 'no_match'],
135
+ ['from a pull request', await mint(deployment, { event_name: 'pull_request' }), 'no_match'],
136
+ ['from another repository', await mint(deployment, { repository_id: '1', repository: 'acme/fork' }), 'no_match'],
137
+ ] as const;
138
+ const before = (await admin.api.audit.list({ actor: RUNNER, detail: '1' })).entries.filter((entry) => entry.action === 'token.exchange').length;
139
+ for (const [what, token, reason] of cases) {
140
+ const answer = await exchange(deployment, token);
141
+ expect(answer.status === 401 && answer.reason === reason, `a token ${what} was not refused as ${reason}`, shown(answer));
142
+ expect(!answer.message?.includes(GITHUB_RUN.ref), `the refusal of a token ${what} said what the binding expects`, answer.message);
143
+ }
144
+ const stranger = await exchange(deployment, await mint(deployment), 'token:conformance-nobody');
145
+ expect(stranger.status === 401 && stranger.reason === 'no_match', 'a token was taken for a service no binding names', shown(stranger));
146
+ const after = (await admin.api.audit.list({ actor: RUNNER, detail: '1' })).entries.filter((entry) => entry.action === 'token.exchange').length;
147
+ expect(after === before, `${after - before} refused exchanges were logged as exchanges`);
148
+ return `${cases.length + 1} refused, each for its reason, none saying what the binding expects, none logged: ${cases.map(([what]) => what).join(', ')}, for another service`;
149
+ }
150
+
151
+ /**
152
+ * The CLI, as a CI job runs it: on GitHub Actions, with the runner's
153
+ * token endpoint and nothing else; elsewhere, with the token in
154
+ * COFFRE_ID_TOKEN. It keeps the credential in memory, and prints neither.
155
+ */
156
+ export async function cliSignsIn(deployment: Deployment, canaries: Canaries): Promise<string> {
157
+ const issuer = deployment.idp.workloads;
158
+ const cli = new Cli(deployment.origin);
159
+ try {
160
+ const base = { COFFRE_API_URL: deployment.origin, COFFRE_SERVICE: RUNNER };
161
+ const given = await mint(deployment);
162
+ const runs = {
163
+ 'on GitHub Actions': { ...base, ACTIONS_ID_TOKEN_REQUEST_URL: issuer.requestUrl, ACTIONS_ID_TOKEN_REQUEST_TOKEN: issuer.requestToken },
164
+ 'with COFFRE_ID_TOKEN': { ...base, COFFRE_ID_TOKEN: given },
165
+ };
166
+ for (const [where, env] of Object.entries(runs)) {
167
+ const run = await cli.run(['get', `${DEV}/API_KEY`], env);
168
+ expect(run.code === 0, `coffre get ${where} exited ${run.code}`, run.output);
169
+ expect(run.output.trim() === canaries[`${DEV}/API_KEY`], `coffre get ${where} did not print the value`);
170
+ expect(!run.output.includes(given) && !run.output.includes(issuer.requestToken) && !/coffre_svc_/.test(run.output), `coffre get ${where} printed a token`);
171
+ }
172
+ expect(!existsSync(join(cli.home, '.coffre', 'credentials.json')), 'the CLI kept a credential on disk');
173
+ return `\`coffre get\` as ${RUNNER}, on GitHub Actions and with COFFRE_ID_TOKEN; no token printed, nothing written`;
174
+ } finally {
175
+ cli.remove();
176
+ }
177
+ }
178
+
179
+ /** Removing the binding ends the credentials it issued at once, and the next run gets none. */
180
+ export async function runUnbound(deployment: Deployment, admin: Person, bindingId: string, credential: string): Promise<string> {
181
+ const me = (token: string) => fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${token}` } }).then((response) => response.status);
182
+ expect((await me(credential)) === 200, 'the credential did not work before its binding was removed');
183
+ await admin.api.bindings.remove(RUNNER, bindingId);
184
+ expect((await me(credential)) === 401, 'the credential still worked once its binding was removed');
185
+ const next = await exchange(deployment, await mint(deployment));
186
+ expect(next.status === 401 && next.reason === 'no_match', 'a run was let in once its binding was removed', shown(next));
187
+ const { bindings } = await admin.api.bindings.list(RUNNER);
188
+ expect(bindings.length === 0, 'the removed binding is still listed', bindings);
189
+ return 'its credential refused at once, and the next run refused as no binding matching';
190
+ }
191
+
192
+ /**
193
+ * One address may exchange only so often: tokens that would be refused
194
+ * anyway still count, before anything about them is read. Fixed windows
195
+ * of a minute, so the 429 may wait for the next one.
196
+ */
197
+ export async function exchangesLimited(deployment: Deployment): Promise<string> {
198
+ const most = 200;
199
+ for (let sent = 1; sent <= most; sent++) {
200
+ const answer = await exchange(deployment, 'not.a.token');
201
+ if (answer.status === 429) {
202
+ expect(answer.reason === 'busy' && answer.retryAfter === '60', 'the 429 did not say to wait a minute', shown(answer));
203
+ return `a 429 after ${sent} malformed tokens from one address, and Retry-After: 60`;
204
+ }
205
+ expect(answer.status === 401 && answer.reason === 'malformed', 'a malformed token was not refused as malformed', shown(answer));
206
+ }
207
+ throw new Error(`${most} exchanges from one address, and none was turned away`);
208
+ }
209
+
210
+ /** No ID token the checks sent, nor credential they were given, in what the deployment's processes printed. */
211
+ export async function tokensUnlogged(deployment: Deployment): Promise<string> {
212
+ const output = deployment.output();
213
+ // A token's header is the same for every token; its claims and signature are its own.
214
+ const found = sent.filter((token) => token.split('.').slice(1).some((part) => output.includes(part)) || (token.startsWith('coffre_') && output.includes(token)));
215
+ expect(found.length === 0, `${found.length} of the tokens and credentials the checks used are in the processes' output`);
216
+ expect(!/coffre_svc_[A-Za-z0-9_-]{8,}/.test(output), "a service credential is in the processes' output");
217
+ return `${sent.length} ID tokens and credentials, none in the processes' output`;
218
+ }
package/src/harness.ts CHANGED
@@ -185,6 +185,8 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
185
185
  ...['--persist-to', state, '--show-interactive-dev-session=false'],
186
186
  // Not in wrangler.jsonc's vars, so not taken from the environment.
187
187
  ...['--var', `GITHUB_URL:${github.GITHUB_URL}`, '--var', `GITHUB_API_URL:${github.GITHUB_API_URL}`],
188
+ // The dev IdP's workload issuer is plain HTTP on loopback, which only a check may trust.
189
+ ...['--var', 'ALLOW_LOOPBACK_ISSUERS_FOR_DEVELOPMENT:true'],
188
190
  ], {
189
191
  // Wrangler hands each Worker the vars and secrets its own
190
192
  // wrangler.jsonc declares, from here: the app never sees the vault key.
@@ -237,6 +239,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
237
239
  DATABASE_URL: `file:${database}`,
238
240
  VAULT_SOCKET: socket,
239
241
  APP_KEY: KEYS.APP_KEY,
242
+ ALLOW_LOOPBACK_ISSUERS_FOR_DEVELOPMENT: 'true',
240
243
  ...github,
241
244
  });
242
245
  let server = startServer();
package/src/idp/idp.ts CHANGED
@@ -5,6 +5,7 @@ import { AuthorizationServer } from './authorize.ts';
5
5
  import { FakeGitHub } from './github.ts';
6
6
  import type { Route } from './http.ts';
7
7
  import { OidcProvider } from './oidc.ts';
8
+ import { WorkloadIssuer } from './workloads.ts';
8
9
  import {
9
10
  defaultGitHubAccount,
10
11
  defaultSubject,
@@ -73,6 +74,9 @@ export class DevIdp {
73
74
  /** See {@link DevIdpOptions.autoApprove}. */
74
75
  autoApprove: boolean;
75
76
 
77
+ /** A CI platform's ID tokens, under `/workloads`, for trust bindings. */
78
+ readonly workloads = new WorkloadIssuer(() => this.origin);
79
+
76
80
  constructor(options: DevIdpOptions = {}) {
77
81
  this.autoApprove = options.autoApprove ?? false;
78
82
  this.#clients.set(DEFAULT_CLIENT.clientId, {
@@ -83,7 +87,7 @@ export class DevIdp {
83
87
  for (const client of options.clients ?? []) this.registerClient(client);
84
88
 
85
89
  const authz = new AuthorizationServer(this);
86
- this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes()];
90
+ this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes(), ...this.workloads.routes()];
87
91
  }
88
92
 
89
93
  get origin(): string {
@@ -105,6 +109,7 @@ export class DevIdp {
105
109
  const { privateKey, publicKey } = await generateKeyPair('RS256', { extractable: true });
106
110
  this.privateKey = privateKey;
107
111
  this.publicJwk = { ...(await exportJWK(publicKey)), kid: this.kid, alg: 'RS256', use: 'sig' };
112
+ await this.workloads.start();
108
113
 
109
114
  this.#server = createServer((req, res) => {
110
115
  // Dev-only: stands in for `cloudflared access login`. Cloudflare Access
package/src/idp/index.ts CHANGED
@@ -3,3 +3,4 @@
3
3
  // it; the dev loop and the tests use it too.
4
4
  export { DEFAULT_CLIENT, DevIdp, type DevIdpClient, type DevIdpOptions, type RegisteredClient } from './idp.ts';
5
5
  export { PERSONAS, type GitHubAccount, type GitHubAccountPatch, type Persona } from './people.ts';
6
+ export { GITHUB_RUN, WorkloadIssuer } from './workloads.ts';
@@ -0,0 +1,124 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ import { exportJWK, generateKeyPair, SignJWT, type CryptoKey, type JWK } from 'jose';
4
+
5
+ import { readParams, sendJson, type Route } from './http.ts';
6
+
7
+ /**
8
+ * A CI platform's ID tokens, as GitHub Actions signs them for a run: an
9
+ * issuer of its own under `/workloads`, with its discovery document and its
10
+ * keys, one RS256 and one ES256, and tokens minted for whatever run a check
11
+ * describes. What coffre's trust bindings and exchange are checked against,
12
+ * through their real code paths: discovery, a key set fetched over HTTP, a
13
+ * signature verified.
14
+ *
15
+ * `GET /workloads/actions` answers as a GitHub runner does a job with
16
+ * `permissions: id-token: write`, to the bearer of `requestToken`. Locally,
17
+ * `POST /workloads/token` mints one, for trying the CLI by hand:
18
+ *
19
+ * COFFRE_ID_TOKEN=$(curl -s -X POST http://127.0.0.1:8081/workloads/token \
20
+ * -d aud=http://127.0.0.1:3000 | jq -r .token)
21
+ */
22
+ export class WorkloadIssuer {
23
+ readonly #origin: () => string;
24
+ /** A job's ACTIONS_ID_TOKEN_REQUEST_TOKEN: the bearer `GET /workloads/actions` wants. */
25
+ readonly requestToken = randomBytes(16).toString('hex');
26
+ #keys: { alg: 'RS256' | 'ES256'; kid: string; privateKey: CryptoKey; jwk: JWK }[] = [];
27
+
28
+ constructor(origin: () => string) {
29
+ this.#origin = origin;
30
+ }
31
+
32
+ /** Where the tokens say they come from: `http://127.0.0.1:<port>/workloads`. */
33
+ get issuer(): string {
34
+ return `${this.#origin()}/workloads`;
35
+ }
36
+
37
+ get jwksUrl(): string {
38
+ return `${this.issuer}/jwks`;
39
+ }
40
+
41
+ /** A job's ACTIONS_ID_TOKEN_REQUEST_URL, which already has a query, as GitHub's does. */
42
+ get requestUrl(): string {
43
+ return `${this.issuer}/actions?api-version=2.0`;
44
+ }
45
+
46
+ async start(): Promise<void> {
47
+ this.#keys = await Promise.all(
48
+ (['RS256', 'ES256'] as const).map(async (alg) => {
49
+ const { privateKey, publicKey } = await generateKeyPair(alg, { extractable: true });
50
+ const kid = `dev-workloads-${alg.toLowerCase()}`;
51
+ return { alg, kid, privateKey, jwk: { ...(await exportJWK(publicKey)), kid, alg, use: 'sig' } };
52
+ }),
53
+ );
54
+ }
55
+
56
+ /**
57
+ * A run's ID token: GitHub's claims for a push of `deploy.yml` to `main`
58
+ * of `acme/api`, for `audience`, valid five minutes, unless `claims` says
59
+ * otherwise.
60
+ */
61
+ async mint(audience: string, claims: Record<string, unknown> = {}, alg: 'RS256' | 'ES256' = 'RS256'): Promise<string> {
62
+ const key = this.#keys.find((candidate) => candidate.alg === alg);
63
+ if (key === undefined) throw new Error('the workload issuer is not started');
64
+ const now = Math.floor(Date.now() / 1000);
65
+ return new SignJWT({ ...GITHUB_RUN, iss: this.issuer, aud: audience, iat: now, nbf: now - 5, exp: now + 300, jti: crypto.randomUUID(), ...claims })
66
+ .setProtectedHeader({ alg: key.alg, kid: key.kid, typ: 'JWT' })
67
+ .sign(key.privateKey);
68
+ }
69
+
70
+ routes(): Route[] {
71
+ return [
72
+ {
73
+ method: 'GET',
74
+ path: '/workloads/.well-known/openid-configuration',
75
+ handler: async (_req, res) =>
76
+ sendJson(res, 200, {
77
+ issuer: this.issuer,
78
+ jwks_uri: this.jwksUrl,
79
+ subject_types_supported: ['public'],
80
+ response_types_supported: ['id_token'],
81
+ id_token_signing_alg_values_supported: ['RS256', 'ES256'],
82
+ claims_supported: Object.keys(GITHUB_RUN),
83
+ }),
84
+ },
85
+ { method: 'GET', path: '/workloads/jwks', handler: async (_req, res) => sendJson(res, 200, { keys: this.#keys.map((key) => key.jwk) }) },
86
+ {
87
+ method: 'GET',
88
+ path: '/workloads/actions',
89
+ handler: async (req, res, url) => {
90
+ if (req.headers.authorization?.replace(/^bearer /i, '') !== this.requestToken) return sendJson(res, 401, { message: 'Bad credentials' });
91
+ const audience = url.searchParams.get('audience');
92
+ if (audience === null) return sendJson(res, 400, { message: 'no audience' });
93
+ sendJson(res, 200, { count: 1, value: await this.mint(audience) });
94
+ },
95
+ },
96
+ {
97
+ method: 'POST',
98
+ path: '/workloads/token',
99
+ handler: async (req, res) => {
100
+ const params = await readParams(req);
101
+ const alg = params?.get('alg') === 'ES256' ? 'ES256' : 'RS256';
102
+ sendJson(res, 200, { token: await this.mint(params?.get('aud') ?? 'http://127.0.0.1:3000', {}, alg) });
103
+ },
104
+ },
105
+ ];
106
+ }
107
+ }
108
+
109
+ /** A run of `deploy.yml`, pushed to `main` of `acme/api`, as GitHub's token says it. */
110
+ export const GITHUB_RUN = {
111
+ sub: 'repo:acme/api:ref:refs/heads/main',
112
+ repository: 'acme/api',
113
+ repository_id: '41532',
114
+ repository_owner: 'acme',
115
+ repository_owner_id: '9919',
116
+ workflow_ref: 'acme/api/.github/workflows/deploy.yml@refs/heads/main',
117
+ ref: 'refs/heads/main',
118
+ ref_type: 'branch',
119
+ event_name: 'push',
120
+ run_id: '7001',
121
+ run_attempt: '1',
122
+ sha: '3f2a9c1e7b6d5c4a3f2a9c1e7b6d5c4a3f2a9c1e',
123
+ actor: 'ada',
124
+ } as const;
package/src/suite.ts CHANGED
@@ -14,6 +14,7 @@ import { canaryScan } from './checks/canaries.ts';
14
14
  import { Cli, cliLogin, verifyAsOwner, verifyAsUser, verifyInterrupted, verifyKeys, verifyLeftovers, verifyWithToken } from './checks/cli.ts';
15
15
  import { pageLoad, personas, setUp, setUpLive, signInAdmin } from './checks/people.ts';
16
16
  import { health } from './checks/surface.ts';
17
+ import { cliSignsIn, exchangesLimited, runSignsIn, runsRefused, runUnbound, spentOnce, tokensUnlogged, trustRun } from './checks/workloads.ts';
17
18
 
18
19
  /** The names of the checks that failed. */
19
20
  export async function conform(deployment: Deployment, options: { bulkLimit: number }): Promise<string[]> {
@@ -52,6 +53,16 @@ export async function conform(deployment: Deployment, options: { bulkLimit: numb
52
53
  }
53
54
  await report.check('offboarding', all, ({ people, canaries }) => offboarding(deployment, people, canaries));
54
55
  await report.check('bulk limit', { people }, ({ people }) => bulkLimit(people, options.bulkLimit));
56
+ // A CI run signing in with its ID token, through a binding. The limit
57
+ // comes last of these: it spends this address's exchanges for the minute.
58
+ const binding = await report.check('trust a run', { admin }, ({ admin }) => trustRun(deployment, admin));
59
+ const credential = await report.check('run signs in', { admin, canaries, binding }, ({ admin, canaries }) => runSignsIn(deployment, admin, canaries));
60
+ await report.check('run token spent', { binding }, () => spentOnce(deployment));
61
+ await report.check('runs refused', { admin, binding }, ({ admin }) => runsRefused(deployment, admin));
62
+ await report.check('run signs in by CLI', { canaries, binding }, ({ canaries }) => cliSignsIn(deployment, canaries));
63
+ await report.check('run unbound', { admin, binding, credential }, ({ admin, binding, credential }) => runUnbound(deployment, admin, binding, credential));
64
+ await report.check('exchanges limited', { binding }, () => exchangesLimited(deployment));
65
+ await report.check('tokens unlogged', { binding }, () => tokensUnlogged(deployment));
55
66
 
56
67
  await report.check('checkpoints', { people }, ({ people }) => checkpoints(deployment, people));
57
68
  await report.check('keys behind writes', { people }, ({ people }) => writesAgree(deployment));