@intentius/chant 0.124.85 → 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.
- package/dist/bundle-check.d.ts +102 -0
- package/dist/bundle-check.d.ts.map +1 -0
- package/dist/bundle-check.js +310 -0
- package/dist/chant-install.d.ts +100 -0
- package/dist/chant-install.d.ts.map +1 -0
- package/dist/chant-install.js +158 -0
- package/dist/ci-commit.d.ts +19 -6
- package/dist/ci-commit.d.ts.map +1 -1
- package/dist/ci-commit.js +23 -4
- package/dist/ci-evidence-jobs.d.ts +78 -0
- package/dist/ci-evidence-jobs.d.ts.map +1 -0
- package/dist/ci-evidence-jobs.js +85 -0
- package/dist/ci-image.d.ts +274 -0
- package/dist/ci-image.d.ts.map +1 -0
- package/dist/ci-image.js +635 -0
- package/dist/ci-login.d.ts +150 -0
- package/dist/ci-login.d.ts.map +1 -0
- package/dist/ci-login.js +240 -0
- package/dist/ci-product.d.ts +16 -0
- package/dist/ci-product.d.ts.map +1 -1
- package/dist/ci-product.js +17 -0
- package/dist/cli/commands/import-index.js +2 -2
- package/dist/cli/handlers/build.d.ts +8 -0
- package/dist/cli/handlers/build.d.ts.map +1 -1
- package/dist/cli/handlers/build.js +22 -4
- package/dist/cli/handlers/ci-check.d.ts.map +1 -1
- package/dist/cli/handlers/ci-check.js +61 -2
- package/dist/cli/handlers/ci-evidence.d.ts +3 -0
- package/dist/cli/handlers/ci-evidence.d.ts.map +1 -0
- package/dist/cli/handlers/ci-evidence.js +174 -0
- package/dist/cli/handlers/components.js +3 -3
- package/dist/cli/handlers/dead-guards.d.ts +3 -0
- package/dist/cli/handlers/dead-guards.d.ts.map +1 -0
- package/dist/cli/handlers/dead-guards.js +35 -0
- package/dist/cli/handlers/graph.js +4 -4
- package/dist/cli/handlers/lifecycle.d.ts +2 -1
- package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
- package/dist/cli/handlers/lifecycle.js +5 -4
- package/dist/cli/handlers/local-chant.d.ts +16 -0
- package/dist/cli/handlers/local-chant.d.ts.map +1 -0
- package/dist/cli/handlers/local-chant.js +109 -0
- package/dist/cli/handlers/operator.js +2 -2
- package/dist/cli/handlers/search.js +5 -5
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +38 -0
- package/dist/cli/parse-args.d.ts.map +1 -1
- package/dist/cli/parse-args.js +28 -0
- package/dist/cli/registry.d.ts +16 -0
- package/dist/cli/registry.d.ts.map +1 -1
- package/dist/components/check-hooks.d.ts +49 -0
- package/dist/components/check-hooks.d.ts.map +1 -1
- package/dist/components/check-hooks.js +64 -4
- package/dist/components/check-steps.d.ts +17 -0
- package/dist/components/check-steps.d.ts.map +1 -1
- package/dist/components/check-steps.js +37 -5
- package/dist/components/product-pipeline.d.ts +23 -0
- package/dist/components/product-pipeline.d.ts.map +1 -1
- package/dist/components/product-pipeline.js +6 -2
- package/dist/components/product-plan.d.ts +143 -0
- package/dist/components/product-plan.d.ts.map +1 -0
- package/dist/components/product-plan.js +145 -0
- package/dist/components/release-compile.d.ts.map +1 -1
- package/dist/components/release-compile.js +2 -2
- package/dist/config.d.ts +39 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +35 -3
- package/dist/dead-guards.d.ts +82 -0
- package/dist/dead-guards.d.ts.map +1 -0
- package/dist/dead-guards.js +436 -0
- package/dist/discovery/files.d.ts +3 -1
- package/dist/discovery/files.d.ts.map +1 -1
- package/dist/discovery/files.js +5 -3
- package/dist/drift-issue.d.ts +152 -0
- package/dist/drift-issue.d.ts.map +1 -0
- package/dist/drift-issue.js +167 -0
- package/dist/floor-table.d.ts +30 -0
- package/dist/floor-table.d.ts.map +1 -0
- package/dist/floor-table.data.d.ts +3 -0
- package/dist/floor-table.data.d.ts.map +1 -0
- package/dist/floor-table.data.js +179 -0
- package/dist/floor-table.js +56 -0
- package/dist/forge-flags.d.ts +90 -0
- package/dist/forge-flags.d.ts.map +1 -0
- package/dist/forge-flags.js +184 -0
- package/dist/lexicon.d.ts +69 -0
- package/dist/lexicon.d.ts.map +1 -1
- package/dist/lifecycle/gated-op.d.ts +7 -1
- package/dist/lifecycle/gated-op.d.ts.map +1 -1
- package/dist/lifecycle/gated-op.js +7 -4
- package/dist/local-chant.d.ts +98 -0
- package/dist/local-chant.d.ts.map +1 -0
- package/dist/local-chant.js +307 -0
- package/dist/op/activities/predict-behaviour.js +2 -2
- package/dist/op/op-waves-evidence-spec.d.ts +13 -0
- package/dist/op/op-waves-evidence-spec.d.ts.map +1 -0
- package/dist/op/op-waves-evidence-spec.js +21 -0
- package/dist/op/op-waves-evidence.d.ts +40 -0
- package/dist/op/op-waves-evidence.d.ts.map +1 -0
- package/dist/op/op-waves-evidence.js +58 -0
- package/dist/op/op-waves-run.d.ts +4 -0
- package/dist/op/op-waves-run.d.ts.map +1 -1
- package/dist/op/op-waves-run.js +24 -1
- package/dist/op/op-waves.d.ts +17 -1
- package/dist/op/op-waves.d.ts.map +1 -1
- package/dist/op/op-waves.js +23 -0
- package/dist/op/schedule-overdue.d.ts +41 -9
- package/dist/op/schedule-overdue.d.ts.map +1 -1
- package/dist/op/schedule-overdue.js +154 -25
- package/dist/plan-summary.d.ts +25 -0
- package/dist/plan-summary.d.ts.map +1 -1
- package/dist/plan-summary.js +31 -0
- package/dist/pr-plan-note.d.ts +35 -0
- package/dist/pr-plan-note.d.ts.map +1 -1
- package/dist/pr-plan-note.js +10 -0
- package/dist/pr-post.d.ts +23 -0
- package/dist/pr-post.d.ts.map +1 -1
- package/dist/pr-post.js +125 -3
- package/dist/release-floors.d.ts +33 -1
- package/dist/release-floors.d.ts.map +1 -1
- package/dist/release-floors.js +33 -1
- package/dist/state-migration.d.ts +24 -0
- package/dist/state-migration.d.ts.map +1 -1
- package/dist/state-migration.js +100 -5
- package/dist/wave-runtime.mjs +309 -302
- package/dist/workspace/ci-green.d.ts.map +1 -1
- package/dist/workspace/ci-green.js +4 -3
- package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
- package/dist/workspace/lexicon-outputs.js +21 -7
- package/dist/workspace/reason-codes.d.ts +3 -0
- package/dist/workspace/reason-codes.d.ts.map +1 -1
- package/dist/workspace/reason-codes.js +4 -0
- package/dist/workspace/ref-gate.schema.json +85 -0
- package/dist/workspace/search-contract.d.ts +1 -1
- package/dist/workspace/search-contract.d.ts.map +1 -1
- package/dist/workspace/trust/check-evidence-report.d.ts +58 -0
- package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
- package/dist/workspace/trust/check-evidence-report.js +109 -0
- package/dist/workspace/trust/check-evidence.d.ts +160 -0
- package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
- package/dist/workspace/trust/check-evidence.js +309 -0
- package/dist/workspace/trust/ci-tag-statement.d.ts +2 -2
- package/dist/workspace/trust/ci-tag-statement.d.ts.map +1 -1
- package/dist/workspace/trust/dsse.d.ts +40 -2
- package/dist/workspace/trust/dsse.d.ts.map +1 -1
- package/dist/workspace/trust/dsse.js +34 -2
- package/dist/workspace/trust/evidence.d.ts +2 -2
- package/dist/workspace/trust/evidence.d.ts.map +1 -1
- package/dist/workspace/trust/keyless-fixture.d.ts +41 -0
- package/dist/workspace/trust/keyless-fixture.d.ts.map +1 -0
- package/dist/workspace/trust/keyless-fixture.js +161 -0
- package/dist/workspace/trust/keyless.d.ts +202 -0
- package/dist/workspace/trust/keyless.d.ts.map +1 -0
- package/dist/workspace/trust/keyless.js +488 -0
- package/dist/workspace/trust/local-evidence.d.ts +123 -0
- package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
- package/dist/workspace/trust/local-evidence.js +259 -0
- package/dist/workspace/trust/op-run-statement.d.ts +2 -2
- package/dist/workspace/trust/op-run-statement.d.ts.map +1 -1
- package/dist/workspace/trust/policy.d.ts +140 -1
- package/dist/workspace/trust/policy.d.ts.map +1 -1
- package/dist/workspace/trust/policy.js +197 -3
- package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
- package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
- package/dist/workspace/trust/ref-gate-cli.js +234 -0
- package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
- package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
- package/dist/workspace/trust/ref-gate-fixture.js +97 -0
- package/dist/workspace/trust/ref-gate.d.ts +187 -0
- package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
- package/dist/workspace/trust/ref-gate.js +432 -0
- package/dist/workspace/trust/run-statement.d.ts +3 -3
- package/dist/workspace/trust/run-statement.d.ts.map +1 -1
- package/dist/workspace/trust/runner-identity.d.ts +56 -0
- package/dist/workspace/trust/runner-identity.d.ts.map +1 -0
- package/dist/workspace/trust/runner-identity.js +65 -0
- package/dist/workspace/trust/trust-files.d.ts.map +1 -1
- package/dist/workspace/trust/trust-files.js +25 -1
- package/package.json +1 -1
- package/src/bundle-check.test.ts +140 -0
- package/src/bundle-check.ts +352 -0
- package/src/chant-install.test.ts +112 -0
- package/src/chant-install.ts +179 -0
- package/src/ci-commit.test.ts +45 -0
- package/src/ci-commit.ts +38 -4
- package/src/ci-evidence-jobs.ts +105 -0
- package/src/ci-image.test.ts +506 -0
- package/src/ci-image.ts +822 -0
- package/src/ci-login.test.ts +235 -0
- package/src/ci-login.ts +307 -0
- package/src/ci-product.ts +18 -0
- package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
- package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
- package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
- package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
- package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
- package/src/cli/commands/import-index.ts +2 -2
- package/src/cli/handlers/build-source-dir.test.ts +64 -0
- package/src/cli/handlers/build.ts +21 -4
- package/src/cli/handlers/ci-check.ts +60 -3
- package/src/cli/handlers/ci-evidence.ts +167 -0
- package/src/cli/handlers/components.ts +3 -3
- package/src/cli/handlers/dead-guards.ts +37 -0
- package/src/cli/handlers/graph.ts +4 -4
- package/src/cli/handlers/lifecycle.ts +5 -4
- package/src/cli/handlers/local-chant.ts +106 -0
- package/src/cli/handlers/operator.ts +2 -2
- package/src/cli/handlers/search.ts +5 -5
- package/src/cli/main.test.ts +7 -0
- package/src/cli/main.ts +38 -0
- package/src/cli/parse-args.ts +21 -0
- package/src/cli/registry.ts +16 -0
- package/src/components/check-evidence-stage.test.ts +80 -0
- package/src/components/check-hooks.ts +84 -4
- package/src/components/check-local-evidence-stage.test.ts +141 -0
- package/src/components/check-steps.ts +56 -6
- package/src/components/product-pipeline.ts +28 -3
- package/src/components/product-plan.test.ts +87 -0
- package/src/components/product-plan.ts +230 -0
- package/src/components/release-compile.ts +2 -2
- package/src/config.ts +44 -3
- package/src/dead-guards.test.ts +206 -0
- package/src/dead-guards.ts +446 -0
- package/src/discovery/files.ts +5 -3
- package/src/drift-issue-bundle.test.ts +31 -0
- package/src/drift-issue.test.ts +206 -0
- package/src/drift-issue.ts +274 -0
- package/src/fit-note.test.ts +44 -0
- package/src/floor-table.data.ts +181 -0
- package/src/floor-table.ts +77 -0
- package/src/forge-flags.test.ts +110 -0
- package/src/forge-flags.ts +208 -0
- package/src/gate-decision-bundle.test.ts +1 -0
- package/src/lexicon.ts +68 -0
- package/src/lifecycle/gated-op.ts +10 -5
- package/src/local-chant.e2e.test.ts +94 -0
- package/src/local-chant.test.ts +162 -0
- package/src/local-chant.ts +341 -0
- package/src/op/activities/predict-behaviour.ts +2 -2
- package/src/op/op-waves-evidence-spec.ts +24 -0
- package/src/op/op-waves-evidence.test.ts +130 -0
- package/src/op/op-waves-evidence.ts +58 -0
- package/src/op/op-waves-run.ts +25 -1
- package/src/op/op-waves.ts +31 -1
- package/src/op/schedule-overdue.test.ts +85 -0
- package/src/op/schedule-overdue.ts +162 -26
- package/src/plan-summary.ts +40 -0
- package/src/pr-plan-note.ts +34 -0
- package/src/pr-post-plan-note.test.ts +146 -0
- package/src/pr-post.ts +127 -3
- package/src/release-floors.ts +47 -1
- package/src/stage-hooks-bundle.test.ts +1 -0
- package/src/state-migration.test.ts +52 -1
- package/src/state-migration.ts +107 -5
- package/src/workspace/ci-green.ts +4 -3
- package/src/workspace/lexicon-outputs.ts +23 -6
- package/src/workspace/reason-codes.test.ts +3 -0
- package/src/workspace/reason-codes.ts +4 -0
- package/src/workspace/ref-gate.schema.json +85 -0
- package/src/workspace/trust/check-evidence-report.ts +115 -0
- package/src/workspace/trust/check-evidence.test.ts +133 -0
- package/src/workspace/trust/check-evidence.ts +327 -0
- package/src/workspace/trust/ci-tag-statement.ts +2 -2
- package/src/workspace/trust/dsse.ts +48 -4
- package/src/workspace/trust/evidence.ts +2 -2
- package/src/workspace/trust/keyless-fixture.ts +214 -0
- package/src/workspace/trust/keyless.test.ts +220 -0
- package/src/workspace/trust/keyless.ts +557 -0
- package/src/workspace/trust/local-evidence.test.ts +127 -0
- package/src/workspace/trust/local-evidence.ts +268 -0
- package/src/workspace/trust/op-run-statement.ts +2 -2
- package/src/workspace/trust/policy.ts +263 -3
- package/src/workspace/trust/ref-gate-cli.ts +244 -0
- package/src/workspace/trust/ref-gate-fixture.ts +125 -0
- package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
- package/src/workspace/trust/ref-gate.test.ts +247 -0
- package/src/workspace/trust/ref-gate.ts +539 -0
- package/src/workspace/trust/run-statement.ts +3 -3
- package/src/workspace/trust/runner-identity.ts +92 -0
- package/src/workspace/trust/trust-files.test.ts +22 -0
- package/src/workspace/trust/trust-files.ts +54 -1
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runner statements signed keyless from the CI job's OIDC identity (#4869).
|
|
3
|
+
*
|
|
4
|
+
* A runner key is a secret a project stores and rotates, and a leaked one
|
|
5
|
+
* signs anything until someone does. A keyless runner holds no key: the job
|
|
6
|
+
* trades its OIDC token for a short-lived certificate from a Fulcio
|
|
7
|
+
* certificate authority (sigstore's, or a private one), signs the DSSE
|
|
8
|
+
* envelope with a key it made for this run, and has the signature
|
|
9
|
+
* timestamped by an RFC 3161 timestamp authority. The envelope's signature
|
|
10
|
+
* then carries the certificate chain and the timestamp token:
|
|
11
|
+
*
|
|
12
|
+
* { keyid, sig, certificates: [<base64 DER>, ...], timestamp: <base64 DER> }
|
|
13
|
+
*
|
|
14
|
+
* `.chant/trust.json` at base lists which identities may sign
|
|
15
|
+
* (`keyless.identities`: an OIDC issuer and a subject pattern over the
|
|
16
|
+
* certificate's subject alternative name, which names the repository, the
|
|
17
|
+
* workflow file and the ref), and names the trusted root, a file in
|
|
18
|
+
* sigstore's `trusted_root.json` format holding the certificate
|
|
19
|
+
* authorities' and timestamp authorities' certificates. So verifying is
|
|
20
|
+
* offline: the chain is checked against the trusted root, the timestamp
|
|
21
|
+
* against the timestamp authorities, and the certificate's validity at the
|
|
22
|
+
* timestamp's time, never at the time of reading. A statement still
|
|
23
|
+
* verifies after its certificate expired.
|
|
24
|
+
*
|
|
25
|
+
* Nothing is sent to a transparency log.
|
|
26
|
+
*
|
|
27
|
+
* Every network call goes through an injected `fetch`, so the tests use a
|
|
28
|
+
* fake token, a fake certificate authority and a fake timestamp authority
|
|
29
|
+
* (./keyless-fixture.ts).
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { createHash, createPublicKey, generateKeyPairSync, sign, verify, X509Certificate, type KeyObject } from "node:crypto";
|
|
33
|
+
import { SIGNING_ID_TOKEN_VAR } from "./check-evidence-report";
|
|
34
|
+
|
|
35
|
+
// ── DER, as much as certificates and RFC 3161 need ──────────────────────────
|
|
36
|
+
|
|
37
|
+
/** One DER element: its tag, its whole encoding and its contents. */
|
|
38
|
+
export interface DerNode {
|
|
39
|
+
tag: number;
|
|
40
|
+
/** The whole element, tag and length included. */
|
|
41
|
+
raw: Buffer;
|
|
42
|
+
/** The contents. */
|
|
43
|
+
value: Buffer;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The element at `at` in `buf`. Throws on a truncated or indefinite-length element. */
|
|
47
|
+
export function derRead(buf: Buffer, at = 0): DerNode & { end: number } {
|
|
48
|
+
if (at + 2 > buf.length) throw new Error("truncated DER");
|
|
49
|
+
const tag = buf[at]!;
|
|
50
|
+
let len = buf[at + 1]!;
|
|
51
|
+
let head = 2;
|
|
52
|
+
if (len & 0x80) {
|
|
53
|
+
const n = len & 0x7f;
|
|
54
|
+
if (n === 0 || n > 4 || at + 2 + n > buf.length) throw new Error("unsupported DER length");
|
|
55
|
+
len = 0;
|
|
56
|
+
for (let i = 0; i < n; i++) len = len * 256 + buf[at + 2 + i]!;
|
|
57
|
+
head = 2 + n;
|
|
58
|
+
}
|
|
59
|
+
const end = at + head + len;
|
|
60
|
+
if (end > buf.length) throw new Error("truncated DER");
|
|
61
|
+
return { tag, raw: buf.subarray(at, end), value: buf.subarray(at + head, end), end };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The elements inside a constructed element. */
|
|
65
|
+
export function derChildren(node: DerNode): DerNode[] {
|
|
66
|
+
const out: DerNode[] = [];
|
|
67
|
+
let at = 0;
|
|
68
|
+
while (at < node.value.length) {
|
|
69
|
+
const c = derRead(node.value, at);
|
|
70
|
+
out.push(c);
|
|
71
|
+
at = c.end;
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A DER element of `tag` holding `parts`. */
|
|
77
|
+
export function der(tag: number, ...parts: Buffer[]): Buffer {
|
|
78
|
+
const body = Buffer.concat(parts);
|
|
79
|
+
const n = body.length;
|
|
80
|
+
const len = n < 0x80 ? Buffer.from([n]) : n < 0x100 ? Buffer.from([0x81, n]) : n < 0x10000 ? Buffer.from([0x82, n >> 8, n & 0xff]) : Buffer.from([0x83, n >> 16, (n >> 8) & 0xff, n & 0xff]);
|
|
81
|
+
return Buffer.concat([Buffer.from([tag]), len, body]);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const DER = { SEQUENCE: 0x30, SET: 0x31, INTEGER: 0x02, BIT_STRING: 0x03, OCTET_STRING: 0x04, NULL: 0x05, OID: 0x06, UTF8: 0x0c, BOOLEAN: 0x01, UTC_TIME: 0x17, GENERALIZED_TIME: 0x18 } as const;
|
|
85
|
+
|
|
86
|
+
/** An OBJECT IDENTIFIER's encoding. */
|
|
87
|
+
export function derOid(oid: string): Buffer {
|
|
88
|
+
const parts = oid.split(".").map(Number);
|
|
89
|
+
const bytes = [parts[0]! * 40 + parts[1]!];
|
|
90
|
+
for (const p of parts.slice(2)) {
|
|
91
|
+
const seven: number[] = [];
|
|
92
|
+
let v = p;
|
|
93
|
+
do {
|
|
94
|
+
seven.unshift(v & 0x7f);
|
|
95
|
+
v = Math.floor(v / 128);
|
|
96
|
+
} while (v > 0);
|
|
97
|
+
for (let i = 0; i < seven.length - 1; i++) seven[i]! |= 0x80;
|
|
98
|
+
bytes.push(...seven);
|
|
99
|
+
}
|
|
100
|
+
return der(DER.OID, Buffer.from(bytes));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The dotted form of an OBJECT IDENTIFIER's contents. */
|
|
104
|
+
export function oidOf(value: Buffer): string {
|
|
105
|
+
const out = [Math.floor(value[0]! / 40), value[0]! % 40];
|
|
106
|
+
let v = 0;
|
|
107
|
+
for (const b of value.subarray(1)) {
|
|
108
|
+
v = v * 128 + (b & 0x7f);
|
|
109
|
+
if (!(b & 0x80)) {
|
|
110
|
+
out.push(v);
|
|
111
|
+
v = 0;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return out.join(".");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A non-negative INTEGER, in DER's minimal form: a Buffer's leading zero
|
|
119
|
+
* bytes are dropped (OpenSSL refuses `00 3a ...` as a bad INTEGER), and one
|
|
120
|
+
* zero byte is put back only when the first byte left has its top bit set.
|
|
121
|
+
*/
|
|
122
|
+
export function derInt(n: number | bigint | Buffer): Buffer {
|
|
123
|
+
let hex = Buffer.isBuffer(n) ? "" : BigInt(n).toString(16);
|
|
124
|
+
if (hex.length % 2) hex = `0${hex}`;
|
|
125
|
+
let b = Buffer.isBuffer(n) ? n : Buffer.from(hex, "hex");
|
|
126
|
+
let start = 0;
|
|
127
|
+
while (start < b.length - 1 && b[start] === 0) start++;
|
|
128
|
+
b = b.subarray(start);
|
|
129
|
+
if (b.length === 0) b = Buffer.from([0]);
|
|
130
|
+
if (b[0]! & 0x80) b = Buffer.concat([Buffer.from([0]), b]);
|
|
131
|
+
return der(DER.INTEGER, b);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export const OID = {
|
|
135
|
+
sha256: "2.16.840.1.101.3.4.2.1",
|
|
136
|
+
sha384: "2.16.840.1.101.3.4.2.2",
|
|
137
|
+
sha512: "2.16.840.1.101.3.4.2.3",
|
|
138
|
+
signedData: "1.2.840.113549.1.7.2",
|
|
139
|
+
tstInfo: "1.2.840.113549.1.9.16.1.4",
|
|
140
|
+
contentType: "1.2.840.113549.1.9.3",
|
|
141
|
+
messageDigest: "1.2.840.113549.1.9.4",
|
|
142
|
+
/** Fulcio's OIDC issuer extension, v1 (raw string) and v2 (DER UTF8String). */
|
|
143
|
+
fulcioIssuerV1: "1.3.6.1.4.1.57264.1.1",
|
|
144
|
+
fulcioIssuerV2: "1.3.6.1.4.1.57264.1.8",
|
|
145
|
+
codeSigning: "1.3.6.1.5.5.7.3.3",
|
|
146
|
+
timeStamping: "1.3.6.1.5.5.7.3.8",
|
|
147
|
+
} as const;
|
|
148
|
+
|
|
149
|
+
const HASH_OF: Record<string, string> = { [OID.sha256]: "sha256", [OID.sha384]: "sha384", [OID.sha512]: "sha512" };
|
|
150
|
+
|
|
151
|
+
// ── The trusted root ─────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
/** A certificate authority or timestamp authority of the trusted root: its chain, and when it may be used. */
|
|
154
|
+
export interface KeylessAuthority {
|
|
155
|
+
certs: X509Certificate[];
|
|
156
|
+
start?: Date;
|
|
157
|
+
end?: Date;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What a keyless signature is verified against: sigstore's `trusted_root.json`, read at base. */
|
|
161
|
+
export interface KeylessRoots {
|
|
162
|
+
ca: KeylessAuthority[];
|
|
163
|
+
tsa: KeylessAuthority[];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function authorities(list: unknown, name: string): KeylessAuthority[] {
|
|
167
|
+
if (list === undefined) return [];
|
|
168
|
+
if (!Array.isArray(list)) throw new Error(`${name} is not a list`);
|
|
169
|
+
return list.map((a, i) => {
|
|
170
|
+
const raw = (a as { certChain?: { certificates?: Array<{ rawBytes?: unknown }> } })?.certChain?.certificates;
|
|
171
|
+
if (!Array.isArray(raw) || raw.length === 0) throw new Error(`${name}[${i}] has no certChain.certificates`);
|
|
172
|
+
const certs = raw.map((c, j) => {
|
|
173
|
+
if (typeof c?.rawBytes !== "string") throw new Error(`${name}[${i}].certChain.certificates[${j}] has no rawBytes`);
|
|
174
|
+
return new X509Certificate(Buffer.from(c.rawBytes, "base64"));
|
|
175
|
+
});
|
|
176
|
+
const valid = (a as { validFor?: { start?: unknown; end?: unknown } }).validFor;
|
|
177
|
+
return {
|
|
178
|
+
certs,
|
|
179
|
+
...(typeof valid?.start === "string" ? { start: new Date(valid.start) } : {}),
|
|
180
|
+
...(typeof valid?.end === "string" ? { end: new Date(valid.end) } : {}),
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The certificate and timestamp authorities of a `trusted_root.json`
|
|
187
|
+
* (`certificateAuthorities` and `timestampAuthorities`, each a `certChain`
|
|
188
|
+
* of base64 DER certificates and an optional `validFor`). Throws when the
|
|
189
|
+
* file is not one, or names no certificate authority.
|
|
190
|
+
*/
|
|
191
|
+
export function parseTrustedRoot(text: string): KeylessRoots {
|
|
192
|
+
const doc = JSON.parse(text) as { certificateAuthorities?: unknown; timestampAuthorities?: unknown };
|
|
193
|
+
const ca = authorities(doc.certificateAuthorities, "certificateAuthorities");
|
|
194
|
+
const tsa = authorities(doc.timestampAuthorities, "timestampAuthorities");
|
|
195
|
+
if (ca.length === 0) throw new Error("it lists no certificateAuthorities");
|
|
196
|
+
if (tsa.length === 0) throw new Error("it lists no timestampAuthorities, so no signature's time can be trusted");
|
|
197
|
+
return { ca, tsa };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ── Identities ───────────────────────────────────────────────────────────────
|
|
201
|
+
|
|
202
|
+
/** A CI identity `.chant/trust.json` lets sign runner statements keyless (#4869). */
|
|
203
|
+
export interface KeylessIdentity {
|
|
204
|
+
principal: string;
|
|
205
|
+
/** The OIDC issuer the certificate names, exactly. */
|
|
206
|
+
issuer: string;
|
|
207
|
+
/**
|
|
208
|
+
* A pattern over the certificate's subject alternative name, such as
|
|
209
|
+
* `https://github.com/acme/infra/.github/workflows/chant.yml@refs/heads/main`.
|
|
210
|
+
* `*` matches within one `/` segment, `**` across them.
|
|
211
|
+
*/
|
|
212
|
+
subject: string;
|
|
213
|
+
roots: KeylessRoots;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** A subject pattern as a regular expression: `**` any text, `*` any text without `/`. */
|
|
217
|
+
export function subjectPattern(pattern: string): RegExp {
|
|
218
|
+
const body = pattern
|
|
219
|
+
.split("**")
|
|
220
|
+
.map((part) => part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*"))
|
|
221
|
+
.join(".*");
|
|
222
|
+
return new RegExp(`^${body}$`);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** The URIs and emails of a certificate's subject alternative name. */
|
|
226
|
+
export function certificateSubjects(cert: X509Certificate): string[] {
|
|
227
|
+
const san = cert.subjectAltName ?? "";
|
|
228
|
+
return san
|
|
229
|
+
.split(/, (?=[A-Za-z ]+:)/)
|
|
230
|
+
.map((s) => s.match(/^(?:URI|email):(.*)$/)?.[1])
|
|
231
|
+
.filter((s): s is string => typeof s === "string" && s.length > 0)
|
|
232
|
+
.map((s) => (s.startsWith('"') && s.endsWith('"') ? (JSON.parse(s) as string) : s));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The extensions of a certificate, by OID: each one's OCTET STRING contents. */
|
|
236
|
+
function extensions(cert: X509Certificate): Map<string, Buffer> {
|
|
237
|
+
const out = new Map<string, Buffer>();
|
|
238
|
+
const tbs = derChildren(derRead(cert.raw))[0]!;
|
|
239
|
+
const wrapper = derChildren(tbs).find((c) => c.tag === 0xa3);
|
|
240
|
+
if (!wrapper) return out;
|
|
241
|
+
for (const ext of derChildren(derChildren(wrapper)[0]!)) {
|
|
242
|
+
const parts = derChildren(ext);
|
|
243
|
+
const value = parts[parts.length - 1]!;
|
|
244
|
+
out.set(oidOf(parts[0]!.value), value.value);
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** The OIDC issuer Fulcio wrote into the certificate, or undefined. */
|
|
250
|
+
export function certificateIssuer(cert: X509Certificate): string | undefined {
|
|
251
|
+
const ext = extensions(cert);
|
|
252
|
+
const v2 = ext.get(OID.fulcioIssuerV2);
|
|
253
|
+
if (v2) return derRead(v2).value.toString("utf8");
|
|
254
|
+
return ext.get(OID.fulcioIssuerV1)?.toString("utf8");
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ── Chains and timestamps ────────────────────────────────────────────────────
|
|
258
|
+
|
|
259
|
+
const within = (cert: X509Certificate, at: Date): boolean => new Date(cert.validFrom) <= at && at <= new Date(cert.validTo);
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Whether `leaf` chains, through `given` and the authorities' own
|
|
263
|
+
* certificates, to one of `authorities` whose `validFor` covers `at`, with
|
|
264
|
+
* every certificate on the way valid at `at`. Every certificate of an
|
|
265
|
+
* authority's chain is trusted, as sigstore's clients treat them.
|
|
266
|
+
*/
|
|
267
|
+
export function chainsTo(leaf: X509Certificate, given: readonly X509Certificate[], list: readonly KeylessAuthority[], at: Date): boolean {
|
|
268
|
+
for (const a of list) {
|
|
269
|
+
if ((a.start && at < a.start) || (a.end && at > a.end)) continue;
|
|
270
|
+
const anchors = new Set(a.certs.map((c) => c.fingerprint256));
|
|
271
|
+
const pool = [...given, ...a.certs];
|
|
272
|
+
let cur = leaf;
|
|
273
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
274
|
+
if (!within(cur, at)) break;
|
|
275
|
+
if (anchors.has(cur.fingerprint256)) return true;
|
|
276
|
+
const issuer = pool.find((p) => p.fingerprint256 !== cur.fingerprint256 && cur.checkIssued(p) && cur.verify(p.publicKey));
|
|
277
|
+
if (!issuer) break;
|
|
278
|
+
cur = issuer;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** A GeneralizedTime's contents as a Date: `YYYYMMDDHHMMSS[.fff]Z`. */
|
|
285
|
+
function generalizedTime(value: Buffer): Date {
|
|
286
|
+
const m = value.toString("ascii").match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d+)?Z$/);
|
|
287
|
+
if (!m) throw new Error("the timestamp's time is not a GeneralizedTime in UTC");
|
|
288
|
+
return new Date(Date.UTC(+m[1]!, +m[2]! - 1, +m[3]!, +m[4]!, +m[5]!, +m[6]!, m[7] ? Math.round(Number(m[7]) * 1000) : 0));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** What a timestamp token says, read without verifying. */
|
|
292
|
+
interface TimestampToken {
|
|
293
|
+
time: Date;
|
|
294
|
+
imprintHash: string;
|
|
295
|
+
imprint: Buffer;
|
|
296
|
+
eContent: Buffer;
|
|
297
|
+
digest: string;
|
|
298
|
+
signedAttrs: Buffer;
|
|
299
|
+
signature: Buffer;
|
|
300
|
+
certs: X509Certificate[];
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Read an RFC 3161 TimeStampToken (a CMS ContentInfo), or the TimeStampResp around one. */
|
|
304
|
+
function readTimestamp(bytes: Buffer): TimestampToken {
|
|
305
|
+
let top: DerNode = derRead(bytes);
|
|
306
|
+
let parts = derChildren(top);
|
|
307
|
+
// A TimeStampResp: status, then the token.
|
|
308
|
+
if (parts[0]?.tag === DER.SEQUENCE && parts[1]?.tag === DER.SEQUENCE) {
|
|
309
|
+
const status = derChildren(parts[0])[0];
|
|
310
|
+
if (!status || status.value.readUIntBE(0, status.value.length) > 1) throw new Error("the timestamp authority did not grant the timestamp");
|
|
311
|
+
top = parts[1];
|
|
312
|
+
parts = derChildren(top);
|
|
313
|
+
}
|
|
314
|
+
if (parts[0]?.tag !== DER.OID || oidOf(parts[0].value) !== OID.signedData) throw new Error("the timestamp is not CMS SignedData");
|
|
315
|
+
const signed = derChildren(derChildren(parts[1]!)[0]!);
|
|
316
|
+
const encap = derChildren(signed[2]!);
|
|
317
|
+
if (oidOf(encap[0]!.value) !== OID.tstInfo) throw new Error("the timestamp's content is not a TSTInfo");
|
|
318
|
+
const eContent = derChildren(encap[1]!)[0]!.value;
|
|
319
|
+
const tst = derChildren(derRead(eContent));
|
|
320
|
+
const imprint = derChildren(tst[2]!);
|
|
321
|
+
const imprintHash = HASH_OF[oidOf(derChildren(imprint[0]!)[0]!.value)];
|
|
322
|
+
if (!imprintHash) throw new Error("the timestamp's message imprint uses a hash chant does not read");
|
|
323
|
+
const time = generalizedTime(tst[4]!.value);
|
|
324
|
+
const certField = signed.find((c) => c.tag === 0xa0);
|
|
325
|
+
const certs = certField ? derChildren(certField).filter((c) => c.tag === DER.SEQUENCE).map((c) => new X509Certificate(c.raw)) : [];
|
|
326
|
+
const signerInfos = signed[signed.length - 1]!;
|
|
327
|
+
if (signerInfos.tag !== DER.SET) throw new Error("the timestamp has no signer");
|
|
328
|
+
const si = derChildren(derChildren(signerInfos)[0]!);
|
|
329
|
+
const digest = HASH_OF[oidOf(derChildren(si[2]!)[0]!.value)];
|
|
330
|
+
const attrs = si.find((c) => c.tag === 0xa0);
|
|
331
|
+
const signature = si.find((c, i) => i > 3 && c.tag === DER.OCTET_STRING);
|
|
332
|
+
if (!digest || !attrs || !signature) throw new Error("the timestamp's signer has no signed attributes or signature");
|
|
333
|
+
// The signature covers the attributes encoded as a SET, not as the [0] they are stored as.
|
|
334
|
+
const signedAttrs = Buffer.concat([Buffer.from([DER.SET]), attrs.raw.subarray(1)]);
|
|
335
|
+
const md = derChildren(attrs).find((a) => oidOf(derChildren(a)[0]!.value) === OID.messageDigest);
|
|
336
|
+
if (!md || !derChildren(derChildren(md)[1]!)[0]!.value.equals(createHash(digest).update(eContent).digest())) {
|
|
337
|
+
throw new Error("the timestamp's signed attributes do not match its TSTInfo");
|
|
338
|
+
}
|
|
339
|
+
return { time, imprintHash, imprint: imprint[1]!.value, eContent, digest, signedAttrs, signature: signature.value, certs };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const usableFor = (cert: X509Certificate, eku: string): boolean => !cert.keyUsage || cert.keyUsage.includes(eku);
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* The time a timestamp token vouches `signature` existed at, once the
|
|
346
|
+
* token's imprint is the signature's hash and a timestamp authority of
|
|
347
|
+
* `roots` signed it. Throws why not.
|
|
348
|
+
*/
|
|
349
|
+
export function verifyTimestamp(token: Buffer, signature: Buffer, roots: KeylessRoots): Date {
|
|
350
|
+
const t = readTimestamp(token);
|
|
351
|
+
if (!t.imprint.equals(createHash(t.imprintHash).update(signature).digest())) throw new Error("the timestamp is for another signature");
|
|
352
|
+
const candidates = [...t.certs, ...roots.tsa.flatMap((a) => a.certs)];
|
|
353
|
+
const signer = candidates.find((c) => {
|
|
354
|
+
try {
|
|
355
|
+
return verify(c.publicKey.asymmetricKeyType === "ed25519" ? null : t.digest, t.signedAttrs, c.publicKey, t.signature);
|
|
356
|
+
} catch {
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
if (!signer) throw new Error("no timestamp authority's certificate verifies the timestamp's signature");
|
|
361
|
+
if (!usableFor(signer, OID.timeStamping)) throw new Error("the timestamp was signed by a certificate not issued for timestamping");
|
|
362
|
+
if (!chainsTo(signer, t.certs, roots.tsa, t.time)) throw new Error("the timestamp's signer does not chain to a timestamp authority of the trusted root");
|
|
363
|
+
return t.time;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// ── Verify ───────────────────────────────────────────────────────────────────
|
|
367
|
+
|
|
368
|
+
/** A DSSE signature made keyless: the DSSE fields and the certificate chain and timestamp. */
|
|
369
|
+
export interface KeylessSignature {
|
|
370
|
+
keyid: string;
|
|
371
|
+
sig: string;
|
|
372
|
+
/** Base64 DER, the signing certificate first. */
|
|
373
|
+
certificates: string[];
|
|
374
|
+
/** Base64 DER RFC 3161 TimeStampToken over `sig`'s bytes. */
|
|
375
|
+
timestamp: string;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export function isKeylessSignature(s: unknown): s is KeylessSignature {
|
|
379
|
+
const k = s as Partial<KeylessSignature> | null;
|
|
380
|
+
return (
|
|
381
|
+
k !== null &&
|
|
382
|
+
typeof k === "object" &&
|
|
383
|
+
typeof k.sig === "string" &&
|
|
384
|
+
typeof k.timestamp === "string" &&
|
|
385
|
+
Array.isArray(k.certificates) &&
|
|
386
|
+
k.certificates.length > 0 &&
|
|
387
|
+
k.certificates.every((c) => typeof c === "string")
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The key id a keyless signature is given: its certificate's SHA-256 fingerprint. */
|
|
392
|
+
export function certificateKeyid(cert: X509Certificate): string {
|
|
393
|
+
return `x509:SHA256:${createHash("sha256").update(cert.raw).digest("base64").replace(/=+$/, "")}`;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export type KeylessVerdict =
|
|
397
|
+
| { ok: true; principal: string; keyid: string; issuer: string; subject: string; signedAt: string }
|
|
398
|
+
| { ok: false; named: boolean; reason: string };
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Verify one keyless signature over `message` (the envelope's PAE) against
|
|
402
|
+
* `identities`. The certificate must chain to the trusted root and be valid
|
|
403
|
+
* at the timestamp's time, the timestamp must verify, and the certificate's
|
|
404
|
+
* issuer and subject must match one identity, whose principal is returned.
|
|
405
|
+
*/
|
|
406
|
+
export function verifyKeylessSignature(message: Buffer, s: KeylessSignature, identities: readonly KeylessIdentity[]): KeylessVerdict {
|
|
407
|
+
if (identities.length === 0) return { ok: false, named: false, reason: "the policy at base lists no keyless identity" };
|
|
408
|
+
let leaf: X509Certificate;
|
|
409
|
+
let chain: X509Certificate[];
|
|
410
|
+
try {
|
|
411
|
+
[leaf, ...chain] = s.certificates.map((c) => new X509Certificate(Buffer.from(c, "base64"))) as [X509Certificate, ...X509Certificate[]];
|
|
412
|
+
} catch (err) {
|
|
413
|
+
return { ok: false, named: false, reason: `the signature's certificates do not parse: ${err instanceof Error ? err.message : String(err)}` };
|
|
414
|
+
}
|
|
415
|
+
const sig = Buffer.from(s.sig, "base64");
|
|
416
|
+
const pub = leaf.publicKey;
|
|
417
|
+
let good = false;
|
|
418
|
+
try {
|
|
419
|
+
good = verify(pub.asymmetricKeyType === "ed25519" ? null : "sha256", message, pub, sig);
|
|
420
|
+
} catch {
|
|
421
|
+
good = false;
|
|
422
|
+
}
|
|
423
|
+
if (!good) return { ok: false, named: false, reason: "the signature does not verify against its certificate's key" };
|
|
424
|
+
if (!usableFor(leaf, OID.codeSigning)) return { ok: false, named: false, reason: "the certificate was not issued for code signing" };
|
|
425
|
+
const issuer = certificateIssuer(leaf);
|
|
426
|
+
const subjects = certificateSubjects(leaf);
|
|
427
|
+
const said = `${issuer ?? "no issuer"} ${subjects.join(" ") || "no subject"}`;
|
|
428
|
+
const named = identities.filter((i) => i.issuer === issuer && subjects.some((s2) => subjectPattern(i.subject).test(s2)));
|
|
429
|
+
if (named.length === 0) return { ok: false, named: false, reason: `the certificate's identity (${said}) is not one the policy at base lists under keyless.identities` };
|
|
430
|
+
const problems: string[] = [];
|
|
431
|
+
for (const id of named) {
|
|
432
|
+
let at: Date;
|
|
433
|
+
try {
|
|
434
|
+
at = verifyTimestamp(Buffer.from(s.timestamp, "base64"), sig, id.roots);
|
|
435
|
+
} catch (err) {
|
|
436
|
+
problems.push(err instanceof Error ? err.message : String(err));
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (!chainsTo(leaf, chain, id.roots.ca, at)) {
|
|
440
|
+
problems.push(`the certificate does not chain to a certificate authority of the trusted root, valid at ${at.toISOString()}`);
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
const subject = subjects.find((s2) => subjectPattern(id.subject).test(s2))!;
|
|
444
|
+
return { ok: true, principal: id.principal, keyid: certificateKeyid(leaf), issuer: issuer!, subject, signedAt: at.toISOString() };
|
|
445
|
+
}
|
|
446
|
+
return { ok: false, named: true, reason: `the keyless signature by ${said} does not verify: ${[...new Set(problems)].join("; ")}` };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** The verifier a policy's identity carries (./dsse.ts's `TrustedIdentity.verifyKeyless`). */
|
|
450
|
+
export function keylessVerifier(identity: KeylessIdentity): (message: Buffer, signature: unknown) => KeylessVerdict {
|
|
451
|
+
return (message, signature) => (isKeylessSignature(signature) ? verifyKeylessSignature(message, signature, [identity]) : { ok: false, named: false, reason: "the signature is not keyless" });
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ── Sign ─────────────────────────────────────────────────────────────────────
|
|
455
|
+
|
|
456
|
+
/** The default certificate authority and timestamp authority: sigstore's public-good instances. */
|
|
457
|
+
export const DEFAULT_FULCIO_URL = "https://fulcio.sigstore.dev";
|
|
458
|
+
export const DEFAULT_TIMESTAMP_URL = "https://timestamp.sigstore.dev/api/v1/timestamp";
|
|
459
|
+
/** The audience the job's token is requested for, as Fulcio expects. */
|
|
460
|
+
export const DEFAULT_SIGNING_AUDIENCE = "sigstore";
|
|
461
|
+
|
|
462
|
+
export { SIGNING_ID_TOKEN_VAR };
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* The job's OIDC token for `audience`: GitLab's {@link SIGNING_ID_TOKEN_VAR},
|
|
466
|
+
* else the token request URL GitHub serves a job with `id-token: write`
|
|
467
|
+
* (and Forgejo 15 a job with `enable-openid-connect: true`), as the cloud
|
|
468
|
+
* login of ../../ci-login.ts takes it.
|
|
469
|
+
*/
|
|
470
|
+
export async function signingToken(env: NodeJS.ProcessEnv, audience: string, fetchFn: typeof fetch): Promise<string> {
|
|
471
|
+
const given = env[SIGNING_ID_TOKEN_VAR];
|
|
472
|
+
if (given) return given.trim();
|
|
473
|
+
const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
|
|
474
|
+
const bearer = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
|
|
475
|
+
if (!url || !bearer) {
|
|
476
|
+
throw new Error(
|
|
477
|
+
`the job has no OIDC token to sign with: GitLab needs id_tokens: ${SIGNING_ID_TOKEN_VAR}: aud: ${audience}; GitHub needs permissions: id-token: write; Forgejo 15 needs enable-openid-connect: true`,
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
const r = await fetchFn(`${url}${url.includes("?") ? "&" : "?"}audience=${encodeURIComponent(audience)}`, { headers: { authorization: `bearer ${bearer}`, accept: "application/json" } });
|
|
481
|
+
if (!r.ok) throw new Error(`the OIDC token request answered ${r.status}`);
|
|
482
|
+
const value = ((await r.json()) as { value?: unknown }).value;
|
|
483
|
+
if (typeof value !== "string" || !value) throw new Error("the OIDC token request answered no token");
|
|
484
|
+
return value;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** A JWT's claims, read without verifying: the certificate authority verifies the token. */
|
|
488
|
+
export function tokenClaims(token: string): Record<string, unknown> {
|
|
489
|
+
const part = token.split(".")[1];
|
|
490
|
+
if (!part) throw new Error("the OIDC token is not a JWT");
|
|
491
|
+
return JSON.parse(Buffer.from(part, "base64url").toString("utf8")) as Record<string, unknown>;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const pemToDer = (pem: string): Buffer => Buffer.from(pem.replace(/-----(BEGIN|END) CERTIFICATE-----/g, "").replace(/\s+/g, ""), "base64");
|
|
495
|
+
|
|
496
|
+
/** A signing certificate: the run's own key, and the chain Fulcio issued for it. */
|
|
497
|
+
export interface KeylessCertificate {
|
|
498
|
+
key: KeyObject;
|
|
499
|
+
/** Base64 DER, the signing certificate first. */
|
|
500
|
+
certificates: string[];
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Trade `token` for a certificate over a P-256 key made for this run, at
|
|
505
|
+
* Fulcio's `POST /api/v2/signingCert`. The proof of possession is the
|
|
506
|
+
* token's subject signed with that key.
|
|
507
|
+
*/
|
|
508
|
+
export async function requestCertificate(token: string, fulcioUrl: string, fetchFn: typeof fetch): Promise<KeylessCertificate> {
|
|
509
|
+
const sub = tokenClaims(token).sub;
|
|
510
|
+
if (typeof sub !== "string" || !sub) throw new Error("the OIDC token has no subject");
|
|
511
|
+
const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
512
|
+
const body = {
|
|
513
|
+
credentials: { oidcIdentityToken: token },
|
|
514
|
+
publicKeyRequest: {
|
|
515
|
+
publicKey: { algorithm: "ECDSA", content: publicKey.export({ format: "pem", type: "spki" }).toString() },
|
|
516
|
+
proofOfPossession: sign("sha256", Buffer.from(sub, "utf8"), privateKey).toString("base64"),
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
const r = await fetchFn(`${fulcioUrl.replace(/\/+$/, "")}/api/v2/signingCert`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body) });
|
|
520
|
+
if (!r.ok) throw new Error(`the certificate authority at ${fulcioUrl} answered ${r.status}: ${(await r.text()).slice(0, 200)}`);
|
|
521
|
+
const doc = (await r.json()) as Record<string, { chain?: { certificates?: unknown } } | undefined>;
|
|
522
|
+
const pems = (doc.signedCertificateEmbeddedSct ?? doc.signedCertificateDetachedSct)?.chain?.certificates;
|
|
523
|
+
if (!Array.isArray(pems) || pems.length === 0 || !pems.every((p) => typeof p === "string")) throw new Error(`the certificate authority at ${fulcioUrl} answered no certificate chain`);
|
|
524
|
+
const certificates = (pems as string[]).map((p) => pemToDer(p).toString("base64"));
|
|
525
|
+
const leaf = new X509Certificate(Buffer.from(certificates[0]!, "base64"));
|
|
526
|
+
const spki = (k: KeyObject) => k.export({ format: "der", type: "spki" }) as Buffer;
|
|
527
|
+
if (!spki(leaf.publicKey).equals(spki(createPublicKey(privateKey)))) throw new Error("the certificate authority certified another key");
|
|
528
|
+
return { key: privateKey, certificates };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** An RFC 3161 TimeStampReq for the SHA-256 of `data`, asking for the authority's certificate. */
|
|
532
|
+
export function timestampRequest(data: Buffer): Buffer {
|
|
533
|
+
const digest = createHash("sha256").update(data).digest();
|
|
534
|
+
return der(DER.SEQUENCE, derInt(1), der(DER.SEQUENCE, der(DER.SEQUENCE, derOid(OID.sha256), der(DER.NULL)), der(DER.OCTET_STRING, digest)), derInt(BigInt(`0x${createHash("sha256").update(digest).update(String(Date.now())).digest("hex").slice(0, 15)}`)), der(DER.BOOLEAN, Buffer.from([0xff])));
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** The TimeStampToken from a TimeStampResp. */
|
|
538
|
+
function tokenOfResponse(resp: Buffer): Buffer {
|
|
539
|
+
const parts = derChildren(derRead(resp));
|
|
540
|
+
const status = parts[0] ? derChildren(parts[0])[0] : undefined;
|
|
541
|
+
if (!status || status.value.readUIntBE(0, status.value.length) > 1 || !parts[1]) throw new Error("the timestamp authority did not grant the timestamp");
|
|
542
|
+
return Buffer.from(parts[1].raw);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** A timestamp token over `signature` from the authority at `url`. */
|
|
546
|
+
export async function requestTimestamp(signature: Buffer, url: string, fetchFn: typeof fetch): Promise<Buffer> {
|
|
547
|
+
const r = await fetchFn(url, { method: "POST", headers: { "content-type": "application/timestamp-query", accept: "application/timestamp-reply" }, body: new Uint8Array(timestampRequest(signature)) });
|
|
548
|
+
if (!r.ok) throw new Error(`the timestamp authority at ${url} answered ${r.status}`);
|
|
549
|
+
return tokenOfResponse(Buffer.from(await r.arrayBuffer()));
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Sign `message` (an envelope's PAE) with `cert`'s key and have the signature timestamped. */
|
|
553
|
+
export async function keylessSignature(message: Buffer, cert: KeylessCertificate, timestampUrl: string, fetchFn: typeof fetch): Promise<KeylessSignature> {
|
|
554
|
+
const sig = sign("sha256", message, cert.key);
|
|
555
|
+
const timestamp = await requestTimestamp(sig, timestampUrl, fetchFn);
|
|
556
|
+
return { keyid: certificateKeyid(new X509Certificate(Buffer.from(cert.certificates[0]!, "base64"))), sig: sig.toString("base64"), certificates: cert.certificates, timestamp: timestamp.toString("base64") };
|
|
557
|
+
}
|