@crombolo/server 0.44.0 → 0.46.1

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.
@@ -0,0 +1,494 @@
1
+ /**
2
+ * Where a bundle was built (story 060): a Sigstore signature over the package,
3
+ * made in GitHub Actions from the commit or tag it was built at, kept in the
4
+ * package as `provenance.json` with links to the commit, the tag, the run and
5
+ * the transparency log. Optional: an unsigned bundle is still a bundle. One
6
+ * whose signature does not check out is always refused. `docs/bundles.md`,
7
+ * "Signing a bundle".
8
+ */
9
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { join, relative, sep } from 'node:path'
12
+ import { bundleFromJSON, type SerializedBundle } from '@sigstore/bundle'
13
+ import { X509Certificate } from '@sigstore/core'
14
+ import { TrustedRoot } from '@sigstore/protobuf-specs'
15
+ import { toSignedEntity, toTrustMaterial, Verifier } from '@sigstore/verify'
16
+
17
+ /** The file in a package that holds its signature, and the one file the digest leaves out. */
18
+ export const PROVENANCE_FILE = 'provenance.json'
19
+
20
+ /** What the signed statement says it is about. */
21
+ export const PROVENANCE_PREDICATE = 'https://crombolo.dev/bundle-provenance/v1'
22
+
23
+ const GITHUB_ISSUER = 'https://token.actions.githubusercontent.com'
24
+
25
+ /**
26
+ * Loaded by name: their type declarations need packages a site does not
27
+ * install, so a site that type-checks its own components would fail on them.
28
+ */
29
+ const SIGSTORE = 'sigstore'
30
+ const SIGSTORE_TUF = '@sigstore/tuf'
31
+ interface SigstoreModule {
32
+ attest(payload: Buffer, payloadType: string): Promise<SerializedBundle>
33
+ }
34
+ interface TufModule {
35
+ getTrustedRoot(options: { cachePath: string; forceCache?: boolean }): Promise<TrustedRoot>
36
+ }
37
+ const IN_TOTO = 'application/vnd.in-toto+json'
38
+
39
+ /** Fulcio's certificate extensions: what GitHub said about the job that signed. */
40
+ const OID = {
41
+ issuer: '1.3.6.1.4.1.57264.1.8',
42
+ workflow: '1.3.6.1.4.1.57264.1.9',
43
+ repository: '1.3.6.1.4.1.57264.1.12',
44
+ commit: '1.3.6.1.4.1.57264.1.13',
45
+ ref: '1.3.6.1.4.1.57264.1.14',
46
+ run: '1.3.6.1.4.1.57264.1.21',
47
+ } as const
48
+
49
+ /** Where a signed bundle was built, as its certificate says. */
50
+ export interface ProvenanceSource {
51
+ issuer: string
52
+ /** `owner/repo`. */
53
+ repository: string
54
+ /** `refs/tags/v1.2.0` or `refs/heads/main`, as it was when the bundle was signed. */
55
+ ref: string
56
+ commit: string
57
+ /** The workflow file and ref that signed it. */
58
+ workflow: string
59
+ run: string | null
60
+ }
61
+
62
+ export interface ProvenanceLinks {
63
+ commit: string
64
+ /** The tag's page, when the bundle was signed from a tag. */
65
+ tag: string | null
66
+ run: string | null
67
+ log: string | null
68
+ }
69
+
70
+ /** `provenance.json`. */
71
+ export interface ProvenanceFile {
72
+ format: 1
73
+ digest: string
74
+ signature: SerializedBundle
75
+ source: ProvenanceSource
76
+ links: ProvenanceLinks
77
+ }
78
+
79
+ /**
80
+ * `unchecked`: Sigstore's trusted root could not be had, so the signature was not
81
+ * checked either way (story 244). Refused like `invalid`, and worth trying again.
82
+ */
83
+ export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' | 'local'
84
+
85
+ export interface ProvenanceResult {
86
+ state: ProvenanceState
87
+ digest?: string
88
+ source?: ProvenanceSource
89
+ links?: ProvenanceLinks
90
+ /** Why a signature was not accepted, in words a person can act on. */
91
+ reason?: string
92
+ }
93
+
94
+ /** Every file a package's digest covers: all of it but its signature, installs and history. */
95
+ function packageFiles(dir: string): string[] {
96
+ const out: string[] = []
97
+ const walk = (at: string) => {
98
+ for (const name of readdirSync(at)) {
99
+ if (name === 'node_modules' || name === '.git') continue
100
+ const path = join(at, name)
101
+ if (statSync(path).isDirectory()) walk(path)
102
+ else out.push(relative(dir, path).split(sep).join('/'))
103
+ }
104
+ }
105
+ walk(dir)
106
+ // By code unit, not locale: the digest has to be the same on every machine.
107
+ return out.filter((path) => path !== PROVENANCE_FILE).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
108
+ }
109
+
110
+ /**
111
+ * The package digest: SHA-256 over every file but `provenance.json`, in path
112
+ * order, as `bundleIntegrity` hashes a payload. It covers what a bundle's own
113
+ * integrity does not: `package.json` and an extension bundle's code.
114
+ */
115
+ export function packageDigest(dir: string): string {
116
+ const hasher = new Bun.CryptoHasher('sha256')
117
+ for (const path of packageFiles(dir)) {
118
+ hasher.update(path)
119
+ hasher.update('\0')
120
+ hasher.update(readFileSync(join(dir, path)))
121
+ hasher.update('\n')
122
+ }
123
+ return `sha256-${hasher.digest('hex')}`
124
+ }
125
+
126
+ const hexOf = (digest: string) => digest.replace(/^sha256-/, '')
127
+
128
+ /** The statement signed: the digest alone, so the public log learns nothing of the bundle but it. */
129
+ function statement(digest: string): Buffer {
130
+ return Buffer.from(
131
+ JSON.stringify({
132
+ _type: 'https://in-toto.io/Statement/v1',
133
+ subject: [{ name: 'crombolo-bundle', digest: { sha256: hexOf(digest) } }],
134
+ predicateType: PROVENANCE_PREDICATE,
135
+ predicate: { format: 1 },
136
+ }),
137
+ )
138
+ }
139
+
140
+ function extensionText(cert: X509Certificate, oid: string): string | undefined {
141
+ const extension = cert.extension(oid)
142
+ return extension?.valueObj.subs?.[0]?.value.toString('utf8')
143
+ }
144
+
145
+ const leafOf = (bundle: SerializedBundle): X509Certificate | undefined => {
146
+ const material = bundle.verificationMaterial as Record<string, unknown>
147
+ const raw =
148
+ (material.certificate as { rawBytes?: string } | undefined)?.rawBytes ??
149
+ (material.x509CertificateChain as { certificates?: Array<{ rawBytes: string }> } | undefined)
150
+ ?.certificates?.[0]?.rawBytes
151
+ return raw ? X509Certificate.parse(Buffer.from(raw, 'base64')) : undefined
152
+ }
153
+
154
+ /** What the certificate says about the job that signed; undefined when it is not one. */
155
+ export function sourceOf(bundle: SerializedBundle): ProvenanceSource | undefined {
156
+ const cert = leafOf(bundle)
157
+ if (!cert) return undefined
158
+ const repositoryUri = extensionText(cert, OID.repository)
159
+ const commit = extensionText(cert, OID.commit)
160
+ const ref = extensionText(cert, OID.ref)
161
+ if (!repositoryUri || !commit || !ref) return undefined
162
+ return {
163
+ issuer: extensionText(cert, OID.issuer) ?? '',
164
+ repository: repositoryUri.replace(/^https:\/\/github\.com\//, ''),
165
+ ref,
166
+ commit,
167
+ workflow: extensionText(cert, OID.workflow) ?? '',
168
+ run: extensionText(cert, OID.run) ?? null,
169
+ }
170
+ }
171
+
172
+ function linksFor(source: ProvenanceSource, bundle: SerializedBundle): ProvenanceLinks {
173
+ const repo = `https://github.com/${source.repository}`
174
+ const tag = source.ref.startsWith('refs/tags/') ? source.ref.slice('refs/tags/'.length) : null
175
+ const logIndex = (bundle.verificationMaterial as { tlogEntries?: Array<{ logIndex?: string }> })
176
+ .tlogEntries?.[0]?.logIndex
177
+ return {
178
+ commit: `${repo}/commit/${source.commit}`,
179
+ tag: tag ? `${repo}/releases/tag/${encodeURIComponent(tag)}` : null,
180
+ run: source.run,
181
+ log: logIndex ? `https://search.sigstore.dev/?logIndex=${logIndex}` : null,
182
+ }
183
+ }
184
+
185
+ /** The ref as a person names it: `v1.2.0`, or the branch. */
186
+ export const refName = (ref: string): string => ref.replace(/^refs\/(tags|heads)\//, '')
187
+
188
+ /** One line for a person: where it was built, or that it was not signed. */
189
+ export function describeProvenance(result: ProvenanceResult): string {
190
+ switch (result.state) {
191
+ case 'signed': {
192
+ const source = result.source as ProvenanceSource
193
+ return `Signed: built from github.com/${source.repository} at ${refName(source.ref)} (${source.commit.slice(0, 7)})`
194
+ }
195
+ case 'unsigned':
196
+ return 'Not signed'
197
+ case 'local':
198
+ return 'Local: from this machine, not a registry'
199
+ case 'invalid':
200
+ return `Signature not accepted: ${result.reason ?? 'it does not check out'}`
201
+ case 'unchecked':
202
+ return `Couldn't be checked right now: ${result.reason ?? 'try again'}`
203
+ }
204
+ }
205
+
206
+ export interface SignOptions {
207
+ /**
208
+ * Sign from a private or internal repository anyway. Sigstore's public log
209
+ * then records the repository's name, workflow, ref and commit for good.
210
+ */
211
+ publicLog?: boolean
212
+ }
213
+
214
+ /** The job's repository visibility, from the event GitHub Actions gives it; undefined when it does not say. */
215
+ export function repositoryVisibility(): 'public' | 'private' | 'internal' | undefined {
216
+ const path = Bun.env.GITHUB_EVENT_PATH
217
+ if (!path || !existsSync(path)) return undefined
218
+ try {
219
+ const repo = (
220
+ JSON.parse(readFileSync(path, 'utf8')) as {
221
+ repository?: { visibility?: unknown; private?: unknown }
222
+ }
223
+ ).repository
224
+ if (
225
+ repo?.visibility === 'public' ||
226
+ repo?.visibility === 'private' ||
227
+ repo?.visibility === 'internal'
228
+ )
229
+ return repo.visibility
230
+ if (typeof repo?.private === 'boolean') return repo.private ? 'private' : 'public'
231
+ } catch {}
232
+ return undefined
233
+ }
234
+
235
+ /**
236
+ * Signs a package directory in GitHub Actions, writing `provenance.json`. The
237
+ * job needs `id-token: write`; Sigstore turns its identity token into a
238
+ * short-lived certificate naming the repository, ref, commit and workflow.
239
+ */
240
+ export async function signPackage(dir: string, options: SignOptions = {}): Promise<ProvenanceFile> {
241
+ if (Bun.env.GITHUB_ACTIONS !== 'true' || !Bun.env.ACTIONS_ID_TOKEN_REQUEST_URL)
242
+ throw new Error(
243
+ 'A bundle is signed in GitHub Actions, by a job with `permissions: id-token: write`: run `crombolo bundle sign` there.',
244
+ )
245
+ const visibility = repositoryVisibility()
246
+ if (visibility !== 'public' && !options.publicLog)
247
+ throw new Error(
248
+ `${visibility === undefined ? 'GitHub Actions did not say whether this repository is public' : `This repository is ${visibility}`}: signing records its name, the workflow, the tag or branch and the commit in Sigstore's public log, for good. Pass --public-log to sign anyway.`,
249
+ )
250
+ const { attest } = (await import(SIGSTORE)) as SigstoreModule
251
+ const digest = packageDigest(dir)
252
+ const signature = await attest(statement(digest), IN_TOTO)
253
+ const source = sourceOf(signature)
254
+ if (!source) throw new Error('The signature Sigstore returned names no GitHub repository.')
255
+ const file: ProvenanceFile = {
256
+ format: 1,
257
+ digest,
258
+ signature,
259
+ source,
260
+ links: linksFor(source, signature),
261
+ }
262
+ writeFileSync(join(dir, PROVENANCE_FILE), `${JSON.stringify(file, null, 2)}\n`)
263
+ return file
264
+ }
265
+
266
+ export interface VerifyProvenanceOptions {
267
+ /** Sigstore's trusted root as JSON; the public one, refreshed through TUF, by default. */
268
+ trustedRoot?: unknown
269
+ }
270
+
271
+ /**
272
+ * Checks the Sigstore bundle itself, throwing when it does not verify. Only a
273
+ * test passes one, through `verifyProvenanceWith`: a signature in this format is
274
+ * made in GitHub Actions, never offline.
275
+ */
276
+ export type SignatureCheck = (signature: SerializedBundle) => void | Promise<void>
277
+
278
+ /** What a test replaces in `verifyProvenanceWith`; nothing a host is offered. */
279
+ export interface ProvenanceSeams {
280
+ verifySignature?: SignatureCheck
281
+ /** Stands in for fetching Sigstore's public trusted root. */
282
+ publicRoot?: () => Promise<TrustedRoot>
283
+ }
284
+
285
+ let publicRoot: { at: number; root: Promise<TrustedRoot> } | undefined
286
+ const ROOT_FOR_MS = 60 * 60_000
287
+
288
+ /** Sigstore's public trusted root, fetched through TUF at most hourly, falling back to its cache. */
289
+ function publicTrustedRoot(): Promise<TrustedRoot> {
290
+ if (!publicRoot || Date.now() - publicRoot.at > ROOT_FOR_MS) {
291
+ const cachePath = join(
292
+ Bun.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'),
293
+ 'crombolo',
294
+ 'sigstore',
295
+ )
296
+ const root = (import(SIGSTORE_TUF) as Promise<TufModule>).then(({ getTrustedRoot }) =>
297
+ getTrustedRoot({ cachePath }).catch(() => getTrustedRoot({ cachePath, forceCache: true })),
298
+ )
299
+ publicRoot = { at: Date.now(), root }
300
+ root.catch(() => {
301
+ publicRoot = undefined
302
+ })
303
+ }
304
+ return publicRoot.root
305
+ }
306
+
307
+ const invalid = (reason: string, digest?: string): ProvenanceResult => ({
308
+ state: 'invalid',
309
+ reason,
310
+ ...(digest ? { digest } : {}),
311
+ })
312
+
313
+ /**
314
+ * Checks a package directory's signature: its digest, Sigstore's signature and
315
+ * certificate against the trusted root, that GitHub Actions signed it, and that
316
+ * `provenance.json` claims what the certificate says. Unsigned when there is no
317
+ * `provenance.json`; invalid, with the reason, when anything disagrees;
318
+ * unchecked when the trusted root could not be fetched and none is cached.
319
+ */
320
+ export function verifyProvenance(
321
+ dir: string,
322
+ options: VerifyProvenanceOptions = {},
323
+ ): Promise<ProvenanceResult> {
324
+ return verifyProvenanceWith(dir, options)
325
+ }
326
+
327
+ /** `verifyProvenance`, with Sigstore's steps replaced: for tests only. */
328
+ export async function verifyProvenanceWith(
329
+ dir: string,
330
+ options: VerifyProvenanceOptions,
331
+ seams: ProvenanceSeams = {},
332
+ ): Promise<ProvenanceResult> {
333
+ const file = join(dir, PROVENANCE_FILE)
334
+ if (!existsSync(file)) return { state: 'unsigned' }
335
+ let provenance: ProvenanceFile
336
+ try {
337
+ provenance = JSON.parse(readFileSync(file, 'utf8')) as ProvenanceFile
338
+ } catch {
339
+ return invalid(`${PROVENANCE_FILE} is not JSON`)
340
+ }
341
+ if (provenance.format !== 1 || !provenance.signature)
342
+ return invalid(`${PROVENANCE_FILE} is not a format this release reads`)
343
+ const digest = packageDigest(dir)
344
+ if (provenance.digest !== digest)
345
+ return invalid('the bundle has changed since it was signed', digest)
346
+
347
+ let check = seams.verifySignature
348
+ if (!check) {
349
+ let root: TrustedRoot
350
+ try {
351
+ root =
352
+ options.trustedRoot !== undefined
353
+ ? TrustedRoot.fromJSON(options.trustedRoot)
354
+ : await (seams.publicRoot ?? publicTrustedRoot)()
355
+ } catch (error) {
356
+ return {
357
+ state: 'unchecked',
358
+ reason: `Sigstore's trusted root could not be fetched: ${error instanceof Error ? error.message : String(error)}`,
359
+ digest,
360
+ }
361
+ }
362
+ check = (signature) => {
363
+ new Verifier(toTrustMaterial(root)).verify(toSignedEntity(bundleFromJSON(signature)), {
364
+ extensions: { issuer: GITHUB_ISSUER },
365
+ })
366
+ }
367
+ }
368
+ let signed: Buffer
369
+ try {
370
+ await check(provenance.signature)
371
+ const envelope = (provenance.signature as { dsseEnvelope?: { payload: string } }).dsseEnvelope
372
+ if (!envelope) return invalid('the signature is not over a statement', digest)
373
+ signed = Buffer.from(envelope.payload, 'base64')
374
+ } catch (error) {
375
+ return invalid(
376
+ `the signature does not check out: ${error instanceof Error ? error.message : String(error)}`,
377
+ digest,
378
+ )
379
+ }
380
+ let subject: { digest?: { sha256?: string } } | undefined
381
+ let predicateType: unknown
382
+ try {
383
+ const parsed = JSON.parse(signed.toString('utf8')) as {
384
+ subject?: Array<{ digest?: { sha256?: string } }>
385
+ predicateType?: unknown
386
+ }
387
+ subject = parsed.subject?.[0]
388
+ predicateType = parsed.predicateType
389
+ } catch {
390
+ return invalid('the signed statement is not JSON', digest)
391
+ }
392
+ if (predicateType !== PROVENANCE_PREDICATE)
393
+ return invalid('the signature is not a Crombolo bundle signature', digest)
394
+ if (subject?.digest?.sha256 !== hexOf(digest))
395
+ return invalid('the signature is for a different bundle', digest)
396
+
397
+ const source = sourceOf(provenance.signature)
398
+ if (!source) return invalid('the certificate names no GitHub repository', digest)
399
+ const claimed = provenance.source
400
+ for (const key of ['repository', 'ref', 'commit'] as const)
401
+ if (claimed?.[key] !== source[key])
402
+ return invalid(
403
+ `${PROVENANCE_FILE} says ${key} ${claimed?.[key] ?? '(none)'}, and the certificate says ${source[key]}`,
404
+ digest,
405
+ )
406
+ return { state: 'signed', digest, source, links: linksFor(source, provenance.signature) }
407
+ }
408
+
409
+ export type SignaturePolicy = 'optional' | 'required'
410
+
411
+ export interface ProvenancePolicy {
412
+ signatures: SignaturePolicy
413
+ /** `org/*`, `org/repo` or `org/repo@<ref pattern>`; empty takes any source. */
414
+ sources: readonly string[]
415
+ }
416
+
417
+ /** Whether a signed bundle's source matches one entry of `CROMBOLO_BUNDLE_SOURCES`. */
418
+ export function sourceAllowed(source: ProvenanceSource, entry: string): boolean {
419
+ const [repoPattern, refPattern] = entry.split('@') as [string, string | undefined]
420
+ if (!new Bun.Glob(repoPattern.toLowerCase()).match(source.repository.toLowerCase())) return false
421
+ return refPattern === undefined || new Bun.Glob(refPattern).match(refName(source.ref))
422
+ }
423
+
424
+ /**
425
+ * Why the site will not take this bundle, or undefined when it will. An
426
+ * invalid or unchecked signature is refused whatever the policy; `local` is the
427
+ * site's own.
428
+ */
429
+ export function provenanceProblem(
430
+ result: ProvenanceResult,
431
+ policy: ProvenancePolicy,
432
+ ): string | undefined {
433
+ if (result.state === 'invalid')
434
+ return `its signature was not accepted: ${result.reason ?? 'it does not check out'}`
435
+ if (result.state === 'unchecked')
436
+ return `its signature could not be checked right now (${result.reason ?? 'try again'}); try again`
437
+ if (result.state === 'local') return undefined
438
+ if (result.state === 'unsigned')
439
+ return policy.signatures === 'required'
440
+ ? 'this site takes only signed bundles (CROMBOLO_BUNDLE_SIGNATURES=required); the producer signs it with `crombolo bundle sign` in GitHub Actions'
441
+ : undefined
442
+ const source = result.source as ProvenanceSource
443
+ if (policy.sources.length > 0 && !policy.sources.some((entry) => sourceAllowed(source, entry)))
444
+ return `it was built from github.com/${source.repository} at ${refName(source.ref)}, and this site takes signed bundles only from ${policy.sources.join(', ')} (CROMBOLO_BUNDLE_SOURCES)`
445
+ return undefined
446
+ }
447
+
448
+ /** A `.tgz` unpacked into a temporary directory for `work`, which is removed afterwards. */
449
+ async function withUnpacked<T>(file: string, work: (dir: string) => Promise<T>): Promise<T> {
450
+ const { mkdtemp, rm } = await import('node:fs/promises')
451
+ const { tmpdir } = await import('node:os')
452
+ const { extractTarball } = await import('./tar.ts')
453
+ const dir = await mkdtemp(join(tmpdir(), 'crombolo-provenance-'))
454
+ try {
455
+ await extractTarball(file, dir)
456
+ return await work(dir)
457
+ } finally {
458
+ await rm(dir, { recursive: true, force: true })
459
+ }
460
+ }
461
+
462
+ export const isTarball = (path: string): boolean => /\.(tgz|tar\.gz)$/i.test(path)
463
+
464
+ /** The digest of a package directory or `.tgz`. */
465
+ export async function digestOf(path: string): Promise<string> {
466
+ return isTarball(path)
467
+ ? withUnpacked(path, async (dir) => packageDigest(dir))
468
+ : packageDigest(path)
469
+ }
470
+
471
+ /** Checks a package directory or `.tgz`. */
472
+ export async function verifyPackage(
473
+ path: string,
474
+ options: VerifyProvenanceOptions = {},
475
+ ): Promise<ProvenanceResult> {
476
+ return isTarball(path)
477
+ ? withUnpacked(path, (dir) => verifyProvenance(dir, options))
478
+ : verifyProvenance(path, options)
479
+ }
480
+
481
+ /** Signs a package directory, or a `.tgz` in place with `provenance.json` added to it. */
482
+ export async function signPath(path: string, options: SignOptions = {}): Promise<ProvenanceFile> {
483
+ if (!isTarball(path)) return signPackage(path, options)
484
+ const { writeNpmTarball } = await import('./tar.ts')
485
+ return withUnpacked(path, async (dir) => {
486
+ const signed = await signPackage(dir, options)
487
+ const entries = [...packageFiles(dir), PROVENANCE_FILE].map((file) => ({
488
+ path: file,
489
+ bytes: new Uint8Array(readFileSync(join(dir, file))),
490
+ }))
491
+ writeFileSync(path, writeNpmTarball(entries))
492
+ return signed
493
+ })
494
+ }