@freedomofpress/sigstore-browser 0.1.13 → 0.1.15

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 (60) hide show
  1. package/.github/workflows/conformance.yml +1 -1
  2. package/.github/workflows/publish.yml +1 -1
  3. package/README.md +20 -16
  4. package/dist/bundle.d.ts +2 -0
  5. package/dist/bundle.d.ts.map +1 -1
  6. package/dist/bundle.js +66 -1
  7. package/dist/bundle.js.map +1 -1
  8. package/dist/interfaces.d.ts +17 -2
  9. package/dist/interfaces.d.ts.map +1 -1
  10. package/dist/interfaces.js +14 -0
  11. package/dist/interfaces.js.map +1 -1
  12. package/dist/policy.d.ts +3 -3
  13. package/dist/policy.d.ts.map +1 -1
  14. package/dist/policy.js +4 -4
  15. package/dist/policy.js.map +1 -1
  16. package/dist/sigstore.d.ts +8 -8
  17. package/dist/sigstore.d.ts.map +1 -1
  18. package/dist/sigstore.js +159 -362
  19. package/dist/sigstore.js.map +1 -1
  20. package/dist/timestamp/tsa.d.ts +6 -2
  21. package/dist/timestamp/tsa.d.ts.map +1 -1
  22. package/dist/timestamp/tsa.js +15 -18
  23. package/dist/timestamp/tsa.js.map +1 -1
  24. package/dist/tlog/body.d.ts +3 -1
  25. package/dist/tlog/body.d.ts.map +1 -1
  26. package/dist/tlog/body.js +18 -5
  27. package/dist/tlog/body.js.map +1 -1
  28. package/dist/tlog/checkpoint.d.ts +2 -2
  29. package/dist/tlog/checkpoint.d.ts.map +1 -1
  30. package/dist/tlog/checkpoint.js +17 -95
  31. package/dist/tlog/checkpoint.js.map +1 -1
  32. package/dist/tlog/dsse.d.ts +3 -2
  33. package/dist/tlog/dsse.d.ts.map +1 -1
  34. package/dist/tlog/dsse.js +8 -5
  35. package/dist/tlog/dsse.js.map +1 -1
  36. package/dist/tlog/hashedrekord.d.ts +3 -2
  37. package/dist/tlog/hashedrekord.d.ts.map +1 -1
  38. package/dist/tlog/hashedrekord.js +8 -5
  39. package/dist/tlog/hashedrekord.js.map +1 -1
  40. package/dist/tlog/intoto.d.ts +3 -2
  41. package/dist/tlog/intoto.d.ts.map +1 -1
  42. package/dist/tlog/intoto.js +3 -1
  43. package/dist/tlog/intoto.js.map +1 -1
  44. package/package.json +2 -2
  45. package/src/bundle.ts +87 -0
  46. package/src/ed25519.browser.test.ts +76 -0
  47. package/src/index.browser.test.ts +46 -1
  48. package/src/interfaces.ts +29 -2
  49. package/src/policy.ts +5 -5
  50. package/src/security.browser.test.ts +249 -0
  51. package/src/sigstore.ts +191 -497
  52. package/src/timestamp/tsa.ts +29 -28
  53. package/src/tlog/body.ts +24 -5
  54. package/src/tlog/checkpoint.ts +22 -122
  55. package/src/tlog/dsse.ts +12 -6
  56. package/src/tlog/hashedrekord.ts +14 -8
  57. package/src/tlog/intoto.ts +5 -2
  58. package/src/verify.browser.test.ts +281 -0
  59. package/test/fixtures/rekor2.ts +14 -0
  60. package/test/fixtures/sigstore.ts +13 -0
package/dist/sigstore.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { base64ToUint8Array, ByteStream, canonicalize, importKey, stringToUint8Array, uint8ArrayEqual, Uint8ArrayToHex, Uint8ArrayToString, verifySignature, verifySignatureOverDigest, } from "@freedomofpress/crypto-browser";
2
2
  import { HashAlgorithms } from "./interfaces.js";
3
3
  import { CertificateChainVerifier, EXTENSION_OID_SCT, X509Certificate, X509SCTExtension, } from "./x509/index.js";
4
+ import { assertBundle } from "./bundle.js";
4
5
  import { preAuthEncoding } from "./dsse.js";
5
- import { SigstoreRoots, } from "./interfaces.js";
6
+ import { parseValidityPeriod, SigstoreRoots, } from "./interfaces.js";
6
7
  import { verifyMerkleInclusion } from "./tlog/merkle.js";
7
8
  import { verifyCheckpoint } from "./tlog/checkpoint.js";
8
9
  import { verifyTLogBody } from "./tlog/body.js";
@@ -10,6 +11,15 @@ import { verifyBundleTimestamp } from "./timestamp/tsa.js";
10
11
  import { TrustedRootProvider } from "./trust/tuf.js";
11
12
  import { AnyOf, AllOf, OIDCIssuer, OIDCIssuerV2, Identity } from "./policy.js";
12
13
  const MEDIA_TYPE_BASE = "application/vnd.dev.sigstore.bundle";
14
+ // Upper bounds on in-toto subjects and digests, matching sigstore-go.
15
+ const MAX_SUBJECTS = 1024;
16
+ const MAX_SUBJECT_DIGESTS = 32;
17
+ // Unknown operators can satisfy threshold one, but add no independence to named operators.
18
+ function countOperators(operators) {
19
+ if (operators.size === 0)
20
+ return 0;
21
+ return Math.max(1, operators.size - (operators.has("") ? 1 : 0));
22
+ }
13
23
  /**
14
24
  * Extract bundle version from mediaType string
15
25
  * Reference: https://github.com/sigstore/sigstore-go/blob/main/pkg/bundle/bundle.go#L159-L177
@@ -28,13 +38,12 @@ function getBundleVersion(mediaType) {
28
38
  const version = mediaType
29
39
  .replace(`${MEDIA_TYPE_BASE}.v`, "")
30
40
  .replace("+json", "");
31
- // Basic semver validation (major.minor or major.minor.patch)
32
- if (/^\d+\.\d+(\.\d+)?$/.test(version)) {
41
+ // Only the versions this verifier implements are accepted.
42
+ if (/^0\.[123]$/.test(version)) {
33
43
  return version;
34
44
  }
35
45
  }
36
- // Default to 0.1 for unknown formats
37
- return "0.1";
46
+ throw new Error(`Unsupported bundle media type: ${mediaType}`);
38
47
  }
39
48
  export class SigstoreVerifier {
40
49
  constructor(options = {}) {
@@ -45,48 +54,34 @@ export class SigstoreVerifier {
45
54
  ctlogThreshold: options.ctlogThreshold ?? 1,
46
55
  tsaThreshold: options.tsaThreshold ?? 0,
47
56
  };
48
- }
49
- async loadLog(frozenTimestamp, logs) {
50
- // Load the first Rekor transparency log key that's valid at the frozen timestamp
51
- // and store its log ID for verification. This matches sigstore-go's approach of
52
- // looking up the verifier by log ID (verify/tlog.go:80-83).
53
- for (const log of logs) {
54
- // if start date is not in the future, and if an end doesn't exist or is in the future
55
- if (frozenTimestamp > new Date(log.publicKey.validFor.start) &&
56
- (!log.publicKey.validFor.end ||
57
- new Date(log.publicKey.validFor.end) > frozenTimestamp)) {
58
- return {
59
- publicKey: await importKey(log.publicKey.keyDetails, log.publicKey.keyDetails, log.publicKey.rawBytes),
60
- logId: base64ToUint8Array(log.logId.keyId),
61
- };
57
+ for (const [name, threshold] of Object.entries(this.options)) {
58
+ if (!Number.isSafeInteger(threshold) || threshold < 0) {
59
+ throw new Error(`${name} must be a non-negative safe integer`);
62
60
  }
63
61
  }
64
- // Return undefined instead of throwing - some bundles don't need Rekor keys
65
- // (e.g., v0.3 bundles with inclusion proofs)
66
- return undefined;
67
62
  }
68
- async loadCTLogs(frozenTimestamp, ctlogs) {
69
- const result = [];
70
- for (const log of ctlogs) {
71
- const start = new Date(log.publicKey.validFor.start);
72
- const end = log.publicKey.validFor.end
73
- ? new Date(log.publicKey.validFor.end)
74
- : new Date('9999-12-31'); // No expiry means valid forever
75
- // Include logs that are valid (started before frozen timestamp)
76
- // We keep all logs, even expired ones, for historical verification
77
- if (start <= frozenTimestamp) {
78
- const publicKey = await importKey(log.publicKey.keyDetails, log.publicKey.keyDetails, log.publicKey.rawBytes);
79
- result.push({
80
- logID: base64ToUint8Array(log.logId.keyId),
81
- publicKey,
82
- validFor: { start, end },
83
- });
84
- }
85
- }
86
- if (result.length === 0) {
87
- throw new Error("Could not find any valid CT logs in sigstore root.");
88
- }
89
- return result;
63
+ // Loads every Rekor key; entries select theirs by log ID and SETs are checked against its validity window.
64
+ async loadLog(logs) {
65
+ return Promise.all(logs.map(async (log) => ({
66
+ publicKey: await importKey(log.publicKey.keyDetails, log.publicKey.keyDetails, log.publicKey.rawBytes),
67
+ logId: base64ToUint8Array(log.logId.keyId),
68
+ hashAlgorithm: log.hashAlgorithm,
69
+ // Empty means unknown; countOperators never adds it to the named operator count.
70
+ operator: log.operator || "",
71
+ validFor: parseValidityPeriod(log.publicKey.validFor),
72
+ })));
73
+ }
74
+ // Loads every CT log; SCTs select their log by ID and are checked against its validity window.
75
+ async loadCTLogs(ctlogs) {
76
+ if (ctlogs.length === 0) {
77
+ throw new Error("Could not find any CT logs in sigstore root.");
78
+ }
79
+ return Promise.all(ctlogs.map(async (log) => ({
80
+ logID: base64ToUint8Array(log.logId.keyId),
81
+ publicKey: await importKey(log.publicKey.keyDetails, log.publicKey.keyDetails, log.publicKey.rawBytes),
82
+ operator: log.operator || "",
83
+ validFor: parseValidityPeriod(log.publicKey.validFor),
84
+ })));
90
85
  }
91
86
  // Adapted from https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/key/certificate.ts#L22-L53
92
87
  // Verifies that the leaf certificate chains to a trusted CA and is valid at the given timestamp.
@@ -115,60 +110,24 @@ export class SigstoreVerifier {
115
110
  }
116
111
  throw new Error(`Failed to verify certificate chain: ${lastError?.message || 'No valid CAs found'}`);
117
112
  }
118
- // Load timestamp authorities that are valid at the frozen timestamp.
119
- // Unlike sigstore-js which doesn't pre-load TSAs (it passes raw TSA data to timestamp verification),
120
- // we parse and filter them at initialization time for consistency with how we handle CAs and other roots.
121
- loadTSA(frozenTimestamp, tsas) {
122
- if (!tsas || tsas.length === 0) {
123
- return [];
124
- }
125
- const result = [];
126
- for (const tsa of tsas) {
127
- const start = new Date(tsa.validFor.start);
128
- const end = tsa.validFor.end ? new Date(tsa.validFor.end) : new Date(8640000000000000);
129
- if (frozenTimestamp > start && frozenTimestamp < end) {
130
- const certChain = tsa.certChain.certificates.map(cert => X509Certificate.parse(base64ToUint8Array(cert.rawBytes)));
131
- if (certChain.length > 0) {
132
- result.push({
133
- certChain,
134
- validFor: { start, end },
135
- });
136
- }
137
- }
138
- }
139
- return result;
140
- }
141
- // Load certificate authorities (Fulcio CAs) that are valid at the frozen timestamp.
142
- // Similar to sigstore-js's filterCertAuthorities() in trust/filter.ts, but we also
143
- // parse the certificates at load time whereas sigstore-js keeps them in the trust material
144
- // and parses them during verification. This pre-loading approach is consistent with our
145
- // architecture of loading all trusted roots at initialization.
146
- loadCA(frozenTimestamp, cas) {
147
- const result = [];
148
- for (const ca of cas) {
149
- const start = new Date(ca.validFor.start);
150
- const end = ca.validFor.end ? new Date(ca.validFor.end) : new Date(8640000000000000);
151
- if (frozenTimestamp > start && frozenTimestamp < end) {
152
- const certChain = ca.certChain.certificates.map(cert => X509Certificate.parse(base64ToUint8Array(cert.rawBytes)));
153
- if (certChain.length > 0) {
154
- result.push({
155
- certChain,
156
- validFor: { start, end },
157
- });
158
- }
159
- }
160
- }
161
- return result;
113
+ // Loads every Fulcio CA; verifyCertificateChain() selects CAs by the observer timestamp.
114
+ loadCA(cas) {
115
+ return cas
116
+ .filter((ca) => ca.certChain.certificates.length > 0)
117
+ .map((ca) => ({
118
+ certChain: ca.certChain.certificates.map((cert) => X509Certificate.parse(base64ToUint8Array(cert.rawBytes))),
119
+ validFor: parseValidityPeriod(ca.validFor),
120
+ }));
162
121
  }
163
122
  async loadSigstoreRoot(rawRoot) {
164
- const frozenTimestamp = new Date();
165
- this.rawRoot = rawRoot;
166
- this.root = {
167
- rekor: await this.loadLog(frozenTimestamp, rawRoot[SigstoreRoots.tlogs]),
168
- ctlogs: await this.loadCTLogs(frozenTimestamp, rawRoot[SigstoreRoots.ctlogs]),
169
- certificateAuthorities: this.loadCA(frozenTimestamp, rawRoot[SigstoreRoots.certificateAuthorities]),
170
- timestampAuthorities: this.loadTSA(frozenTimestamp, rawRoot.timestampAuthorities),
123
+ rawRoot.timestampAuthorities?.forEach((authority) => parseValidityPeriod(authority.validFor));
124
+ const root = {
125
+ rekor: await this.loadLog(rawRoot[SigstoreRoots.tlogs]),
126
+ ctlogs: await this.loadCTLogs(rawRoot[SigstoreRoots.ctlogs]),
127
+ certificateAuthorities: this.loadCA(rawRoot[SigstoreRoots.certificateAuthorities]),
171
128
  };
129
+ this.rawRoot = rawRoot;
130
+ this.root = root;
172
131
  }
173
132
  /**
174
133
  * Load Sigstore trusted root via TUF
@@ -185,7 +144,7 @@ export class SigstoreVerifier {
185
144
  // Key differences:
186
145
  // - Adds duplicate SCT detection (not in reference)
187
146
  // - Inline CT log filtering by logID and validity period (reference uses filterTLogAuthorities)
188
- // - Returns array of verified SCT logIDs for threshold checking (matches reference behavior)
147
+ // - Returns the distinct operators of the logs whose SCTs verified, for threshold checking
189
148
  async verifySCT(cert, issuer, ctlogs) {
190
149
  let extSCT;
191
150
  // Verifying the SCT requires that we remove the SCT extension and
@@ -236,7 +195,7 @@ export class SigstoreVerifier {
236
195
  // Calculate and return the verification results for each SCT
237
196
  // Unlike sigstore-go which counts verified SCTs and checks threshold at the end,
238
197
  // sigstore-js throws immediately if any SCT fails verification
239
- const verifiedSCTs = [];
198
+ const operators = new Set();
240
199
  for (const sct of extSCT.signedCertificateTimestamps) {
241
200
  // Find the CT log that matches this SCT's log ID and is valid for the SCT datetime
242
201
  const validCTLogs = ctlogs.filter((log) => {
@@ -251,191 +210,81 @@ export class SigstoreVerifier {
251
210
  for (const log of validCTLogs) {
252
211
  try {
253
212
  if (await sct.verify(preCert.buffer, log.publicKey)) {
254
- return true;
213
+ return log;
255
214
  }
256
215
  }
257
216
  catch {
258
217
  // Continue trying other logs
259
218
  }
260
219
  }
261
- return false;
220
+ return undefined;
262
221
  })();
263
222
  if (!verified) {
264
223
  throw new Error("SCT verification failed");
265
224
  }
266
- verifiedSCTs.push(sct.logID);
225
+ operators.add(verified.operator);
267
226
  }
268
- return verifiedSCTs;
227
+ return operators;
228
+ }
229
+ // Verifies the signed entry timestamp and returns the integrated time it binds.
230
+ async verifySET(entry, promise, log) {
231
+ const integratedTime = Number(entry.integratedTime);
232
+ const integratedDate = new Date(integratedTime * 1000);
233
+ if (integratedDate < log.validFor.start || integratedDate > log.validFor.end) {
234
+ throw new Error("Rekor key was not valid at the integrated time.");
235
+ }
236
+ const signed = stringToUint8Array(canonicalize({
237
+ body: entry.canonicalizedBody,
238
+ integratedTime,
239
+ logIndex: Number(entry.logIndex),
240
+ logID: Uint8ArrayToHex(log.logId),
241
+ }));
242
+ if (!(await verifySignature(log.publicKey, signed, base64ToUint8Array(promise), log.hashAlgorithm))) {
243
+ throw new Error("Failed to verify the inclusion promise in the provided bundle.");
244
+ }
245
+ return integratedDate;
269
246
  }
270
- async verifyInclusionPromise(cert, bundle, rekor) {
247
+ // Fully verifies every entry from a trusted log and returns the SET-bound integrated times.
248
+ // Entries from unknown logs are ignored; the threshold counts distinct log operators that verified.
249
+ async verifyTlogEntries(cert, bundle, rekor) {
271
250
  const entries = bundle.verificationMaterial.tlogEntries;
272
- // Check that bundle has enough tlog entries to meet threshold
273
- if (entries.length < this.options.tlogThreshold) {
274
- throw new Error(`Not enough tlog entries: ${entries.length} < ${this.options.tlogThreshold}`);
275
- }
276
- // Prevent DoS via excessive entries and threshold bypass via duplicates
277
- // Matches sigstore-go limits (verify/tlog.go:46-57)
278
- const MAX_TLOG_ENTRIES = 32;
279
- if (entries.length > MAX_TLOG_ENTRIES) {
280
- throw new Error(`Too many tlog entries: ${entries.length} > ${MAX_TLOG_ENTRIES}`);
281
- }
282
- for (let i = 0; i < entries.length; i++) {
283
- for (let j = i + 1; j < entries.length; j++) {
284
- const iLogId = Uint8ArrayToHex(base64ToUint8Array(entries[i].logId.keyId));
285
- const jLogId = Uint8ArrayToHex(base64ToUint8Array(entries[j].logId.keyId));
286
- if (iLogId === jLogId && entries[i].logIndex === entries[j].logIndex) {
287
- throw new Error(`Duplicate tlog entry found: logID=${iLogId}, logIndex=${entries[i].logIndex}`);
288
- }
289
- }
290
- }
291
- const entry = entries[0];
292
- // Extract bundle version from mediaType
293
- // Reference: https://github.com/sigstore/sigstore-go/blob/main/pkg/bundle/bundle.go#L159-L177
294
- const bundleVersion = getBundleVersion(bundle.mediaType);
295
- const isV02OrLater = parseFloat(bundleVersion) >= 0.2;
296
- // Bundle v0.2+ requires an inclusion proof
297
- if (isV02OrLater && !entry.inclusionProof) {
298
- throw new Error("Bundle v0.2+ requires an inclusion proof.");
299
- }
300
- // For rekor2/v0.3 bundles with inclusion proofs, the inclusion promise is optional
301
- if (!entry.inclusionPromise?.signedEntryTimestamp) {
302
- // If there's no inclusion promise, there must be an inclusion proof
303
- if (!entry.inclusionProof) {
304
- throw new Error("Bundle must have either an inclusion promise or an inclusion proof.");
251
+ // Only v0.1 bundles may rely on an inclusion promise alone.
252
+ const requireProof = getBundleVersion(bundle.mediaType) !== "0.1";
253
+ const operators = new Set();
254
+ const integratedTimes = [];
255
+ for (const entry of entries) {
256
+ const logId = base64ToUint8Array(entry.logId.keyId);
257
+ const log = rekor.find((l) => uint8ArrayEqual(l.logId, logId));
258
+ if (!log)
259
+ continue;
260
+ const promise = entry.inclusionPromise?.signedEntryTimestamp;
261
+ if (!entry.inclusionProof && (requireProof || !promise)) {
262
+ throw new Error("Transparency log entry requires an inclusion proof.");
305
263
  }
306
- }
307
- else {
308
- // Verify the inclusion promise signature if present
309
- // For v0.3 bundles that have both inclusion promise and proof,
310
- // we can skip the promise verification if we don't have a Rekor key
311
- // and there's a valid inclusion proof
312
- if (!rekor && entry.inclusionProof) {
313
- // Skip promise verification if we have an inclusion proof
314
- // The inclusion proof will be verified later
264
+ if (promise) {
265
+ integratedTimes.push(await this.verifySET(entry, promise, log));
315
266
  }
316
- else {
317
- if (!rekor) {
318
- throw new Error("Rekor public key not found in trusted root");
319
- }
320
- // Verify the log ID matches (matches sigstore-go verify/tlog.go:80-83)
321
- const entryLogId = base64ToUint8Array(entry.logId.keyId);
322
- if (!uint8ArrayEqual(rekor.logId, entryLogId)) {
323
- throw new Error(`Rekor log ID mismatch: bundle uses ${Uint8ArrayToHex(entryLogId)} but loaded key is for ${Uint8ArrayToHex(rekor.logId)}`);
324
- }
325
- const signature = base64ToUint8Array(entry.inclusionPromise.signedEntryTimestamp);
326
- const keyId = Uint8ArrayToHex(entryLogId);
327
- const integratedTime = Number(entry.integratedTime);
328
- const signed = stringToUint8Array(canonicalize({
329
- body: entry.canonicalizedBody,
330
- integratedTime: integratedTime,
331
- logIndex: Number(entry.logIndex),
332
- logID: keyId,
333
- }));
334
- if (!(await verifySignature(rekor.publicKey, signed, signature))) {
335
- throw new Error("Failed to verify the inclusion promise in the provided bundle.");
336
- }
267
+ if (entry.inclusionProof) {
268
+ await verifyMerkleInclusion(entry);
269
+ await verifyCheckpoint(entry, log);
337
270
  }
338
- }
339
- // Validate integrated time and logged certificate
340
- // Note: Rekor v2 bundles don't have integrated time in the tlog entry
341
- if (entry.integratedTime) {
342
- const integratedTime = Number(entry.integratedTime);
343
- const integratedDate = new Date(integratedTime * 1000);
344
- if (!cert.validForDate(integratedDate)) {
271
+ if (entry.integratedTime && !cert.validForDate(new Date(Number(entry.integratedTime) * 1000))) {
345
272
  throw new Error("Artifact signing was logged outside of the certificate validity.");
346
273
  }
274
+ await verifyTLogBody(entry, bundle, cert);
275
+ operators.add(log.operator);
347
276
  }
348
- else {
349
- // Rekor v2 bundles (no integratedTime) require a timestamp for verification
350
- if (!bundle.verificationMaterial.timestampVerificationData) {
351
- throw new Error("Rekor v2 bundles require a timestamp for verification.");
352
- }
353
- }
354
- // Verify that the certificate in the log matches the signing certificate
355
- // The format depends on the entry type (hashedrekord vs dsse) and version
356
- const bodyJson = JSON.parse(Uint8ArrayToString(base64ToUint8Array(entry.canonicalizedBody)));
357
- if (bodyJson.kind === "hashedrekord") {
358
- let loggedCertContent;
359
- // Check for hashedRekordV002 structure (Rekor v2)
360
- if (bodyJson.spec.hashedRekordV002) {
361
- const verifier = bodyJson.spec.hashedRekordV002.signature.verifier;
362
- if (verifier?.x509Certificate) {
363
- loggedCertContent = verifier.x509Certificate.rawBytes;
364
- }
365
- }
366
- // Check for older hashedrekord structure
367
- else if (bodyJson.spec.signature?.publicKey) {
368
- loggedCertContent = bodyJson.spec.signature.publicKey.content;
369
- }
370
- if (loggedCertContent) {
371
- // For hashedrekord v0.0.1, publicKey.content is base64-encoded PEM
372
- // For hashedRekordV002, x509Certificate.rawBytes is base64-encoded DER
373
- let loggedCert;
374
- if (bodyJson.spec.hashedRekordV002) {
375
- loggedCert = X509Certificate.parse(base64ToUint8Array(loggedCertContent));
376
- }
377
- else {
378
- const pemString = Uint8ArrayToString(base64ToUint8Array(loggedCertContent));
379
- loggedCert = X509Certificate.parse(pemString);
380
- }
381
- if (!cert.equals(loggedCert)) {
382
- throw new Error("Certificate in Rekor log does not match the signing certificate.");
383
- }
384
- }
385
- }
386
- else if (bodyJson.kind === "dsse") {
387
- // DSSE v0.0.1: certificate is in spec.signatures[0].verifier (base64-encoded PEM)
388
- // https://github.com/sigstore/sigstore-go/blob/main/pkg/tlog/entry.go#L356-L357
389
- const verifierContent = bodyJson.spec.signatures?.[0]?.verifier;
390
- if (verifierContent) {
391
- const pemString = Uint8ArrayToString(base64ToUint8Array(verifierContent));
392
- const loggedCert = X509Certificate.parse(pemString);
393
- if (!cert.equals(loggedCert)) {
394
- throw new Error("Certificate in DSSE tlog entry does not match the signing certificate.");
395
- }
396
- }
397
- }
398
- else if (bodyJson.kind === "intoto") {
399
- // intoto v0.0.2: certificate is in spec.content.envelope.signatures[0].publicKey (base64-encoded PEM)
400
- // https://github.com/sigstore/sigstore-go/blob/main/pkg/tlog/entry.go#L360-L361
401
- const publicKeyContent = bodyJson.spec.content?.envelope?.signatures?.[0]?.publicKey;
402
- if (publicKeyContent) {
403
- const pemString = Uint8ArrayToString(base64ToUint8Array(publicKeyContent));
404
- const loggedCert = X509Certificate.parse(pemString);
405
- if (!cert.equals(loggedCert)) {
406
- throw new Error("Certificate in intoto tlog entry does not match the signing certificate.");
407
- }
408
- }
409
- }
410
- else {
411
- // Unknown entry type - this should not happen with standard Sigstore bundles
412
- throw new Error(`Unsupported tlog entry kind: ${bodyJson.kind}`);
277
+ const verifiedOperators = countOperators(operators);
278
+ if (verifiedOperators < this.options.tlogThreshold) {
279
+ throw new Error(`Not enough verified transparency logs: ${verifiedOperators} < ${this.options.tlogThreshold}`);
413
280
  }
414
- return true;
281
+ return integratedTimes;
415
282
  }
416
- async verifyInclusionProof(bundle) {
417
- if (!this.rawRoot) {
418
- throw new Error("Sigstore root is undefined");
419
- }
420
- if (bundle.verificationMaterial.tlogEntries.length < 1) {
421
- throw new Error("No transparency log entries found in bundle");
422
- }
423
- // Verify inclusion proof for ALL entries, not just the first one
424
- // Reference: https://github.com/sigstore/sigstore-go/blob/main/pkg/verify/tlog.go#L74-L127
425
- for (const entry of bundle.verificationMaterial.tlogEntries) {
426
- // Only verify if there's an inclusion proof (v0.3/rekor2 bundles)
427
- // v0.1 bundles use inclusion promises instead, verified in verifyInclusionPromise
428
- if (entry.inclusionProof) {
429
- await verifyMerkleInclusion(entry);
430
- if (entry.inclusionProof.checkpoint) {
431
- await verifyCheckpoint(entry, this.rawRoot.tlogs);
432
- }
433
- }
434
- }
435
- }
436
- async verifyArtifactPolicy(policy, bundle, data, isDigestOnly = false) {
437
- // Quick checks first: does the signing certificate have the correct identity?
438
- if (!this.root) {
283
+ // Shared checks: policy, transparency log, timestamps, chain at every observer time, SCTs.
284
+ // Returns the signing certificate and the bundle's signature.
285
+ async verifyBundle(bundle, policy) {
286
+ assertBundle(bundle);
287
+ if (!this.root || !this.rawRoot) {
439
288
  throw new Error("Sigstore root is undefined");
440
289
  }
441
290
  const cert = bundle.verificationMaterial.certificate ||
@@ -444,67 +293,49 @@ export class SigstoreVerifier {
444
293
  throw new Error("No certificate found in bundle");
445
294
  }
446
295
  const signingCert = X509Certificate.parse(base64ToUint8Array(cert.rawBytes));
447
- // Handle both regular bundles (messageSignature) and DSSE bundles (dsseEnvelope)
448
- let signature;
449
- if (bundle.messageSignature) {
450
- signature = base64ToUint8Array(bundle.messageSignature.signature);
296
+ const signature = base64ToUint8Array(bundle.messageSignature ? bundle.messageSignature.signature : bundle.dsseEnvelope.signatures[0].sig);
297
+ await policy.verify(signingCert);
298
+ // Observer timestamps come from SET-bound integrated times and verified RFC 3161 timestamps.
299
+ // Rekor v2 entries carry no integrated time, so they need a TSA timestamp to be anchored at all.
300
+ const integratedTimes = await this.verifyTlogEntries(signingCert, bundle, this.root.rekor);
301
+ const timestamps = await verifyBundleTimestamp(bundle.verificationMaterial.timestampVerificationData, signature, this.rawRoot.timestampAuthorities || []);
302
+ const tsaOperators = countOperators(new Set(timestamps.map((t) => t.operator)));
303
+ if (tsaOperators < this.options.tsaThreshold) {
304
+ throw new Error(`Not enough verified TSA operators: ${tsaOperators} < ${this.options.tsaThreshold}`);
305
+ }
306
+ const observerTimes = [...integratedTimes, ...timestamps.map((t) => t.signingTime)];
307
+ if (observerTimes.length === 0) {
308
+ throw new Error("No verified observer timestamp anchors the signature in time.");
309
+ }
310
+ // The CA window and the whole chain are checked at every observer time, never at the leaf's own notBefore.
311
+ let certPath = [];
312
+ for (const ts of observerTimes) {
313
+ certPath = await this.verifyCertificateChain(ts, signingCert, this.root.certificateAuthorities);
451
314
  }
452
- else if (bundle.dsseEnvelope) {
453
- if (!bundle.dsseEnvelope.signatures || bundle.dsseEnvelope.signatures.length === 0) {
454
- throw new Error("DSSE envelope has no signatures");
455
- }
456
- signature = base64ToUint8Array(bundle.dsseEnvelope.signatures[0].sig);
457
- }
458
- else {
459
- throw new Error("Bundle does not contain a message signature or DSSE envelope");
460
- }
461
- // # 1 Basic stuff: ceritificate policy validation
462
- policy.verify(signingCert);
463
- // # 2 Certificate validity - verify chain to trusted CA
464
- // Similar to sigstore-js key/index.ts:59-64 which calls verifyCertificateChain()
465
- // Returns the verified certificate path [leaf, intermediate(s), root]
466
- const certPath = await this.verifyCertificateChain(signingCert.notBefore, signingCert, this.root.certificateAuthorities);
467
- // # 3 To verify the SCT we need to build a preCert (because the cert was logged without the SCT)
468
- // https://github.com/sigstore/sigstore-js/packages/verify/src/key/sct.ts#L45
469
- // Similar to sigstore-js key/index.ts:67 which uses path[0] (leaf) and path[1] (issuer)
470
- // for SCT verification. Handle edge case where path has only one cert (self-signed root).
471
315
  const issuerCert = certPath.length > 1 ? certPath[1] : certPath[0];
472
- const verifiedSCTs = await this.verifySCT(signingCert, issuerCert, this.root.ctlogs);
473
- if (verifiedSCTs.length < this.options.ctlogThreshold) {
474
- throw new Error(`Not enough valid SCTs: found ${verifiedSCTs.length}, required ${this.options.ctlogThreshold}`);
475
- }
476
- // # 4 Rekor inclusion promise
477
- if (!(await this.verifyInclusionPromise(signingCert, bundle, this.root.rekor))) {
478
- throw new Error("Inclusion promise validation failed.");
316
+ const ctOperators = countOperators(await this.verifySCT(signingCert, issuerCert, this.root.ctlogs));
317
+ if (ctOperators < this.options.ctlogThreshold) {
318
+ throw new Error(`Not enough verified CT log operators: ${ctOperators} < ${this.options.ctlogThreshold}`);
479
319
  }
480
- // # 5 Rekor inclusion proof (Merkle tree verification)
481
- await this.verifyInclusionProof(bundle);
482
- // # 5.1 Rekor body verification - verify ALL entries (matches sigstore-js verifier.ts:147)
483
- for (const entry of bundle.verificationMaterial.tlogEntries) {
484
- await verifyTLogBody(entry, bundle);
485
- }
486
- // # 6 TSA Timestamp Verification
487
- // Verify all timestamps and enforce threshold
488
- // Reference: https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/verifier.ts#L101-L106
489
- const verifiedTimestamps = await verifyBundleTimestamp(bundle.verificationMaterial.timestampVerificationData, signature, this.rawRoot?.timestampAuthorities || []);
490
- if (verifiedTimestamps.length < this.options.tsaThreshold) {
491
- throw new Error(`Not enough verified TSA timestamps: ${verifiedTimestamps.length} < ${this.options.tsaThreshold}`);
492
- }
493
- // If we have verified timestamps, check certificate validity at each timestamp time
494
- for (const verifiedTimestamp of verifiedTimestamps) {
495
- if (!signingCert.validForDate(verifiedTimestamp)) {
496
- throw new Error("Certificate was not valid at the time of timestamping");
497
- }
320
+ return { signingCert, signature };
321
+ }
322
+ async verifyArtifactPolicy(policy, bundle, data, isDigestOnly = false) {
323
+ if (isDigestOnly && data.byteLength !== 32) {
324
+ throw new Error("SHA-256 digest must be exactly 32 bytes");
498
325
  }
326
+ const { signingCert, signature } = await this.verifyBundle(bundle, policy);
499
327
  // # 7 Revocation *skipping* not really a thing (unsurprisingly)
500
328
  // # 8 verify the signed data
501
329
  if (bundle.dsseEnvelope) {
502
- // For DSSE bundles, verify the signature over the PAE
330
+ // Only in-toto statements are understood; other payload types must not be read as one.
331
+ if (bundle.dsseEnvelope.payloadType !== "application/vnd.in-toto+json") {
332
+ throw new Error(`Unsupported DSSE payload type: ${bundle.dsseEnvelope.payloadType}`);
333
+ }
503
334
  const payloadBytes = base64ToUint8Array(bundle.dsseEnvelope.payload);
504
335
  const payload = JSON.parse(Uint8ArrayToString(payloadBytes));
505
336
  // Verify the artifact digest matches a subject in the in-toto statement
506
- if (!payload.subject || payload.subject.length === 0) {
507
- throw new Error("DSSE payload has no subject");
337
+ if (!Array.isArray(payload?.subject) || payload.subject.length === 0 || payload.subject.length > MAX_SUBJECTS) {
338
+ throw new Error(`DSSE payload must have between 1 and ${MAX_SUBJECTS} subjects`);
508
339
  }
509
340
  // Compute or extract the artifact digest
510
341
  let artifactDigest;
@@ -516,14 +347,14 @@ export class SigstoreVerifier {
516
347
  // data is the file content, compute the digest
517
348
  artifactDigest = Uint8ArrayToHex(new Uint8Array(await crypto.subtle.digest(HashAlgorithms.SHA256, data)));
518
349
  }
519
- // Find matching subject by scanning all subjects (not just [0])
520
- let matchedSubject = null;
350
+ // Every subject must carry a bounded digest map; any one of them may match the artifact.
351
+ let matchedSubject = false;
521
352
  for (const subject of payload.subject) {
522
- const subjectDigest = subject.digest?.["sha256"];
523
- if (subjectDigest && artifactDigest === subjectDigest.toLowerCase()) {
524
- matchedSubject = subject;
525
- break;
353
+ const digests = subject?.digest;
354
+ if (!digests || typeof digests !== "object" || Array.isArray(digests) || Object.keys(digests).length > MAX_SUBJECT_DIGESTS) {
355
+ throw new Error(`Invalid DSSE subject digest map (maximum ${MAX_SUBJECT_DIGESTS} digests)`);
526
356
  }
357
+ matchedSubject || (matchedSubject = typeof digests.sha256 === "string" && artifactDigest === digests.sha256.toLowerCase());
527
358
  }
528
359
  if (!matchedSubject) {
529
360
  throw new Error(`Artifact digest ${artifactDigest} does not match any subject in DSSE payload`);
@@ -537,6 +368,14 @@ export class SigstoreVerifier {
537
368
  }
538
369
  }
539
370
  else {
371
+ // The bundle's message digest must be the digest of the artifact being verified.
372
+ const { messageDigest } = bundle.messageSignature;
373
+ const digest = isDigestOnly
374
+ ? data
375
+ : new Uint8Array(await crypto.subtle.digest(HashAlgorithms.SHA256, data));
376
+ if (messageDigest.algorithm !== "SHA2_256" || !uint8ArrayEqual(digest, base64ToUint8Array(messageDigest.digest))) {
377
+ throw new Error("Artifact digest does not match the bundle message digest");
378
+ }
540
379
  const publicKey = await signingCert.publicKeyObj;
541
380
  if (isDigestOnly) {
542
381
  // For hashedrekord bundles, verify signature over the digest directly.
@@ -583,50 +422,10 @@ export class SigstoreVerifier {
583
422
  * @returns The payload type and payload bytes from the verified envelope
584
423
  */
585
424
  async verifyDsse(bundle, policy) {
586
- if (!this.root) {
587
- throw new Error("Sigstore root is undefined");
588
- }
425
+ const { signingCert, signature } = await this.verifyBundle(bundle, policy);
589
426
  if (!bundle.dsseEnvelope) {
590
427
  throw new Error("Bundle does not contain a DSSE envelope");
591
428
  }
592
- // Extract certificate from bundle
593
- const cert = bundle.verificationMaterial.certificate ||
594
- bundle.verificationMaterial.x509CertificateChain?.certificates[0];
595
- if (!cert) {
596
- throw new Error("No certificate found in bundle");
597
- }
598
- const signingCert = X509Certificate.parse(base64ToUint8Array(cert.rawBytes));
599
- // (1) Verify certificate chain to trusted CA
600
- const certPath = await this.verifyCertificateChain(signingCert.notBefore, signingCert, this.root.certificateAuthorities);
601
- // (2) Verify SCTs
602
- const issuerCert = certPath.length > 1 ? certPath[1] : certPath[0];
603
- const verifiedSCTs = await this.verifySCT(signingCert, issuerCert, this.root.ctlogs);
604
- if (verifiedSCTs.length < this.options.ctlogThreshold) {
605
- throw new Error(`Not enough valid SCTs: found ${verifiedSCTs.length}, required ${this.options.ctlogThreshold}`);
606
- }
607
- // (3) Verify the signing certificate against the policy
608
- policy.verify(signingCert);
609
- // (4) Verify Rekor inclusion promise
610
- if (!(await this.verifyInclusionPromise(signingCert, bundle, this.root.rekor))) {
611
- throw new Error("Inclusion promise validation failed");
612
- }
613
- // (5) Verify Rekor inclusion proof (Merkle tree verification)
614
- await this.verifyInclusionProof(bundle);
615
- // Validate envelope has exactly one signature (matches sigstore-python dsse._verify)
616
- if (!bundle.dsseEnvelope.signatures || bundle.dsseEnvelope.signatures.length !== 1) {
617
- throw new Error(`DSSE envelope must have exactly 1 signature, got ${bundle.dsseEnvelope.signatures?.length ?? 0}`);
618
- }
619
- // (6) TSA Timestamp verification
620
- const signature = base64ToUint8Array(bundle.dsseEnvelope.signatures[0].sig);
621
- const verifiedTimestamps = await verifyBundleTimestamp(bundle.verificationMaterial.timestampVerificationData, signature, this.rawRoot?.timestampAuthorities || []);
622
- if (verifiedTimestamps.length < this.options.tsaThreshold) {
623
- throw new Error(`Not enough verified TSA timestamps: ${verifiedTimestamps.length} < ${this.options.tsaThreshold}`);
624
- }
625
- for (const verifiedTimestamp of verifiedTimestamps) {
626
- if (!signingCert.validForDate(verifiedTimestamp)) {
627
- throw new Error("Certificate was not valid at the time of timestamping");
628
- }
629
- }
630
429
  // (7) Verify the DSSE envelope signature
631
430
  const payloadBytes = base64ToUint8Array(bundle.dsseEnvelope.payload);
632
431
  const pae = preAuthEncoding(bundle.dsseEnvelope.payloadType, payloadBytes);
@@ -635,13 +434,11 @@ export class SigstoreVerifier {
635
434
  if (!verified) {
636
435
  throw new Error("DSSE signature verification failed");
637
436
  }
638
- // (8) Verify the consistency of the log entry's body against the bundle materials
639
- // The entry MUST be of type "dsse" for DSSE verification
437
+ // (8) Every entry MUST be of type "dsse" for DSSE verification
640
438
  for (const entry of bundle.verificationMaterial.tlogEntries) {
641
439
  if (entry.kindVersion.kind !== "dsse") {
642
440
  throw new Error(`Expected entry type dsse, got ${entry.kindVersion.kind}`);
643
441
  }
644
- await verifyTLogBody(entry, bundle);
645
442
  }
646
443
  // Return the verified payload
647
444
  return {