@intentius/chant 0.124.86 → 0.124.87

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.
Files changed (91) hide show
  1. package/dist/ci-commit.d.ts +1 -1
  2. package/dist/ci-evidence-jobs.d.ts +31 -7
  3. package/dist/ci-evidence-jobs.d.ts.map +1 -1
  4. package/dist/ci-evidence-jobs.js +35 -5
  5. package/dist/ci-product.d.ts +1 -1
  6. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  7. package/dist/cli/handlers/ci-check.js +17 -13
  8. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -1
  9. package/dist/cli/handlers/ci-evidence.js +11 -8
  10. package/dist/components/check-hooks.js +3 -3
  11. package/dist/components/check-steps.js +1 -1
  12. package/dist/components/product-plan.d.ts +7 -1
  13. package/dist/components/product-plan.d.ts.map +1 -1
  14. package/dist/components/product-plan.js +3 -1
  15. package/dist/floor-table.data.d.ts.map +1 -1
  16. package/dist/floor-table.data.js +1 -0
  17. package/dist/op/op-waves-evidence.d.ts +5 -3
  18. package/dist/op/op-waves-evidence.d.ts.map +1 -1
  19. package/dist/op/op-waves-evidence.js +9 -8
  20. package/dist/release-floors.d.ts +18 -16
  21. package/dist/release-floors.d.ts.map +1 -1
  22. package/dist/release-floors.js +3 -1
  23. package/dist/state-migration.d.ts +1 -1
  24. package/dist/wave-runtime.mjs +299 -299
  25. package/dist/workspace/ci-green.d.ts.map +1 -1
  26. package/dist/workspace/ci-green.js +4 -3
  27. package/dist/workspace/trust/check-evidence-report.d.ts +7 -0
  28. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -1
  29. package/dist/workspace/trust/check-evidence-report.js +7 -0
  30. package/dist/workspace/trust/check-evidence.d.ts +46 -12
  31. package/dist/workspace/trust/check-evidence.d.ts.map +1 -1
  32. package/dist/workspace/trust/check-evidence.js +94 -22
  33. package/dist/workspace/trust/ci-tag-statement.d.ts +2 -2
  34. package/dist/workspace/trust/ci-tag-statement.d.ts.map +1 -1
  35. package/dist/workspace/trust/dsse.d.ts +40 -2
  36. package/dist/workspace/trust/dsse.d.ts.map +1 -1
  37. package/dist/workspace/trust/dsse.js +34 -2
  38. package/dist/workspace/trust/evidence.d.ts +2 -2
  39. package/dist/workspace/trust/evidence.d.ts.map +1 -1
  40. package/dist/workspace/trust/keyless-fixture.d.ts +41 -0
  41. package/dist/workspace/trust/keyless-fixture.d.ts.map +1 -0
  42. package/dist/workspace/trust/keyless-fixture.js +161 -0
  43. package/dist/workspace/trust/keyless.d.ts +202 -0
  44. package/dist/workspace/trust/keyless.d.ts.map +1 -0
  45. package/dist/workspace/trust/keyless.js +488 -0
  46. package/dist/workspace/trust/local-evidence.d.ts +3 -0
  47. package/dist/workspace/trust/local-evidence.d.ts.map +1 -1
  48. package/dist/workspace/trust/op-run-statement.d.ts +2 -2
  49. package/dist/workspace/trust/op-run-statement.d.ts.map +1 -1
  50. package/dist/workspace/trust/policy.d.ts +56 -1
  51. package/dist/workspace/trust/policy.d.ts.map +1 -1
  52. package/dist/workspace/trust/policy.js +103 -2
  53. package/dist/workspace/trust/ref-gate.d.ts +1 -1
  54. package/dist/workspace/trust/ref-gate.d.ts.map +1 -1
  55. package/dist/workspace/trust/ref-gate.js +3 -1
  56. package/dist/workspace/trust/run-statement.d.ts +3 -3
  57. package/dist/workspace/trust/run-statement.d.ts.map +1 -1
  58. package/dist/workspace/trust/runner-identity.d.ts +56 -0
  59. package/dist/workspace/trust/runner-identity.d.ts.map +1 -0
  60. package/dist/workspace/trust/runner-identity.js +65 -0
  61. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  62. package/dist/workspace/trust/trust-files.js +8 -1
  63. package/package.json +1 -1
  64. package/src/ci-evidence-jobs.ts +45 -7
  65. package/src/cli/handlers/ci-check.ts +16 -12
  66. package/src/cli/handlers/ci-evidence.ts +13 -8
  67. package/src/components/check-hooks.ts +3 -3
  68. package/src/components/check-steps.ts +1 -1
  69. package/src/components/product-plan.ts +7 -3
  70. package/src/floor-table.data.ts +1 -0
  71. package/src/op/op-waves-evidence.test.ts +1 -1
  72. package/src/op/op-waves-evidence.ts +10 -9
  73. package/src/release-floors.ts +4 -1
  74. package/src/workspace/ci-green.ts +4 -3
  75. package/src/workspace/trust/check-evidence-report.ts +9 -0
  76. package/src/workspace/trust/check-evidence.test.ts +3 -3
  77. package/src/workspace/trust/check-evidence.ts +95 -25
  78. package/src/workspace/trust/ci-tag-statement.ts +2 -2
  79. package/src/workspace/trust/dsse.ts +48 -4
  80. package/src/workspace/trust/evidence.ts +2 -2
  81. package/src/workspace/trust/keyless-fixture.ts +214 -0
  82. package/src/workspace/trust/keyless.test.ts +220 -0
  83. package/src/workspace/trust/keyless.ts +557 -0
  84. package/src/workspace/trust/local-evidence.ts +3 -1
  85. package/src/workspace/trust/op-run-statement.ts +2 -2
  86. package/src/workspace/trust/policy.ts +129 -2
  87. package/src/workspace/trust/ref-gate.ts +3 -2
  88. package/src/workspace/trust/run-statement.ts +3 -3
  89. package/src/workspace/trust/runner-identity.ts +92 -0
  90. package/src/workspace/trust/trust-files.test.ts +6 -0
  91. package/src/workspace/trust/trust-files.ts +14 -1
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Test support for keyless runner statements (#4869): a fake forge token
3
+ * service, a fake Fulcio certificate authority and a fake RFC 3161
4
+ * timestamp authority, all answered by one `fetch` that never leaves the
5
+ * process. The certificates and timestamps are real DER, signed with keys
6
+ * made here, so ./keyless.ts verifies them as it would sigstore's. The
7
+ * clock is the fixture's, so a test can sign in the past and verify after
8
+ * the certificate expired.
9
+ */
10
+
11
+ import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign, verify, X509Certificate, type KeyObject } from "node:crypto";
12
+ import { DER, der, derChildren, derInt, derOid, derRead, OID } from "./keyless";
13
+
14
+ const ECDSA_SHA256 = "1.2.840.10045.4.3.2";
15
+ const CN = "2.5.4.3";
16
+
17
+ const name = (cn: string): Buffer => der(DER.SEQUENCE, der(DER.SET, der(DER.SEQUENCE, derOid(CN), der(DER.UTF8, Buffer.from(cn)))));
18
+ const algId = (oid: string, withNull = false): Buffer => der(DER.SEQUENCE, derOid(oid), ...(withNull ? [der(DER.NULL)] : []));
19
+ const ext = (oid: string, critical: boolean, value: Buffer): Buffer => der(DER.SEQUENCE, derOid(oid), ...(critical ? [der(DER.BOOLEAN, Buffer.from([0xff]))] : []), der(DER.OCTET_STRING, value));
20
+
21
+ function utcTime(d: Date): Buffer {
22
+ const iso = d.toISOString();
23
+ return der(DER.UTC_TIME, Buffer.from(`${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`));
24
+ }
25
+
26
+ function generalized(d: Date): Buffer {
27
+ const iso = d.toISOString();
28
+ return der(DER.GENERALIZED_TIME, Buffer.from(`${iso.slice(0, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`));
29
+ }
30
+
31
+ interface Issued {
32
+ cert: X509Certificate;
33
+ der: Buffer;
34
+ key?: KeyObject;
35
+ cn: string;
36
+ }
37
+
38
+ /** A certificate for `publicKey`, signed by `issuer` (or by `selfKey`, self-signed). */
39
+ function certificate(opts: { cn: string; publicKey: KeyObject; issuer?: Issued; signKey: KeyObject; notBefore: Date; notAfter: Date; extensions: Buffer[] }): Buffer {
40
+ const tbs = der(
41
+ DER.SEQUENCE,
42
+ der(0xa0, derInt(2)),
43
+ derInt(randomBytes(8)),
44
+ algId(ECDSA_SHA256),
45
+ name(opts.issuer?.cn ?? opts.cn),
46
+ der(DER.SEQUENCE, utcTime(opts.notBefore), utcTime(opts.notAfter)),
47
+ name(opts.cn),
48
+ opts.publicKey.export({ format: "der", type: "spki" }) as Buffer,
49
+ der(0xa3, der(DER.SEQUENCE, ...opts.extensions)),
50
+ );
51
+ return der(DER.SEQUENCE, tbs, algId(ECDSA_SHA256), der(DER.BIT_STRING, Buffer.from([0]), sign("sha256", tbs, opts.signKey)));
52
+ }
53
+
54
+ const CA_EXTENSIONS = [ext("2.5.29.19", true, der(DER.SEQUENCE, der(DER.BOOLEAN, Buffer.from([0xff])))), ext("2.5.29.15", true, der(DER.BIT_STRING, Buffer.from([1, 0x06])))];
55
+
56
+ function authority(cn: string, notBefore: Date): Issued {
57
+ const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
58
+ const bytes = certificate({ cn, publicKey, signKey: privateKey, notBefore, notAfter: new Date(notBefore.getTime() + 30 * 365 * 86400_000), extensions: CA_EXTENSIONS });
59
+ return { cert: new X509Certificate(bytes), der: bytes, key: privateKey, cn };
60
+ }
61
+
62
+ /** A fake forge OIDC token with `claims`: a JWT whose signature nothing checks but the fake authority. */
63
+ export function fakeToken(claims: Record<string, unknown>): string {
64
+ const part = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
65
+ return `${part({ alg: "RS256", typ: "JWT" })}.${part(claims)}.fake-signature-4869`;
66
+ }
67
+
68
+ /** The claims of a GitHub Actions job's token for `workflow` of `repository` at `ref`. */
69
+ export function githubClaims(repository: string, workflow: string, ref: string): Record<string, unknown> {
70
+ return {
71
+ iss: FAKE_GITHUB_ISSUER,
72
+ sub: `repo:${repository}:ref:${ref}`,
73
+ aud: "sigstore",
74
+ repository,
75
+ ref,
76
+ job_workflow_ref: `${repository}/.github/workflows/${workflow}@${ref}`,
77
+ };
78
+ }
79
+
80
+ /** The issuer the fake authority accepts GitHub-shaped tokens from. */
81
+ export const FAKE_GITHUB_ISSUER = "https://token.actions.githubusercontent.com";
82
+
83
+ export const FAKE_FULCIO_URL = "https://fulcio.fake.test";
84
+ export const FAKE_TSA_URL = "https://tsa.fake.test/api/v1/timestamp";
85
+ export const FAKE_TOKEN_URL = "https://forge.fake.test/oidc/token?api-version=2.0";
86
+ export const FAKE_REQUEST_TOKEN = "fake-request-token-4869";
87
+
88
+ /** What the fakes were asked. */
89
+ export interface SigstoreFakeLog {
90
+ tokens: string[];
91
+ certificates: string[];
92
+ timestamps: number;
93
+ }
94
+
95
+ export interface SigstoreFake {
96
+ /** Answers the forge's token URL, Fulcio and the timestamp authority. Anything else is refused. */
97
+ fetch: typeof fetch;
98
+ /** The trusted root, in sigstore's `trusted_root.json` format. */
99
+ trustedRoot: string;
100
+ /** The environment of a GitHub job with `id-token: write`, whose token carries `claims`. */
101
+ jobEnv(claims: Record<string, unknown>): NodeJS.ProcessEnv;
102
+ log: SigstoreFakeLog;
103
+ /** Sets the time the authorities issue and stamp at. */
104
+ setNow(d: Date): void;
105
+ }
106
+
107
+ /** Start the fakes. `now` is the authorities' clock; the authorities' own certificates are valid from 2020 for 30 years. */
108
+ export function sigstoreFake(opts: { now?: Date } = {}): SigstoreFake {
109
+ let now = opts.now ?? new Date();
110
+ const epoch = new Date("2020-01-01T00:00:00Z");
111
+ const ca = authority("fake fulcio root 4869", epoch);
112
+ const tsaRoot = authority("fake tsa root 4869", epoch);
113
+ const tsaPair = generateKeyPairSync("ec", { namedCurve: "P-256" });
114
+ const tsaDer = certificate({
115
+ cn: "fake tsa 4869",
116
+ publicKey: tsaPair.publicKey,
117
+ issuer: tsaRoot,
118
+ signKey: tsaRoot.key!,
119
+ notBefore: epoch,
120
+ notAfter: new Date(epoch.getTime() + 30 * 365 * 86400_000),
121
+ extensions: [ext("2.5.29.37", true, der(DER.SEQUENCE, derOid(OID.timeStamping)))],
122
+ });
123
+ const tsa: Issued = { cert: new X509Certificate(tsaDer), der: tsaDer, key: tsaPair.privateKey, cn: "fake tsa 4869" };
124
+ const log: SigstoreFakeLog = { tokens: [], certificates: [], timestamps: 0 };
125
+ const pending = new Map<string, string>();
126
+
127
+ const pem = (b: Buffer) => `-----BEGIN CERTIFICATE-----\n${b.toString("base64").replace(/(.{64})/g, "$1\n")}\n-----END CERTIFICATE-----\n`;
128
+
129
+ const issueLeaf = (body: string): Response => {
130
+ const req = JSON.parse(body) as { credentials: { oidcIdentityToken: string }; publicKeyRequest: { publicKey: { content: string }; proofOfPossession: string } };
131
+ const token = req.credentials.oidcIdentityToken;
132
+ const claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString()) as Record<string, string>;
133
+ if (claims.iss !== FAKE_GITHUB_ISSUER || claims.aud !== "sigstore") return new Response("token refused", { status: 401 });
134
+ const publicKey = createPublicKey(req.publicKeyRequest.publicKey.content);
135
+ if (!verify("sha256", Buffer.from(claims.sub!), publicKey, Buffer.from(req.publicKeyRequest.proofOfPossession, "base64"))) return new Response("no proof of possession", { status: 400 });
136
+ const san = `https://github.com/${claims.job_workflow_ref}`;
137
+ log.certificates.push(san);
138
+ const leaf = certificate({
139
+ cn: "sigstore",
140
+ publicKey,
141
+ issuer: ca,
142
+ signKey: ca.key!,
143
+ notBefore: now,
144
+ notAfter: new Date(now.getTime() + 10 * 60_000),
145
+ extensions: [
146
+ ext("2.5.29.15", true, der(DER.BIT_STRING, Buffer.from([7, 0x80]))),
147
+ ext("2.5.29.37", false, der(DER.SEQUENCE, derOid(OID.codeSigning))),
148
+ ext("2.5.29.17", true, der(DER.SEQUENCE, der(0x86, Buffer.from(san)))),
149
+ ext(OID.fulcioIssuerV1, false, Buffer.from(claims.iss!)),
150
+ ext(OID.fulcioIssuerV2, false, der(DER.UTF8, Buffer.from(claims.iss!))),
151
+ ],
152
+ });
153
+ return Response.json({ signedCertificateEmbeddedSct: { chain: { certificates: [pem(leaf), pem(ca.der)] } } });
154
+ };
155
+
156
+ const stamp = (body: Buffer): Response => {
157
+ const req = derChildren(derRead(body));
158
+ const imprint = derChildren(req[1]!);
159
+ const hashed = imprint[1]!.value;
160
+ log.timestamps++;
161
+ const tstInfo = der(DER.SEQUENCE, derInt(1), derOid("1.2.3.4.4869"), der(DER.SEQUENCE, algId(OID.sha256, true), der(DER.OCTET_STRING, hashed)), derInt(randomBytes(8)), generalized(now));
162
+ const attrs = [
163
+ der(DER.SEQUENCE, derOid(OID.contentType), der(DER.SET, derOid(OID.tstInfo))),
164
+ der(DER.SEQUENCE, derOid(OID.messageDigest), der(DER.SET, der(DER.OCTET_STRING, createHash("sha256").update(tstInfo).digest()))),
165
+ ];
166
+ const signature = sign("sha256", der(DER.SET, ...attrs), tsa.key!);
167
+ const issuerSerial = derChildren(derChildren(derRead(tsa.der))[0]!);
168
+ const signerInfo = der(DER.SEQUENCE, derInt(1), der(DER.SEQUENCE, issuerSerial[3]!.raw, issuerSerial[1]!.raw), algId(OID.sha256), der(0xa0, ...attrs), algId(ECDSA_SHA256), der(DER.OCTET_STRING, signature));
169
+ const signedData = der(DER.SEQUENCE, derInt(3), der(DER.SET, algId(OID.sha256)), der(DER.SEQUENCE, derOid(OID.tstInfo), der(0xa0, der(DER.OCTET_STRING, tstInfo))), der(0xa0, tsa.der), der(DER.SET, signerInfo));
170
+ const token = der(DER.SEQUENCE, derOid(OID.signedData), der(0xa0, signedData));
171
+ return new Response(new Uint8Array(der(DER.SEQUENCE, der(DER.SEQUENCE, derInt(0)), token)), { headers: { "content-type": "application/timestamp-reply" } });
172
+ };
173
+
174
+ const fakeFetch = (async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
175
+ const url = String(input instanceof Request ? input.url : input);
176
+ const headers = new Headers(init?.headers);
177
+ if (url.startsWith(FAKE_TOKEN_URL)) {
178
+ if (headers.get("authorization") !== `bearer ${FAKE_REQUEST_TOKEN}`) return new Response("no", { status: 403 });
179
+ const id = new URL(url).searchParams.get("job") ?? "";
180
+ const claims = pending.get(id);
181
+ if (!claims) return new Response("unknown job", { status: 404 });
182
+ const audience = new URL(url).searchParams.get("audience");
183
+ log.tokens.push(audience ?? "");
184
+ return Response.json({ value: fakeToken({ ...JSON.parse(claims), aud: audience }) });
185
+ }
186
+ if (url === `${FAKE_FULCIO_URL}/api/v2/signingCert`) return issueLeaf(String(init?.body));
187
+ if (url === FAKE_TSA_URL) return stamp(Buffer.from(init?.body as Uint8Array));
188
+ throw new Error(`the sigstore fake refuses ${url}: a test never reaches a real service`);
189
+ }) as typeof fetch;
190
+
191
+ const trustedRoot = JSON.stringify(
192
+ {
193
+ mediaType: "application/vnd.dev.sigstore.trustedroot+json;version=0.1",
194
+ certificateAuthorities: [{ uri: FAKE_FULCIO_URL, certChain: { certificates: [{ rawBytes: ca.der.toString("base64") }] }, validFor: { start: epoch.toISOString() } }],
195
+ timestampAuthorities: [{ uri: FAKE_TSA_URL, certChain: { certificates: [{ rawBytes: tsa.der.toString("base64") }, { rawBytes: tsaRoot.der.toString("base64") }] }, validFor: { start: epoch.toISOString() } }],
196
+ },
197
+ null,
198
+ 2,
199
+ );
200
+
201
+ return {
202
+ fetch: fakeFetch,
203
+ trustedRoot,
204
+ log,
205
+ setNow: (d) => {
206
+ now = d;
207
+ },
208
+ jobEnv: (claims) => {
209
+ const id = String(pending.size + 1);
210
+ pending.set(id, JSON.stringify(claims));
211
+ return { ACTIONS_ID_TOKEN_REQUEST_URL: `${FAKE_TOKEN_URL}&job=${id}`, ACTIONS_ID_TOKEN_REQUEST_TOKEN: FAKE_REQUEST_TOKEN };
212
+ },
213
+ };
214
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * #4869: runner statements signed keyless from the CI job's OIDC identity.
3
+ * A fake forge token, a fake certificate authority and a fake timestamp
4
+ * authority (./keyless-fixture.ts); nothing reaches sigstore or a forge.
5
+ *
6
+ * Done when: a green tag, an Op run and a piece of runner evidence signed
7
+ * by a listed workflow identity verify offline, and one signed by another
8
+ * workflow is reported and ignored; verification works after the
9
+ * certificate expired; key-signed statements from before `keyless.since`
10
+ * still count.
11
+ */
12
+
13
+ import { execFileSync } from "node:child_process";
14
+ import { generateKeyPairSync } from "node:crypto";
15
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { describe, expect, test } from "vitest";
19
+ import { canonicalJson } from "../../effect-receipt";
20
+ import { gitRevisionSource } from "../record-source";
21
+ import { keylessEvidenceSigner, readCheckEvidence, recordChecks, runnerEvidenceSigner, runnerKeyEvidenceSigner, signChecks, type EvidenceSigner } from "./check-evidence";
22
+ import { buildCiTagStatement, verifyCiTagStatement, type CiTagRecord } from "./ci-tag-statement";
23
+ import { IN_TOTO_PAYLOAD_TYPE, loadRunnerKey } from "./dsse";
24
+ import { githubClaims, sigstoreFake, FAKE_FULCIO_URL, FAKE_GITHUB_ISSUER, FAKE_TSA_URL, type SigstoreFake } from "./keyless-fixture";
25
+ import { subjectPattern } from "./keyless";
26
+ import { buildOpRunStatement, verifyOpRunStatement } from "./op-run-statement";
27
+ import { protectedPaths, readTrustPolicy, runnersAt } from "./policy";
28
+ import type { OpRunRecord } from "../../op/runtime";
29
+
30
+ function git(cwd: string, ...args: string[]): string {
31
+ return execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false", ...args], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
32
+ }
33
+
34
+ const REPO = "acme/infra";
35
+ const LISTED = `https://github.com/${REPO}/.github/workflows/chant-*.yml@refs/heads/main`;
36
+
37
+ function runnerKey(): { pem: string; pub: string } {
38
+ const { privateKey } = generateKeyPairSync("ed25519");
39
+ const pem = privateKey.export({ format: "pem", type: "pkcs8" }).toString();
40
+ return { pem, pub: loadRunnerKey(pem).publicKey };
41
+ }
42
+
43
+ /** A repository whose base lists `ci` keyless (and, with `key`, by a runner key too), and a change on top. */
44
+ function repo(fake: SigstoreFake, opts: { key?: string; since?: (dir: string) => string } = {}): { dir: string; base: string; head: string } {
45
+ const dir = mkdtempSync(join(tmpdir(), "chant-4869-"));
46
+ git(dir, "init", "--quiet");
47
+ mkdirSync(join(dir, ".chant"));
48
+ writeFileSync(join(dir, "main.tf"), "# one\n");
49
+ git(dir, "add", ".");
50
+ git(dir, "commit", "--quiet", "-m", "one");
51
+ const trust = (since?: string) =>
52
+ JSON.stringify({
53
+ schema: 1,
54
+ roles: { runner: ["ci"] },
55
+ ...(opts.key ? { runners: [{ principal: "ci", class: "runner", key: opts.key }] } : {}),
56
+ keyless: {
57
+ trustedRoot: ".chant/trusted_root.json",
58
+ fulcio: FAKE_FULCIO_URL,
59
+ timestamp: FAKE_TSA_URL,
60
+ identities: [{ principal: "ci", class: "runner", issuer: FAKE_GITHUB_ISSUER, subject: LISTED }],
61
+ ...(since ? { since } : {}),
62
+ },
63
+ });
64
+ writeFileSync(join(dir, ".chant/trusted_root.json"), fake.trustedRoot);
65
+ writeFileSync(join(dir, ".chant/trust.json"), trust());
66
+ git(dir, "add", ".");
67
+ git(dir, "commit", "--quiet", "-m", "trust");
68
+ if (opts.since) {
69
+ writeFileSync(join(dir, ".chant/trust.json"), trust(opts.since(dir)));
70
+ git(dir, "commit", "--quiet", "-am", "since");
71
+ }
72
+ const base = git(dir, "rev-parse", "HEAD");
73
+ writeFileSync(join(dir, "main.tf"), "# change\n");
74
+ git(dir, "commit", "--quiet", "-am", "change");
75
+ return { dir, base, head: git(dir, "rev-parse", "HEAD") };
76
+ }
77
+
78
+ const listedJob = (fake: SigstoreFake) => fake.jobEnv(githubClaims(REPO, "chant-pr.yml", "refs/heads/main"));
79
+ const otherJob = (fake: SigstoreFake) => fake.jobEnv(githubClaims(REPO, "deploy.yml", "refs/heads/main"));
80
+
81
+ /** A signer for another workflow's job: it gets a certificate, which the policy does not list, so it signs as `ci` regardless. */
82
+ async function rogueSigner(fake: SigstoreFake, r: { dir: string; base: string }): Promise<EvidenceSigner> {
83
+ const listed = await keylessEvidenceSigner(r.dir, r.base, { env: listedJob(fake), fetch: fake.fetch });
84
+ const { requestCertificate, keylessSignature, signingToken } = await import("./keyless");
85
+ const { pae } = await import("./dsse");
86
+ const cert = await requestCertificate(await signingToken(otherJob(fake), "sigstore", fake.fetch), FAKE_FULCIO_URL, fake.fetch);
87
+ return {
88
+ principal: listed.principal,
89
+ sign: async (payloadType, payload) => ({ payloadType, payload: payload.toString("base64"), signatures: [await keylessSignature(pae(payloadType, payload), cert, FAKE_TSA_URL, fake.fetch)] }),
90
+ };
91
+ }
92
+
93
+ describe("keyless runner statements (#4869)", () => {
94
+ test("runner evidence signed by a listed workflow identity verifies offline; another workflow's is reported and ignored", async () => {
95
+ const fake = sigstoreFake();
96
+ const r = repo(fake);
97
+ const signer = await keylessEvidenceSigner(r.dir, r.base, { env: listedJob(fake), fetch: fake.fetch });
98
+ expect(signer.principal).toBe("ci");
99
+ expect(fake.log.tokens).toEqual(["sigstore"]);
100
+ await recordChecks(r.dir, await signChecks(r.dir, r.head, [{ check: "plan" }], signer), { push: false });
101
+ expect(await readCheckEvidence(r.dir, r.head, r.base, ["plan"])).toEqual([{ check: "plan", status: "current", runner: "ci", commit: r.head }]);
102
+
103
+ // Another workflow of the same repository: its own certificate, which the policy does not list.
104
+ const rogue = await rogueSigner(fake, r);
105
+ await recordChecks(r.dir, await signChecks(r.dir, r.head, [{ check: "policy" }], rogue), { push: false });
106
+ const [v] = await readCheckEvidence(r.dir, r.head, r.base, ["policy"]);
107
+ expect(v!.status).toBe("untrusted");
108
+ expect(v).toMatchObject({ reason: expect.stringContaining(`https://github.com/${REPO}/.github/workflows/deploy.yml@refs/heads/main`) });
109
+ expect(v).toMatchObject({ reason: expect.stringContaining("not one the policy at base lists under keyless.identities") });
110
+ });
111
+
112
+ test("the signer refuses a job whose identity the policy does not list, before it signs anything", async () => {
113
+ const fake = sigstoreFake();
114
+ const r = repo(fake);
115
+ await expect(keylessEvidenceSigner(r.dir, r.base, { env: otherJob(fake), fetch: fake.fetch })).rejects.toThrow(/lists no keyless identity for this job .*deploy\.yml/);
116
+ expect(fake.log.timestamps).toBe(0);
117
+ await expect(keylessEvidenceSigner(r.dir, r.base, { env: {}, fetch: fake.fetch })).rejects.toThrow(/id-token: write/);
118
+ });
119
+
120
+ test("a green tag and an Op run signed keyless verify offline, and another workflow's are ignored", async () => {
121
+ const fake = sigstoreFake();
122
+ const r = repo(fake);
123
+ const policy = readTrustPolicy(gitRevisionSource(r.dir, r.base), r.base);
124
+ const runners = runnersAt(policy, { repo: r.dir, commit: r.head });
125
+ const signer = await keylessEvidenceSigner(r.dir, r.base, { env: listedJob(fake), fetch: fake.fetch });
126
+ const rogue = await rogueSigner(fake, r);
127
+ const sign = (s: EvidenceSigner, statement: unknown) => s.sign(IN_TOTO_PAYLOAD_TYPE, Buffer.from(canonicalJson(statement), "utf8"));
128
+
129
+ const tag: CiTagRecord = { schema: 1, tag: "green", commit: r.head, branch: "main", at: "2026-11-09T00:00:00Z" };
130
+ const signedTag = { ...tag, statement: await sign(signer, buildCiTagStatement(tag, "ci")) };
131
+ expect(verifyCiTagStatement(signedTag, { sha: r.head, kind: "green", branch: "main" }, runners, policy.roles)).toMatchObject({ status: "signed", signer: "ci" });
132
+ const rogueTag = { ...tag, statement: await sign(rogue, buildCiTagStatement(tag, "ci")) };
133
+ expect(verifyCiTagStatement(rogueTag, { sha: r.head, kind: "green", branch: "main" }, runners, policy.roles)).toMatchObject({ status: "untrusted", reason: expect.stringContaining("deploy.yml") });
134
+
135
+ const run = { id: "run-1", op: "apply", env: "prod", status: "ok", gitSha: r.head } as unknown as OpRunRecord;
136
+ const signedRun = { ...run, statement: await sign(signer, buildOpRunStatement(run, "ci")) } as OpRunRecord;
137
+ expect(verifyOpRunStatement(signedRun, runners, policy.roles)).toMatchObject({ status: "signed", signer: "ci" });
138
+ const rogueRun = { ...run, statement: await sign(rogue, buildOpRunStatement(run, "ci")) } as OpRunRecord;
139
+ expect(verifyOpRunStatement(rogueRun, runners, policy.roles)).toMatchObject({ status: "untrusted" });
140
+ });
141
+
142
+ test("a statement verifies after its certificate expired: validity is judged at the timestamp's time", async () => {
143
+ // The authorities' clock is in 2021; the certificate lived ten minutes then. Verification runs now.
144
+ const fake = sigstoreFake({ now: new Date("2021-03-01T12:00:00Z") });
145
+ const r = repo(fake);
146
+ const signer = await keylessEvidenceSigner(r.dir, r.base, { env: listedJob(fake), fetch: fake.fetch });
147
+ await recordChecks(r.dir, await signChecks(r.dir, r.head, [{ check: "plan" }], signer), { push: false });
148
+ expect(await readCheckEvidence(r.dir, r.head, r.base, ["plan"])).toEqual([{ check: "plan", status: "current", runner: "ci", commit: r.head }]);
149
+
150
+ // A timestamp from after the certificate expired does not count.
151
+ const late = await keylessEvidenceSigner(r.dir, r.base, { env: listedJob(fake), fetch: fake.fetch });
152
+ fake.setNow(new Date("2021-03-01T12:30:00Z"));
153
+ await expect(signChecks(r.dir, r.head, [{ check: "policy" }], late)).rejects.toThrow(/does not chain to a certificate authority of the trusted root, valid at 2021-03-01T12:30/);
154
+ });
155
+
156
+ test("key-signed evidence before keyless.since still counts, and after it does not", async () => {
157
+ const fake = sigstoreFake();
158
+ const key = runnerKey();
159
+ let first = "";
160
+ const r = repo(fake, {
161
+ key: key.pub,
162
+ since: (dir) => {
163
+ first = git(dir, "rev-parse", "HEAD~1");
164
+ return git(dir, "rev-parse", "HEAD");
165
+ },
166
+ });
167
+ const keySigner = runnerKeyEvidenceSigner(r.dir, r.base, key.pem);
168
+ await recordChecks(r.dir, await signChecks(r.dir, first, [{ check: "plan" }], keySigner), { push: false });
169
+ await recordChecks(r.dir, await signChecks(r.dir, r.head, [{ check: "plan" }], keySigner), { push: false });
170
+ expect(await readCheckEvidence(r.dir, first, r.base, ["plan"])).toEqual([{ check: "plan", status: "current", runner: "ci", commit: first }]);
171
+ expect((await readCheckEvidence(r.dir, r.head, r.base, ["plan"]))[0]!.status).toBe("untrusted");
172
+ // The same commit signed keyless counts.
173
+ const keyless = await runnerEvidenceSigner(r.dir, r.base, { env: { ...listedJob(fake), CHANT_RUNNER_IDENTITY: "oidc" }, fetch: fake.fetch });
174
+ await recordChecks(r.dir, await signChecks(r.dir, r.head, [{ check: "plan" }], keyless!), { push: false });
175
+ expect(await readCheckEvidence(r.dir, r.head, r.base, ["plan"])).toEqual([{ check: "plan", status: "current", runner: "ci", commit: r.head }]);
176
+ });
177
+
178
+ test("a trusted root that does not read leaves the identities out, and since still leaves the keys out", () => {
179
+ const fake = sigstoreFake();
180
+ const r = repo(fake, { key: runnerKey().pub, since: (dir) => git(dir, "rev-parse", "HEAD") });
181
+ writeFileSync(join(r.dir, ".chant/trusted_root.json"), "{}");
182
+ git(r.dir, "commit", "--quiet", "-am", "break the root");
183
+ const at = git(r.dir, "rev-parse", "HEAD");
184
+ const policy = readTrustPolicy(gitRevisionSource(r.dir, at), at);
185
+ expect(policy.runnerIdentities).toEqual([]);
186
+ expect(policy.excludedRunners[0]!.reason).toMatch(/trusted root .chant\/trusted_root.json cannot be read/);
187
+ expect(runnersAt(policy, { repo: r.dir, commit: at })).toEqual([]);
188
+ expect(protectedPaths(policy)).toContain(".chant/trusted_root.json");
189
+ });
190
+
191
+ test("a subject pattern's * stays within a path segment, ** crosses them", () => {
192
+ expect(subjectPattern(LISTED).test(`https://github.com/${REPO}/.github/workflows/chant-pr.yml@refs/heads/main`)).toBe(true);
193
+ expect(subjectPattern(LISTED).test(`https://github.com/${REPO}/.github/workflows/sub/chant-pr.yml@refs/heads/main`)).toBe(false);
194
+ expect(subjectPattern("https://gitlab.com/acme/**@refs/heads/main").test("https://gitlab.com/acme/infra//.gitlab-ci.yml@refs/heads/main")).toBe(true);
195
+ });
196
+ });
197
+
198
+ describe("the runner identity an init writes (#4869)", () => {
199
+ test("a GitHub workflow's identity goes under keyless, and its principal under roles.runner, once", async () => {
200
+ const { ciRunnerIdentity, withRunnerIdentity } = await import("./runner-identity");
201
+ const id = ciRunnerIdentity({ forge: "github", repository: REPO, workflow: ".github/workflows/chant-pr.yml" });
202
+ expect(id).toEqual({ principal: "ci", class: "runner", issuer: FAKE_GITHUB_ISSUER, subject: `https://github.com/${REPO}/.github/workflows/chant-pr.yml@refs/heads/main` });
203
+ const once = withRunnerIdentity(JSON.stringify({ schema: 1, roles: { admin: ["alice"] } }), id);
204
+ expect(withRunnerIdentity(once, id)).toBe(once);
205
+ expect(JSON.parse(once)).toEqual({ schema: 1, roles: { admin: ["alice"], runner: ["ci"] }, keyless: { trustedRoot: ".chant/trusted_root.json", identities: [id] } });
206
+ expect(ciRunnerIdentity({ forge: "gitlab", repository: "acme/infra" }).subject).toBe("https://gitlab.com/acme/infra//.gitlab-ci.yml@refs/heads/main");
207
+ expect(() => ciRunnerIdentity({ forge: "forgejo", repository: "acme/infra", workflow: "x.yml" })).toThrow(/certificate authority the project runs/);
208
+ });
209
+ });
210
+
211
+ describe("DER INTEGERs (#4869)", () => {
212
+ test("a serial with leading zero bytes is written in minimal form, so OpenSSL reads the certificate", async () => {
213
+ const { derInt } = await import("./keyless");
214
+ expect(derInt(Buffer.from("003a2d0f26856400", "hex")).toString("hex")).toBe("02073a2d0f26856400");
215
+ expect(derInt(Buffer.from("0000ff", "hex")).toString("hex")).toBe("020200ff");
216
+ expect(derInt(Buffer.from("80", "hex")).toString("hex")).toBe("02020080");
217
+ expect(derInt(Buffer.from("0000", "hex")).toString("hex")).toBe("020100");
218
+ expect(derInt(3).toString("hex")).toBe("020103");
219
+ });
220
+ });