@tinfoilsh/verifier 2.0.0-rc.3 → 2.0.0-rc.5

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 (38) hide show
  1. package/README.md +48 -10
  2. package/dist/errors.d.ts +16 -8
  3. package/dist/errors.d.ts.map +1 -1
  4. package/dist/errors.js +11 -9
  5. package/dist/errors.js.map +1 -1
  6. package/dist/index.d.ts +6 -5
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +7 -6
  9. package/dist/index.js.map +1 -1
  10. package/dist/internal/endorsement/approval.js +1 -2
  11. package/dist/internal/endorsement/approval.js.map +1 -1
  12. package/dist/internal/quote/config.js +17 -4
  13. package/dist/internal/quote/config.js.map +1 -1
  14. package/dist/internal/quote/legacy.js +12 -11
  15. package/dist/internal/quote/legacy.js.map +1 -1
  16. package/dist/internal/quote/quote.js +56 -4
  17. package/dist/internal/quote/quote.js.map +1 -1
  18. package/dist/internal/quote/sev/expectations.js +13 -16
  19. package/dist/internal/quote/sev/expectations.js.map +1 -1
  20. package/dist/internal/runtime/config.js +11 -33
  21. package/dist/internal/runtime/config.js.map +1 -1
  22. package/dist/internal/sigstore/certificate.js +4 -4
  23. package/dist/internal/sigstore/certificate.js.map +1 -1
  24. package/dist/report.d.ts +203 -0
  25. package/dist/report.d.ts.map +1 -0
  26. package/dist/report.js +244 -0
  27. package/dist/report.js.map +1 -0
  28. package/dist/verification.d.ts +100 -36
  29. package/dist/verification.d.ts.map +1 -1
  30. package/dist/verification.js +91 -37
  31. package/dist/verification.js.map +1 -1
  32. package/dist/verifier.d.ts +128 -67
  33. package/dist/verifier.d.ts.map +1 -1
  34. package/dist/verifier.js +277 -139
  35. package/dist/verifier.js.map +1 -1
  36. package/dist/version.js +2 -2
  37. package/dist/version.js.map +1 -1
  38. package/package.json +2 -3
package/dist/verifier.js CHANGED
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Verifier_instances, _Verifier_policy, _Verifier_prov, _Verifier_configVerifier, _Verifier_freshnessVerifier, _Verifier_roots, _Verifier_requirePin, _Verifier_requiresConfigCollateral, _Verifier_codeReferences, _Verifier_witnessedAt, _Verifier_referencePins, _Verifier_configReferences, _Verifier_resolveConfig, _Verifier_resolveRuntime, _Verifier_resolvePlatform, _Verifier_approvedAt;
12
+ var _Verifier_instances, _Verifier_policy, _Verifier_prov, _Verifier_configVerifier, _Verifier_freshnessVerifier, _Verifier_roots, _Verifier_verify, _Verifier_requirePin, _Verifier_requiresConfigCollateral, _Verifier_codeReferences, _Verifier_witnessedAt, _Verifier_referencePins, _Verifier_configReferences, _Verifier_resolveConfig, _Verifier_resolveRuntime, _Verifier_resolvePlatform, _Verifier_approvedAt;
13
13
  /**
14
14
  * The v3 verifier: parses and binds a document, authenticates its reference
15
15
  * values, authenticates the CPU quote, assembles the expected state and
@@ -22,7 +22,7 @@ import { InvalidInputError, parse as parseDocument } from "./document/document.j
22
22
  import { UsageError, VerificationError, VerifyError } from "./errors.js";
23
23
  import { sha256, toHex, utf8 } from "./internal/bytes.js";
24
24
  import { decodeLowerHex } from "./internal/canonical.js";
25
- import { ConfigVerifier, FreshnessVerifier, KIND_PLATFORM, KIND_RUNTIME, MAX_CONFIG_SIZE, parseConfigName, PLATFORM_ARTIFACT_NAME, PUBLIC_REGISTRY_ID, publicSigningKeys, validateConfigPins, validateRegistryIDs, } from "./internal/endorsement/approval.js";
25
+ import { ConfigVerifier, FreshnessVerifier, KIND_PLATFORM, KIND_RUNTIME, parseConfigName, PLATFORM_ARTIFACT_NAME, PUBLIC_REGISTRY_ID, publicSigningKeys, validateConfigPins, validateRegistryIDs, } from "./internal/endorsement/approval.js";
26
26
  import { authenticateFreshness, MAX_FRESHNESS_AGE_MS } from "./internal/endorsement/freshness.js";
27
27
  import { ProvenanceClient } from "./internal/endorsement/provenance.js";
28
28
  import { parseReference } from "./internal/endorsement/reference.js";
@@ -30,12 +30,13 @@ import { authenticateRuntime } from "./internal/endorsement/runtime.js";
30
30
  import { strictParse } from "./internal/json/index.js";
31
31
  import { ARTIFACT_FORMAT, ARTIFACT_FORMAT_V2, parse as parseArtifact } from "./internal/policy/artifact.js";
32
32
  import * as quote from "./internal/quote/quote.js";
33
- import { configRuntime } from "./internal/runtime/config.js";
33
+ import { configRuntime, MAX_CONFIG_SIZE } from "./internal/runtime/config.js";
34
34
  import { decodeManifest, parseManifest } from "./internal/runtime/manifest.js";
35
35
  import * as semver from "./internal/semver.js";
36
36
  import { pinnedKeys } from "./internal/sigstore/keyed.js";
37
37
  import { cloneExpected, REGISTER_SIZE } from "./measurement.js";
38
- import { verificationOf } from "./verification.js";
38
+ import { measuredKeys, ReportBuilder } from "./report.js";
39
+ import { verifiedFactsOf } from "./verification.js";
39
40
  /** Only this module holds the token the constructor requires, so untyped code that calls it is refused. */
40
41
  const BUILT_HERE = Symbol("Verifier");
41
42
  /** Calls the private constructor; the class assigns it, as the only place the constructor can be called. */
@@ -63,17 +64,20 @@ export class Verifier {
63
64
  __classPrivateFieldSet(this, _Verifier_roots, parts.roots, "f");
64
65
  this.freshnessMaxAgeMs = parts.policy.freshnessMaxAgeMs;
65
66
  this.pinnedRegisters = parts.policy.pinnedRegisters === undefined ? undefined : Object.freeze(cloneExpected(parts.policy.pinnedRegisters));
66
- this.callerAuthorizesConfig = parts.policy.embedded.configReference !== undefined || parts.policy.configAuthorizer !== undefined;
67
67
  // The properties describe the policy the verifier enforces, so neither can be changed after it is built.
68
68
  Object.freeze(this);
69
69
  }
70
70
  /**
71
- * Builds a verifier. Defaults use the embedded production trust roots,
72
- * Tinfoil's public signing keys, and a seven-day freshness bound.
73
- * Throws UsageError for invalid options.
71
+ * Builds a verifier that trusts configs as `config` selects and applies
72
+ * `policy`. Undefined `config` selects Tinfoil's public registry, and an
73
+ * undefined or empty `policy` keeps every default: the embedded production
74
+ * trust roots, Tinfoil's public artifact signing keys and a seven-day
75
+ * freshness bound. Both are copied, so later changes by the caller have no
76
+ * effect. Throws UsageError for an invalid field, an unknown `kind` among
77
+ * them.
74
78
  */
75
- static async create(options = {}) {
76
- return buildVerifier(options, {});
79
+ static async create(config, policy) {
80
+ return buildVerifier(config, policy, {});
77
81
  }
78
82
  /**
79
83
  * Throws UsageError, without a document or network I/O, for a pin that
@@ -96,13 +100,23 @@ export class Verifier {
96
100
  /**
97
101
  * Appraises a nonce-bound v3 document against `pin` at the current time.
98
102
  * The document's collateral decides which part of `pin` applies.
103
+ *
104
+ * A document that it accepts resolves to a {@link VerificationReport}
105
+ * whose `verifiedFacts` hold what the document proved; the caller must
106
+ * bind its traffic to the keys in them and enforce their
107
+ * `freshnessExpiresAt`. A document that it rejects rejects with a
108
+ * {@link VerificationError} whose `report` shows the step that failed and
109
+ * what the steps before it established. A {@link UsageError} carries no
110
+ * report, because it reports a mistake in the caller's code rather than a
111
+ * rejected document.
99
112
  */
100
113
  async verifyV3(docBytes, nonce, pin) {
101
114
  return this.verifyV3At(docBytes, nonce, pin, new Date());
102
115
  }
103
116
  /**
104
117
  * Like {@link verifyV3}, but `verificationTime` replaces the clock in every
105
- * time-bound check (freshness, vendor certificate and CRL validity).
118
+ * time-bound check (freshness, vendor certificate and CRL validity), and
119
+ * the report's `metadata.verifiedAt` reports it.
106
120
  */
107
121
  async verifyV3At(docBytes, nonce, pin, verificationTime) {
108
122
  if (!(verificationTime instanceof Date) || !Number.isFinite(verificationTime.getTime())) {
@@ -115,51 +129,108 @@ export class Verifier {
115
129
  usage(() => parseReference(repo));
116
130
  __classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_referencePins).call(this, project);
117
131
  const now = new Date(verificationTime.getTime());
118
- const doc = await at("envelope", async () => {
119
- try {
120
- return await parseDocument(docBytes, nonce);
121
- }
122
- catch (err) {
123
- if (err instanceof InvalidInputError)
124
- throw new UsageError(err.message, { cause: err });
132
+ const metadata = { verifier: { name: VERIFIER_NAME, version: VERIFIER_VERSION }, verifiedAt: now };
133
+ const steps = new ReportBuilder();
134
+ let verified;
135
+ try {
136
+ verified = await __classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_verify).call(this, docBytes, nonce, repo, project, now, steps);
137
+ }
138
+ catch (err) {
139
+ // A usage error passes through without a report; a step's rejection
140
+ // becomes a VerificationError at its layer that carries the report.
141
+ if (!(err instanceof StepFailure))
125
142
  throw err;
126
- }
127
- });
128
- const refs = await at("provenance", async () => {
129
- switch (doc.collateralFormat()) {
130
- case FORMAT_V3:
131
- if (project === "" && repo !== "") {
132
- throw new Error("document carries config registry collateral, but only a GitHub repository is pinned");
133
- }
134
- return __classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_configReferences).call(this, doc, project, now);
135
- case FORMAT_V2:
136
- if (repo === "" && project !== "" && !__classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_requiresConfigCollateral).call(this)) {
137
- throw new Error("document carries GitHub repository collateral, but only a registry project is pinned");
138
- }
139
- return __classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_codeReferences).call(this, doc, repo, now);
140
- default:
141
- throw new Error(`unsupported collateral format ${JSON.stringify(doc.collateralFormat())}`);
142
- }
143
- });
144
- const authenticated = await at("quote", () => quote.authenticate(doc.cpuEvidence(), doc.cpuEndorsements(), now, { dangerousTestOnlyRoots: __classPrivateFieldGet(this, _Verifier_roots, "f") }));
145
- const assembled = await at("policy", () => quote.assemble(doc, refs.quote, __classPrivateFieldGet(this, _Verifier_policy, "f").pinnedRegisters, authenticated));
146
- await at("policy", () => quote.validate(assembled));
147
- return verificationOf({
148
- configRepo: refs.artifact.repo,
149
- codeDigest: refs.artifact.digest,
150
- codeTag: refs.artifact.tag,
151
- codeMeasurement: assembled.codeMeasurement,
152
- enclaveMeasurement: authenticated.measurement,
153
- cryptoMaterial: doc.cryptoMaterialItems(),
154
- config: refs.config,
155
- runtime: refs.config === undefined ? undefined : refs.artifact,
156
- platform: refs.platform,
157
- freshnessExpiresAt: new Date(Math.min(refs.freshnessExpiresAt?.getTime() ?? Infinity, authenticated.expiresAt.getTime())),
158
- metadata: { verifier: { name: VERIFIER_NAME, version: VERIFIER_VERSION }, verifiedAt: now },
159
- });
143
+ // The step names its layer, so its message is the failing check's own, without the error's prefix.
144
+ const report = steps.failed(err.layer, err.message, metadata);
145
+ throw new VerificationError(err.message, { layer: err.layer, report, cause: err.cause });
146
+ }
147
+ return steps.passedAll(verified, metadata);
160
148
  }
161
149
  }
162
- _Verifier_policy = new WeakMap(), _Verifier_prov = new WeakMap(), _Verifier_configVerifier = new WeakMap(), _Verifier_freshnessVerifier = new WeakMap(), _Verifier_roots = new WeakMap(), _Verifier_instances = new WeakSet(), _Verifier_requirePin = function _Verifier_requirePin(repo, project) {
150
+ _Verifier_policy = new WeakMap(), _Verifier_prov = new WeakMap(), _Verifier_configVerifier = new WeakMap(), _Verifier_freshnessVerifier = new WeakMap(), _Verifier_roots = new WeakMap(), _Verifier_instances = new WeakSet(), _Verifier_verify =
151
+ /**
152
+ * The verification itself: it records in `steps` each step that passes,
153
+ * and the facts that the step establishes, from the values that the step
154
+ * already computes. A rejection is a {@link StepFailure}.
155
+ */
156
+ async function _Verifier_verify(docBytes, nonce, repo, project, now, steps) {
157
+ const { doc, measured } = await at("envelope", async () => {
158
+ let parsed;
159
+ try {
160
+ parsed = await parseDocument(docBytes, nonce);
161
+ }
162
+ catch (err) {
163
+ if (err instanceof InvalidInputError)
164
+ throw new UsageError(err.message, { cause: err });
165
+ throw err;
166
+ }
167
+ return { doc: parsed, measured: await measuredKeys(parsed.cryptoMaterialItems()) };
168
+ });
169
+ steps.passed("envelope");
170
+ steps.measured = measured;
171
+ const refs = await at("provenance", async () => {
172
+ switch (doc.collateralFormat()) {
173
+ case FORMAT_V3:
174
+ if (project === "" && repo !== "") {
175
+ throw new Error("document carries config registry collateral, but only a GitHub repository is pinned");
176
+ }
177
+ return __classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_configReferences).call(this, doc, project, now);
178
+ case FORMAT_V2:
179
+ if (repo === "" && project !== "" && !__classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_requiresConfigCollateral).call(this)) {
180
+ throw new Error("document carries GitHub repository collateral, but only a registry project is pinned");
181
+ }
182
+ return __classPrivateFieldGet(this, _Verifier_instances, "m", _Verifier_codeReferences).call(this, doc, repo, now);
183
+ default:
184
+ throw new Error(`unsupported collateral format ${JSON.stringify(doc.collateralFormat())}`);
185
+ }
186
+ });
187
+ if (embedded(refs)) {
188
+ steps.set("provenance", "skipped", "the verifier embeds every reference value, so there is no endorsement to authenticate");
189
+ }
190
+ else {
191
+ steps.passed("provenance");
192
+ }
193
+ steps.expected = {
194
+ configRepo: refs.artifact.repo,
195
+ artifact: refs.artifact,
196
+ ...(refs.config === undefined ? {} : { config: refs.config }),
197
+ ...(refs.platform === undefined ? {} : { platform: refs.platform }),
198
+ };
199
+ const code = quote.codeMeasurement(refs.quote, doc.cpuEvidence().format);
200
+ if (code !== undefined)
201
+ steps.expected.codeMeasurement = code;
202
+ const authenticated = await at("quote", () => quote.authenticate(doc.cpuEvidence(), doc.cpuEndorsements(), now, { dangerousTestOnlyRoots: __classPrivateFieldGet(this, _Verifier_roots, "f") }));
203
+ steps.passed("quote");
204
+ steps.measured.cpu = { measurement: authenticated.measurement };
205
+ const expected = steps.expected;
206
+ const assembled = await at("policy", async () => {
207
+ try {
208
+ return await quote.assemble(doc, refs.quote, __classPrivateFieldGet(this, _Verifier_policy, "f").pinnedRegisters, authenticated);
209
+ }
210
+ catch (err) {
211
+ // The registers were resolved before the failure, so the report shows them.
212
+ if (!(err instanceof quote.ResolvedError))
213
+ throw err;
214
+ expected.measurement = err.expected;
215
+ throw err.cause;
216
+ }
217
+ });
218
+ expected.measurement = assembled.expected;
219
+ await at("policy", () => quote.validate(assembled));
220
+ steps.passed("policy");
221
+ return verifiedFactsOf({
222
+ configRepo: refs.artifact.repo,
223
+ codeDigest: refs.artifact.digest,
224
+ codeTag: refs.artifact.tag,
225
+ codeMeasurement: assembled.codeMeasurement,
226
+ enclaveMeasurement: authenticated.measurement,
227
+ cryptoMaterial: doc.cryptoMaterialItems(),
228
+ config: refs.config,
229
+ runtime: refs.config === undefined ? undefined : refs.artifact,
230
+ platform: refs.platform,
231
+ freshnessExpiresAt: new Date(Math.min(refs.freshnessExpiresAt?.getTime() ?? Infinity, authenticated.expiresAt.getTime())),
232
+ });
233
+ }, _Verifier_requirePin = function _Verifier_requirePin(repo, project) {
163
234
  const p = __classPrivateFieldGet(this, _Verifier_policy, "f");
164
235
  if (repo !== "" || project !== "" || p.embedded.configReference !== undefined || p.configAuthorizer !== undefined || p.configKeysPinned || p.configRegistryIDs !== undefined)
165
236
  return;
@@ -272,7 +343,7 @@ async function _Verifier_resolveConfig(doc, pins, now) {
272
343
  await authorizer({ ...material, config: config.slice(), ...(material.issuer === undefined ? {} : { issuer: material.issuer.slice() }) });
273
344
  }
274
345
  catch (err) {
275
- throw new VerificationError(`authorizing config: ${message(err)}`, { layer: "provenance", cause: err });
346
+ throw new StepFailure("provenance", `authorizing config: ${message(err)}`, err);
276
347
  }
277
348
  const digest = toHex(await sha256(config));
278
349
  return { expected: configRuntime(config), config: { source: "policy", name: "", digest, reference: "", signingKeyHint: "", registryID: "" } };
@@ -376,59 +447,46 @@ async function _Verifier_approvedAt(doc, id, kind, what, artifact, now) {
376
447
  (() => {
377
448
  construct = (parts) => new Verifier(BUILT_HERE, parts);
378
449
  })();
379
- /** Validates every option, resolves the trust material and assembles the verifier. */
380
- async function assemble(options, roots) {
450
+ /** Validates the config trust and the policy, resolves the trust material and assembles the verifier. */
451
+ async function assemble(config, policy, roots) {
381
452
  const prov = roots.sigstore ? await ProvenanceClient.fromJSON(roots.sigstore) : await ProvenanceClient.default();
382
- const pinnedRegisters = options.pinnedRegisters === undefined ? undefined : validPins(options.pinnedRegisters);
383
- const freshnessMaxAgeMs = freshnessBound(options.freshnessMaxAgeMs);
384
- const configKeys = options.configSigningKeys === undefined ? undefined : await keysOf("config signing keys", options.configSigningKeys);
385
- const freshnessKeys = options.freshnessSigningKeys === undefined ? undefined : await keysOf("freshness signing keys", options.freshnessSigningKeys);
386
- if (options.configAuthorizer !== undefined && typeof options.configAuthorizer !== "function") {
387
- throw new UsageError("config authorizer must be a function");
388
- }
389
- const embedded = options.embeddedReferences === undefined ? {} : await embeddedOf(options.embeddedReferences);
390
- if (embedded.configReference !== undefined && configKeys !== undefined) {
391
- throw new UsageError("embedded config and config signing keys select conflicting trust sources");
392
- }
393
- if (options.configAuthorizer !== undefined && (embedded.configReference !== undefined || configKeys !== undefined)) {
394
- throw new UsageError("config authorizer conflicts with embedded config or config signing keys");
395
- }
396
- const configRegistryIDs = options.configRegistryIDs === undefined ? undefined : usage(() => registryIDsOf(options.configRegistryIDs));
397
- if (configRegistryIDs !== undefined && (embedded.configReference !== undefined || options.configAuthorizer !== undefined)) {
398
- throw new UsageError("config authority pins require endorsement verification");
399
- }
400
- if (configRegistryIDs !== undefined && configKeys !== undefined) {
401
- throw new UsageError("config registry ID policy requires Tinfoil registry root verification");
402
- }
403
- if (embedded.runtime !== undefined && embedded.platform !== undefined && freshnessKeys !== undefined) {
404
- throw new UsageError("freshness signing keys have no endorsed artifact to verify");
405
- }
453
+ if (policy !== undefined && (typeof policy !== "object" || policy === null))
454
+ throw new UsageError("policy must be an object");
455
+ const pinnedRegisters = policy?.pinnedRegisters === undefined ? undefined : validPins(policy.pinnedRegisters);
456
+ const freshnessMaxAgeMs = freshnessBound(policy?.freshnessMaxAgeMs);
457
+ // The artifacts come first, so that an embedded config can check an embedded runtime against itself.
458
+ const artifacts = await artifactTrustOf(policy?.artifacts);
459
+ const trust = await configTrustOf(config, artifacts.runtime);
406
460
  const publicKeys = await publicSigningKeys();
407
461
  // Without caller-pinned config keys, the public keys are the registry
408
462
  // roots as well: they issue the signing certificates of certified approvals.
409
463
  const registryKeys = roots.registryRoots === undefined ? publicKeys : await keysOf("registry roots", roots.registryRoots);
410
- const configVerifier = configKeys === undefined ? new ConfigVerifier(prov.root, registryKeys, registryKeys) : new ConfigVerifier(prov.root, configKeys);
411
- const freshnessVerifier = new FreshnessVerifier(prov.root, freshnessKeys ?? publicKeys);
412
- const policy = {
413
- embedded,
464
+ const configVerifier = trust.configKeys === undefined ? new ConfigVerifier(prov.root, registryKeys, registryKeys) : new ConfigVerifier(prov.root, trust.configKeys);
465
+ const freshnessVerifier = new FreshnessVerifier(prov.root, artifacts.freshnessKeys ?? publicKeys);
466
+ const settings = {
467
+ embedded: {
468
+ ...(trust.configReference === undefined ? {} : { configReference: trust.configReference }),
469
+ ...(artifacts.runtime === undefined ? {} : { runtime: artifacts.runtime }),
470
+ ...(artifacts.platform === undefined ? {} : { platform: artifacts.platform }),
471
+ },
414
472
  pinnedRegisters,
415
473
  freshnessMaxAgeMs,
416
- configAuthorizer: options.configAuthorizer,
417
- configRegistryIDs,
418
- configKeysPinned: configKeys !== undefined,
419
- freshnessKeysPinned: freshnessKeys !== undefined,
474
+ configAuthorizer: trust.configAuthorizer,
475
+ configRegistryIDs: trust.configRegistryIDs,
476
+ configKeysPinned: trust.configKeys !== undefined,
477
+ freshnessKeysPinned: artifacts.freshnessKeys !== undefined,
420
478
  };
421
- return construct({ policy, prov, configVerifier, freshnessVerifier, roots: { amd: roots.amd, intel: roots.intel } });
479
+ return construct({ policy: settings, prov, configVerifier, freshnessVerifier, roots: { amd: roots.amd, intel: roots.intel } });
422
480
  }
423
481
  /**
424
- * @internal Validates the options and assembles the verifier under `roots`,
425
- * where an absent root selects the embedded production anchor; any failure
426
- * is a UsageError. {@link Verifier.create} is this with no roots injected.
427
- * Not exported from the package entry.
482
+ * @internal Validates the config trust and the policy and assembles the
483
+ * verifier under `roots`, where an absent root selects the embedded
484
+ * production anchor; any failure is a UsageError. {@link Verifier.create} is
485
+ * this with no roots injected. Not exported from the package entry.
428
486
  */
429
- export async function buildVerifier(options, roots) {
487
+ export async function buildVerifier(config, policy, roots) {
430
488
  try {
431
- return await assemble(options, roots);
489
+ return await assemble(config, policy, roots);
432
490
  }
433
491
  catch (err) {
434
492
  if (err instanceof UsageError)
@@ -436,6 +494,101 @@ export async function buildVerifier(options, roots) {
436
494
  throw new UsageError(message(err), { cause: err });
437
495
  }
438
496
  }
497
+ /** Validates and copies `artifacts`; undefined selects the endorsed artifacts under Tinfoil's keys. */
498
+ async function artifactTrustOf(artifacts) {
499
+ if (artifacts === undefined)
500
+ return {};
501
+ switch (kindOf(artifacts, "artifact trust")) {
502
+ case "endorsedArtifacts": {
503
+ const a = artifacts;
504
+ return a.freshnessKeys === undefined ? {} : { freshnessKeys: await keysOf("freshness signing keys", a.freshnessKeys) };
505
+ }
506
+ case "embeddedArtifacts": {
507
+ const a = artifacts;
508
+ const runtime = optionalBytes("embedded runtime", a.runtime);
509
+ const platform = optionalBytes("embedded platform", a.platform);
510
+ if (runtime === undefined && platform === undefined)
511
+ throw new UsageError("embedded artifacts must contain a runtime or a platform");
512
+ if (runtime !== undefined && platform !== undefined && a.freshnessKeys !== undefined) {
513
+ throw new UsageError("freshness signing keys have no endorsed artifact to verify");
514
+ }
515
+ const freshnessKeys = a.freshnessKeys === undefined ? undefined : await keysOf("freshness signing keys", a.freshnessKeys);
516
+ if (runtime !== undefined)
517
+ decodeManifest(runtime);
518
+ if (platform !== undefined && parseArtifact(platform).format !== ARTIFACT_FORMAT_V2) {
519
+ throw new UsageError("embedded platform requires platform-endorsements/v2");
520
+ }
521
+ return {
522
+ ...(freshnessKeys === undefined ? {} : { freshnessKeys }),
523
+ ...(runtime === undefined ? {} : { runtime }),
524
+ ...(platform === undefined ? {} : { platform }),
525
+ };
526
+ }
527
+ default:
528
+ throw new UsageError(`artifact trust must have kind "endorsedArtifacts" or "embeddedArtifacts", not ${describeKind(artifacts)}`);
529
+ }
530
+ }
531
+ /**
532
+ * Validates and copies `config`; undefined selects the public registry. An
533
+ * embedded config is checked against `embeddedRuntime`, the caller's own
534
+ * runtime manifest when it embeds one: both come from the caller, so a
535
+ * manifest that the config doesn't pin is rejected here rather than at
536
+ * verification.
537
+ */
538
+ async function configTrustOf(config, embeddedRuntime) {
539
+ if (config === undefined)
540
+ return {};
541
+ switch (kindOf(config, "config trust")) {
542
+ case "registries":
543
+ return { configRegistryIDs: usage(() => registryIDsOf(config.ids)) };
544
+ case "configSigningKeys":
545
+ return { configKeys: await keysOf("config signing keys", config.keys) };
546
+ case "configAuthorizer": {
547
+ const authorize = config.authorize;
548
+ if (typeof authorize !== "function")
549
+ throw new UsageError("config authorizer must be a function");
550
+ return { configAuthorizer: authorize };
551
+ }
552
+ case "embeddedConfig":
553
+ case "embeddedConfigReference": {
554
+ const reference = await configReferenceOf(config);
555
+ if (reference.name !== "")
556
+ usage(() => parseConfigName(reference.name));
557
+ usage(() => decodeLowerHex("config digest", reference.digest, 32));
558
+ usage(() => validateRuntimeReference(reference.runtime));
559
+ if (embeddedRuntime !== undefined)
560
+ await parseManifest(embeddedRuntime, reference.runtime);
561
+ return { configReference: reference };
562
+ }
563
+ default:
564
+ throw new UsageError(`config trust must have kind "registries", "configSigningKeys", "configAuthorizer", "embeddedConfig" or "embeddedConfigReference", not ${describeKind(config)}`);
565
+ }
566
+ }
567
+ /** The `kind` of a sum-type value that untyped code may have passed as anything; a non-object is a UsageError. */
568
+ function kindOf(value, what) {
569
+ if (typeof value !== "object" || value === null)
570
+ throw new UsageError(`${what} must be an object with a kind`);
571
+ return value.kind;
572
+ }
573
+ /** How an unknown `kind` is named in an error. */
574
+ function describeKind(value) {
575
+ const kind = value.kind;
576
+ if (kind === undefined)
577
+ return "a value without one";
578
+ if (typeof kind === "string")
579
+ return JSON.stringify(kind);
580
+ if (typeof kind === "number" || typeof kind === "boolean" || typeof kind === "bigint" || kind === null)
581
+ return String(kind);
582
+ return `a ${typeof kind}`;
583
+ }
584
+ /** A copy of caller-supplied bytes, or undefined when they are absent; anything but a Uint8Array is a UsageError. */
585
+ function optionalBytes(what, bytes) {
586
+ if (bytes === undefined)
587
+ return undefined;
588
+ if (!(bytes instanceof Uint8Array))
589
+ throw new UsageError(`${what} must be a Uint8Array`);
590
+ return bytes.slice();
591
+ }
439
592
  /** The parts of `pin`, "" when unset. A bare string is refused, not read as an empty pin. */
440
593
  function pinOf(pin) {
441
594
  if (typeof pin !== "object" || pin === null)
@@ -452,6 +605,18 @@ function registryIDsOf(registryIDs) {
452
605
  validateRegistryIDs(registryIDs);
453
606
  return [...registryIDs];
454
607
  }
608
+ /**
609
+ * A step's rejection of the document at `layer`, which `verifyV3At` reports
610
+ * as a {@link VerificationError} with the same message and cause once the
611
+ * report is complete.
612
+ */
613
+ class StepFailure extends Error {
614
+ constructor(layer, message, cause) {
615
+ super(message);
616
+ this.layer = layer;
617
+ this.cause = cause;
618
+ }
619
+ }
455
620
  /**
456
621
  * Runs one pipeline step; an error that is not already classified is
457
622
  * attributed to `layer`. That includes the verifier's own failures inside
@@ -463,11 +628,19 @@ async function at(layer, step) {
463
628
  return await step();
464
629
  }
465
630
  catch (err) {
466
- if (err instanceof VerifyError)
631
+ if (err instanceof VerifyError || err instanceof StepFailure)
467
632
  throw err;
468
- throw new VerificationError(message(err), { layer, cause: err });
633
+ throw new StepFailure(layer, message(err), err);
469
634
  }
470
635
  }
636
+ /**
637
+ * Whether the caller embedded every reference value in the verifier, so
638
+ * that provenance authenticated nothing: the config, the runtime and the
639
+ * platform.
640
+ */
641
+ function embedded(refs) {
642
+ return refs.config?.source === "embedded" && refs.artifact.source === "embedded" && refs.platform?.source === "embedded";
643
+ }
471
644
  /** Runs a caller-input check; its failure is a UsageError. */
472
645
  function usage(check) {
473
646
  try {
@@ -518,6 +691,8 @@ function freshnessBound(maxAgeMs) {
518
691
  return maxAgeMs;
519
692
  }
520
693
  async function keysOf(what, pems) {
694
+ if (!Array.isArray(pems) || pems.some((pem) => typeof pem !== "string"))
695
+ throw new UsageError(`${what} must be a list of PEM strings`);
521
696
  if (pems.length === 0)
522
697
  throw new UsageError(`${what} must not be empty`);
523
698
  try {
@@ -528,53 +703,16 @@ async function keysOf(what, pems) {
528
703
  }
529
704
  }
530
705
  /**
531
- * Validates the embedded references and settles the config reference: the
532
- * caller's own, or one derived from embedded config bytes. Both come from
533
- * the caller, so a runtime manifest the reference does not pin is rejected
534
- * here rather than at verification.
535
- */
536
- async function embeddedOf(refs) {
537
- if (refs.config === undefined && refs.runtime === undefined && refs.platform === undefined) {
538
- throw new UsageError("embedded references must contain at least one component");
539
- }
540
- const configReference = refs.config === undefined ? undefined : await configReferenceOf(refs.config);
541
- if (configReference !== undefined) {
542
- const reference = configReference;
543
- if (reference.name !== "")
544
- usage(() => parseConfigName(reference.name));
545
- usage(() => decodeLowerHex("config digest", reference.digest, 32));
546
- usage(() => validateRuntimeReference(reference.runtime));
547
- if (refs.runtime !== undefined)
548
- await parseManifest(refs.runtime, reference.runtime);
549
- }
550
- if (refs.runtime !== undefined)
551
- decodeManifest(refs.runtime);
552
- if (refs.platform !== undefined && parseArtifact(refs.platform).format !== ARTIFACT_FORMAT_V2) {
553
- throw new UsageError("embedded platform requires platform-endorsements/v2");
554
- }
555
- return {
556
- ...(configReference === undefined ? {} : { configReference }),
557
- ...(refs.runtime === undefined ? {} : { runtime: refs.runtime.slice() }),
558
- ...(refs.platform === undefined ? {} : { platform: refs.platform.slice() }),
559
- };
560
- }
561
- /**
562
- * The config reference an embedded config settles to: derived from its
563
- * bytes, or a copy of the caller's digest and runtime pin. The type admits
564
- * one form or the other; an object from untyped code that has both or
565
- * neither is refused.
706
+ * The config reference that an embedded config settles to: derived from its
707
+ * bytes, or a copy of the caller's digest and runtime pin.
566
708
  */
567
709
  async function configReferenceOf(config) {
568
- if (typeof config !== "object" || config === null)
569
- throw new UsageError("embedded config must be an object");
570
- const hasBytes = config.bytes !== undefined;
571
- const hasDigest = config.digest !== undefined;
572
- if (hasBytes === hasDigest)
573
- throw new UsageError("embedded config is either its bytes or its digest and runtime pin, not both or neither");
574
- if (hasBytes) {
710
+ if (config.kind === "embeddedConfig") {
575
711
  const { name, bytes } = config;
576
712
  if (!(bytes instanceof Uint8Array))
577
713
  throw new UsageError("embedded config bytes must be a Uint8Array");
714
+ if (name !== undefined && typeof name !== "string")
715
+ throw new UsageError("embedded config name must be a string");
578
716
  // Copied once so the digest and the runtime pin come from the same bytes, whatever the caller does to its buffer meanwhile.
579
717
  const copy = bytes.slice();
580
718
  return { name: name ?? "", digest: toHex(await sha256(copy)), runtime: usage(() => configRuntime(copy)) };