@agledger/verify-core 1.4.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chain.js CHANGED
@@ -15,44 +15,160 @@
15
15
  * - ALWAYS-RUN (every surface): position monotonicity, payloadHash =
16
16
  * sha256(cose_sign1), previous-hash link, COSE_Sign1 decode, the signed
17
17
  * protected-header chain-claim cross-check, and the Ed25519 signature.
18
- * - INPUT-GATED (only when the normalized entry carries the inputs, i.e. the
19
- * dump path): binding-integrity, OIDC-actor cross-check, temporal
20
- * key-validity. The `/audit-export` wire does NOT carry the inputs these
21
- * need (the API re-projects the export payload from the signed bytes and
22
- * omits the synthesized flag), so running them there would either no-op
23
- * silently or compare signed bytes to a derivative of themselves. They are
24
- * therefore reported as `skipped_no_input` on the export path, NEVER folded
25
- * into a green verdict.
18
+ * - INPUT-GATED (only when the normalized entry, or the caller, supplies the
19
+ * inputs): binding-integrity, OIDC-actor cross-check, temporal
20
+ * key-validity, the agent-signature re-check, and key anchoring (a
21
+ * registry marked by `applyKeyTrust`). The first three run on
22
+ * the dump and on any export from an engine that ships the row fields
23
+ * (>= v0.26.x). The agent-signature check needs the cert's public key,
24
+ * which neither surface carries, so it runs only when the caller passes
25
+ * `agentKeys`. A check without its input is reported `skipped_no_input`,
26
+ * NEVER folded into a green verdict.
26
27
  *
27
28
  * Failure ordering is fixed so `brokenAt` is deterministic. The null-key
28
- * signature skip happens LAST, after the binding/OIDC checks, so a row written
29
- * without a signing key is still subject to every structural check.
29
+ * branch comes LAST, after the binding/OIDC checks, so a row written without a
30
+ * signing key is still subject to every structural check, and a tamper finding
31
+ * on it is reported under its own code rather than as CHAIN_ENTRY_UNSIGNED.
32
+ * That branch grades the entry the way the engine does: an unsigned entry
33
+ * after a signed one in its chain, or written at or after the earliest key
34
+ * activation (`signingSince`), is CHAIN_ENTRY_UNSIGNED; an earlier one is a
35
+ * `skipped` signature, reduced coverage rather than a break.
36
+ */
37
+ import { buildPredicateForRow, decodeCoseSign1, decodePredicate, deepEqual, describeUnsupportedAlgorithm, ed25519JwkThumbprint, ed25519JwkToSpki, extractAgentSignatureClaim, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, resolveKeyAlgorithm, sha256Hex, stripEnvelopeExtensions, envelopeExtensionsMatch, verifyAgentSignature, verifyCoseSign1, } from './primitives.js';
38
+ import { instantMs, rfc3339Ms } from './instant.js';
39
+ import { assertKnownOptions } from './options.js';
40
+ /**
41
+ * Index keys by key id. A key whose `spkiBase64` is not a non-empty string
42
+ * carries no key material (a registry row with its public key nulled), so it
43
+ * is left out: an entry naming it fails CHAIN_SIGNATURE_MISSING_KEY.
30
44
  */
31
- import { buildPredicateForRow, decodeCoseSign1, decodePredicate, deepEqual, describeUnsupportedAlgorithm, extractChainClaim, extractKid, extractOnBehalfOfClaim, resolveKeyAlgorithm, sha256Hex, stripEnvelopeExtensions, verifyCoseSign1, } from './primitives.js';
32
45
  export function buildKeyRegistry(keys) {
33
46
  const map = new Map();
34
- for (const k of keys)
47
+ for (const k of keys) {
48
+ if (typeof k.spkiBase64 !== 'string' || k.spkiBase64 === '')
49
+ continue;
35
50
  map.set(k.keyId, k);
51
+ }
36
52
  return map;
37
53
  }
54
+ /**
55
+ * Index caller-supplied agent cert keys by thumbprint. A key is matched to an
56
+ * entry only through the thumbprint that entry signed, so a key supplied for
57
+ * the wrong cert is never checked against it: it simply matches nothing.
58
+ * That is also why the source of a key needs no trust: the signed thumbprint
59
+ * is what binds it. Throws `TypeError` on anything that is not an Ed25519 JWK.
60
+ */
61
+ export function buildAgentKeyRegistry(jwks) {
62
+ if (!Array.isArray(jwks)) {
63
+ throw new TypeError('agentKeys must be an array of Ed25519 JWKs ({ kty: "OKP", crv: "Ed25519", x }).');
64
+ }
65
+ const map = new Map();
66
+ jwks.forEach((jwk, i) => {
67
+ const thumbprint = ed25519JwkThumbprint(jwk);
68
+ const spki = ed25519JwkToSpki(jwk);
69
+ if (thumbprint === null || spki === null) {
70
+ throw new TypeError(`agentKeys[${i}] is not an Ed25519 public-key JWK. Expected { kty: "OKP", crv: "Ed25519", x: <base64url of 32 bytes> }, the publicKeyJwk sent at cert exchange (also the cnf.jwk claim inside the certJws).`);
71
+ }
72
+ map.set(thumbprint, spki);
73
+ });
74
+ return map;
75
+ }
76
+ /** The code an {@link AccountedEntry} carries. Not a {@link FailureCode}: it never fails a verdict. */
77
+ export const ACCOUNTED_ENTRY_CODE = 'CHAIN_SIGNED_BY_DISTRUSTED_KEY';
78
+ const PLATFORM_OPS_RECORD_ID = '00000000-0000-0000-0000-000000000000';
79
+ /** Name a chain scope (a record id or a dump `chain_key`) as {@link AccountedEntry} does. */
80
+ export function chainOfScope(scopeId) {
81
+ if (scopeId.startsWith('schema:')) {
82
+ const org = scopeId.slice('schema:'.length);
83
+ return { chain: 'schema', recordId: null, orgId: org === '__platform__' ? null : org };
84
+ }
85
+ if (scopeId.toLowerCase() === PLATFORM_OPS_RECORD_ID)
86
+ return { chain: 'admin', recordId: null, orgId: null };
87
+ return { chain: 'record', recordId: scopeId, orgId: null };
88
+ }
89
+ /**
90
+ * The earliest `activatedAt` among `keys`, as the ISO string it was given in,
91
+ * or `null` when no key carries a parseable one. This is the instant from
92
+ * which the engine treats every chain entry and checkpoint as required to be
93
+ * signed; pass every key the verifier knows, retired ones included, since the
94
+ * engine reads it as `min(activated_at)` over its whole key registry.
95
+ */
96
+ export function earliestKeyActivation(keys) {
97
+ let earliest = null;
98
+ for (const k of keys) {
99
+ if (typeof k.activatedAt !== 'string')
100
+ continue;
101
+ const at = instantMs(k.activatedAt);
102
+ if (Number.isNaN(at))
103
+ continue;
104
+ if (earliest === null || at < earliest.at)
105
+ earliest = { at, iso: k.activatedAt };
106
+ }
107
+ return earliest?.iso ?? null;
108
+ }
109
+ /**
110
+ * Whether a row with no signing key id, written at `writtenAt`, falls inside
111
+ * the era in which the install signs everything: at or after `signingSince`
112
+ * (see `earliestKeyActivation`). This is the rule for an unsigned checkpoint
113
+ * (CHECKPOINT_UNSIGNED) and an unsigned read-log leaf or tree head, and the
114
+ * time half of the rule for an unsigned entry (CHAIN_ENTRY_UNSIGNED).
115
+ *
116
+ * False when `signingSince` is absent or unparseable: with no instant from
117
+ * which the install signs, nothing has to be signed. True when `signingSince`
118
+ * is known and `writtenAt` is missing or not strict RFC 3339: the engine times every
119
+ * row, so a row with no readable time was edited, and it cannot be placed
120
+ * before signing began. It fails closed rather than reading as early history.
121
+ */
122
+ export function writtenWhileSigning(writtenAt, signingSince) {
123
+ if (typeof signingSince !== 'string')
124
+ return false;
125
+ const since = instantMs(signingSince);
126
+ if (Number.isNaN(since))
127
+ return false;
128
+ const written = typeof writtenAt === 'string' ? rfc3339Ms(writtenAt) : Number.NaN;
129
+ if (Number.isNaN(written))
130
+ return true;
131
+ return written >= since;
132
+ }
133
+ /** Whether `value` is a strict RFC 3339 instant the walk can place. */
134
+ function isInstant(value) {
135
+ return typeof value === 'string' && !Number.isNaN(rfc3339Ms(value));
136
+ }
137
+ /**
138
+ * The order the walk sorts entries in: by `chainPosition`, an entry whose
139
+ * position is not a safe integer after every one whose is, ties in input
140
+ * order. Such an entry then fails CHAIN_POSITION_GAP at its place.
141
+ */
142
+ function positionKey(position) {
143
+ return Number.isSafeInteger(position) ? position : Number.POSITIVE_INFINITY;
144
+ }
38
145
  /**
39
146
  * Verify a single hash chain. `entries` are all the entries for one scope; they
40
147
  * are sorted by chainPosition internally (so a reordered export array still
41
148
  * validates the true chain; tampering surfaces through the hash links).
42
149
  */
43
150
  export function verifyChain(entries, keys, options = {}) {
151
+ assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'signingSince']);
44
152
  const scopeId = entries[0]?.scopeId ?? '(empty)';
45
- const sorted = [...entries].sort((a, b) => a.chainPosition - b.chainPosition);
153
+ const sorted = entries
154
+ .map((entry, at) => ({ entry, at, key: positionKey(entry.chainPosition) }))
155
+ .sort((a, b) => (a.key === b.key ? a.at - b.at : a.key < b.key ? -1 : 1))
156
+ .map(({ entry }) => entry);
46
157
  const entryResults = [];
47
158
  const coverage = { signed: 0, unsigned: 0, skipped: 0, total: sorted.length };
48
159
  const optionalChecks = {
49
160
  payload_binding: 'skipped_no_input',
50
161
  oidc_actor: 'skipped_no_input',
162
+ actor_attribution: 'skipped_no_input',
51
163
  key_temporal: 'skipped_no_input',
164
+ agent_signature: 'skipped_no_input',
165
+ key_anchoring: 'skipped_no_input',
52
166
  };
53
- const keyProvenance = { outOfBand: 0, embedded: 0 };
167
+ const keyProvenance = { supplied: 0, embedded: 0 };
168
+ const agentSignatures = { present: 0, verified: 0 };
54
169
  let verifiedEntries = 0;
55
170
  let brokenAt;
171
+ const accounted = [];
56
172
  if (sorted.length === 0) {
57
173
  return {
58
174
  scopeId,
@@ -61,18 +177,48 @@ export function verifyChain(entries, keys, options = {}) {
61
177
  verifiedEntries: 0,
62
178
  brokenAt: { position: 0, code: 'CHAIN_EMPTY', detail: 'No entries to verify.' },
63
179
  entries: [],
180
+ accounted: [],
64
181
  signatureCoverage: coverage,
65
182
  optionalChecks,
66
183
  keyProvenance,
184
+ agentSignatures,
67
185
  };
68
186
  }
187
+ let signingSince;
188
+ if (options.signingSince === undefined) {
189
+ signingSince = earliestKeyActivation(keys.values());
190
+ }
191
+ else {
192
+ signingSince = options.signingSince;
193
+ if (signingSince !== null && Number.isNaN(instantMs(signingSince))) {
194
+ throw new TypeError(`signingSince must be an RFC 3339 instant or null (got ${JSON.stringify(signingSince)}).`);
195
+ }
196
+ }
197
+ const mustSign = { signedBefore: false, signingSince };
69
198
  let previousHash = null;
70
199
  for (let i = 0; i < sorted.length; i++) {
71
200
  const entry = sorted[i];
72
201
  const expectedPosition = i + 1;
73
- const result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks);
202
+ let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks, mustSign);
203
+ // As the engine's walk does: any earlier row naming a key, whatever its own
204
+ // verdict, means this chain was already being signed.
205
+ if (entry.signingKeyId !== null)
206
+ mustSign.signedBefore = true;
207
+ if (result.valid && result.accounted === undefined) {
208
+ result = checkAgentSignature(entry, result, options.agentKeys, optionalChecks, agentSignatures);
209
+ }
74
210
  entryResults.push(result);
75
- if (result.valid)
211
+ if (result.accounted !== undefined) {
212
+ accounted.push({
213
+ code: result.accounted.code,
214
+ ...chainOfScope(scopeId),
215
+ scopeId,
216
+ position: result.position,
217
+ keyId: entry.signingKeyId ?? '',
218
+ detail: result.accounted.detail,
219
+ });
220
+ }
221
+ else if (result.valid)
76
222
  verifiedEntries++;
77
223
  else if (!brokenAt && result.failure) {
78
224
  brokenAt = { position: result.position, code: result.failure.code, detail: result.failure.detail };
@@ -80,8 +226,8 @@ export function verifyChain(entries, keys, options = {}) {
80
226
  switch (result.signature) {
81
227
  case 'ok':
82
228
  coverage.signed++;
83
- if (result.keySource === 'out-of-band')
84
- keyProvenance.outOfBand++;
229
+ if (result.keySource === 'supplied')
230
+ keyProvenance.supplied++;
85
231
  else if (result.keySource === 'embedded')
86
232
  keyProvenance.embedded++;
87
233
  break;
@@ -97,28 +243,82 @@ export function verifyChain(entries, keys, options = {}) {
97
243
  }
98
244
  previousHash = entry.payloadHash;
99
245
  }
246
+ // The caller walked the key statements (every key carries a verdict), but no
247
+ // entry got as far as the anchoring check.
248
+ if (optionalChecks.key_anchoring === 'skipped_no_input' && [...keys.values()].some((k) => k.trust !== undefined)) {
249
+ optionalChecks.key_anchoring = 'not_checked';
250
+ }
100
251
  return {
101
252
  scopeId,
102
- valid: verifiedEntries === sorted.length,
253
+ valid: verifiedEntries + accounted.length === sorted.length,
103
254
  totalEntries: sorted.length,
104
255
  verifiedEntries,
105
256
  brokenAt,
106
257
  entries: entryResults,
258
+ accounted,
107
259
  signatureCoverage: coverage,
108
260
  optionalChecks,
109
261
  keyProvenance,
262
+ agentSignatures,
110
263
  };
111
264
  }
265
+ /**
266
+ * Offline re-check of a sealed agent signature, on an entry that already
267
+ * passed every other check (so its payload is the engine's signed bytes).
268
+ *
269
+ * Runs only on an engine-validated identity (`on_behalf_of.validated: true`).
270
+ * On a caller-asserted one, entries written before the engine sealed these
271
+ * fields itself carry them as caller passthrough, and the marker telling the
272
+ * two apart is a column neither the export nor the dump publishes, so a
273
+ * failure there could not be told from a claim nobody ever checked.
274
+ */
275
+ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
276
+ const parts = decodeCoseSign1(Buffer.from(entry.coseSign1, 'base64'));
277
+ if (!parts)
278
+ return result;
279
+ const claim = extractAgentSignatureClaim(parts.payloadBstr);
280
+ if (claim === null)
281
+ return result;
282
+ counts.present++;
283
+ if (!claim.validated || !agentKeys || claim.certThumbprint === null)
284
+ return result;
285
+ const spki = agentKeys.get(claim.certThumbprint);
286
+ if (spki === undefined)
287
+ return result;
288
+ optionalChecks.agent_signature = 'applied';
289
+ const outcome = verifyAgentSignature(spki, claim);
290
+ if (outcome === 'ok') {
291
+ counts.verified++;
292
+ return result;
293
+ }
294
+ const certLabel = claim.certId ?? claim.certThumbprint;
295
+ if (outcome === 'unsupported') {
296
+ return fail(entry.scopeId, result.position, 'CHAIN_UNSUPPORTED_ALGORITHM', `Agent signature for cert ${certLabel} could not be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA). Not verified, and not tamper evidence.`, result.signature);
297
+ }
298
+ return fail(entry.scopeId, result.position, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
299
+ ? `Sealed agent_signature for cert ${certLabel} has a shape nothing can verify (alg must be EdDSA, content_hash sha256:<hex64>, signature 64 bytes of standard base64).`
300
+ : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`, result.signature);
301
+ }
302
+ function accountedResult(scopeId, position, detail) {
303
+ return { scopeId, position, valid: true, accounted: { code: ACCOUNTED_ENTRY_CODE, detail }, signature: 'accounted' };
304
+ }
305
+ /** The registry declares an algorithm for the key that its key material does not commit to. */
306
+ function declaredAlgorithmLies(key) {
307
+ if (typeof key.algorithm !== 'string')
308
+ return false;
309
+ const keyAlg = resolveKeyAlgorithm(key.spkiBase64);
310
+ return typeof keyAlg === 'object' && keyAlg.name.toLowerCase() !== key.algorithm.toLowerCase();
311
+ }
112
312
  function fail(scopeId, position, code, detail, signature = 'not-checked') {
113
313
  return { scopeId, position, valid: false, failure: { code, detail }, signature };
114
314
  }
115
- function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks) {
315
+ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
116
316
  const { scopeId } = entry;
117
317
  if (entry.chainPosition !== expectedPosition) {
118
318
  return fail(scopeId, entry.chainPosition, 'CHAIN_POSITION_GAP', `Expected chainPosition ${expectedPosition}, got ${entry.chainPosition}.`);
119
319
  }
120
- if (!entry.coseSign1 || !entry.payloadHash) {
121
- return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', 'Entry is missing coseSign1 or payloadHash.');
320
+ if (typeof entry.coseSign1 !== 'string' || typeof entry.payloadHash !== 'string' || !entry.coseSign1 || !entry.payloadHash) {
321
+ return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', 'Entry is missing coseSign1 or payloadHash, or carries one that is not a string.');
122
322
  }
123
323
  const envelopeBytes = Buffer.from(entry.coseSign1, 'base64');
124
324
  const recomputed = sha256Hex(envelopeBytes);
@@ -143,6 +343,36 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
143
343
  chainClaim.previous_hash !== expectedPrev) {
144
344
  return fail(scopeId, expectedPosition, 'CHAIN_COSE_HEADER_MISMATCH', `Signed protected-header chain claim (position=${chainClaim?.position ?? 'null'}, prev=${chainClaim?.previous_hash ?? 'null'}) diverges from row columns (position=${entry.chainPosition}, prev=${entry.previousHash ?? 'null'}).`);
145
345
  }
346
+ // Input-gated: actor attribution. The row's actorId/actorOwnerId columns are
347
+ // the projection a report displays as "who did this", and the engine's own
348
+ // export guide names them as the trustworthy attribution while listing only
349
+ // actorDisplayName / actorOwnerType / humanReadableLabel as unsigned. They
350
+ // are signature-covered, at CWT_Claims label 15 -> private label -65539, so
351
+ // a rewritten column is a re-attribution of the action to another actor and
352
+ // must not verify. Same shape as the signed-kid check above: compare the
353
+ // column against the signed claim, and skip only when one side is absent
354
+ // (an older engine that never carried the claim, or an artifact that does
355
+ // not carry the columns).
356
+ const attribution = entry.actorAttribution;
357
+ if (attribution) {
358
+ const actorClaim = extractActorClaim(parts.protectedBstr);
359
+ if (actorClaim) {
360
+ optionalChecks.actor_attribution = 'applied';
361
+ const mismatches = [];
362
+ if (attribution.actorId !== null && attribution.actorId !== actorClaim.key_id) {
363
+ mismatches.push(`actorId=${attribution.actorId} vs signed ${actorClaim.key_id}`);
364
+ }
365
+ if (attribution.actorOwnerId !== null && attribution.actorOwnerId !== actorClaim.owner_id) {
366
+ mismatches.push(`actorOwnerId=${attribution.actorOwnerId} vs signed ${actorClaim.owner_id}`);
367
+ }
368
+ if (attribution.actorRole !== null && attribution.actorRole !== actorClaim.role) {
369
+ mismatches.push(`actorRole=${attribution.actorRole} vs signed ${actorClaim.role}`);
370
+ }
371
+ if (mismatches.length > 0) {
372
+ return fail(scopeId, expectedPosition, 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH', `Row actor columns diverge from the signature-covered actor claim (${mismatches.join('; ')}).`);
373
+ }
374
+ }
375
+ }
146
376
  // Input-gated: binding-integrity. Runs whenever the row payload is present:
147
377
  // the dump always carries it, and the export now carries it too (engine ≥ v0.26.x).
148
378
  if (entry.binding) {
@@ -150,7 +380,11 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
150
380
  const decodedRaw = decodePredicate(parts.payloadBstr);
151
381
  const rebuilt = buildPredicateForRow(entry.binding.recordId, entry.binding.entryType, entry.binding.payload);
152
382
  const decoded = decodedRaw !== null ? stripEnvelopeExtensions(decodedRaw) : null;
153
- if (decoded === null || rebuilt === null || !deepEqual(rebuilt, decoded)) {
383
+ if (decodedRaw === null ||
384
+ decoded === null ||
385
+ rebuilt === null ||
386
+ !deepEqual(rebuilt, decoded) ||
387
+ !envelopeExtensionsMatch(entry.binding.payload, decodedRaw)) {
154
388
  return fail(scopeId, expectedPosition, 'CHAIN_PAYLOAD_BINDING_MISMATCH', 'Denormalised row payload no longer matches the canonical projection of the signed predicate.');
155
389
  }
156
390
  }
@@ -167,12 +401,31 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
167
401
  // and fails CHAIN_SIGNATURE_MISSING_KEY below: a truthiness shortcut here
168
402
  // would let a tampered signingKeyId:"" row skip its signature check.
169
403
  if (entry.signingKeyId === null) {
404
+ // Engine mirror of `signature_missing`. An unsigned entry is reduced
405
+ // coverage only where the install had not yet begun to sign: before any
406
+ // signed entry in this chain, and before the earliest key activation.
407
+ // Anywhere else no process of the install could have written it; it is
408
+ // what a writer holding no key leaves on the tip, or a signed row whose
409
+ // key id was nulled. Checked ahead of the caller's key policy because it
410
+ // is evidence about the chain itself, whatever policy the run applies.
411
+ if (mustSign.signedBefore) {
412
+ return fail(scopeId, expectedPosition, 'CHAIN_ENTRY_UNSIGNED', 'Entry has no signingKeyId but follows a signed entry in the same chain.');
413
+ }
414
+ // The engine times every entry. Without a time the walk can read, an
415
+ // unsigned entry cannot be placed before signing began, so it is not
416
+ // early history: it fails closed.
417
+ if (mustSign.signingSince !== null && !isInstant(entry.createdAt)) {
418
+ return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', `Entry has no signingKeyId and no parseable createdAt, so it cannot be placed before the earliest signing key activation ${mustSign.signingSince}.`);
419
+ }
420
+ if (writtenWhileSigning(entry.createdAt, mustSign.signingSince)) {
421
+ return fail(scopeId, expectedPosition, 'CHAIN_ENTRY_UNSIGNED', `Entry has no signingKeyId but was written ${entry.createdAt}, at or after the earliest signing key activation ${mustSign.signingSince}.`);
422
+ }
170
423
  // Fail closed under a key policy: a high-assurance run that requires a
171
- // specific key (or out-of-band keys) must NOT accept an unsigned/null-key
424
+ // specific key (or supplied keys) must NOT accept an unsigned/null-key
172
425
  // entry as valid; otherwise an attacker forges an entry, nulls its
173
426
  // signingKeyId, and slips past the policy the auditor explicitly set.
174
- if (options.requireKeyId || options.requireOutOfBandKeys) {
175
- return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', 'Entry has no signingKeyId but this run requires a signed entry (requireKeyId / requireOutOfBandKeys).');
427
+ if (options.requireKeyId || options.requireSuppliedKeys) {
428
+ return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', 'Entry has no signingKeyId but this run requires a signed entry (requireKeyId / requireSuppliedKeys).');
176
429
  }
177
430
  return { scopeId, position: expectedPosition, valid: true, signature: 'skipped' };
178
431
  }
@@ -183,51 +436,98 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
183
436
  if (!key) {
184
437
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_MISSING_KEY', `No public key available for signingKeyId=${entry.signingKeyId}.`);
185
438
  }
186
- if (options.requireOutOfBandKeys && key.source !== 'out-of-band') {
187
- return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', `Key ${entry.signingKeyId} is embedded in the artifact; this run requires out-of-band keys.`);
439
+ if (options.requireSuppliedKeys && key.source !== 'supplied') {
440
+ return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', `Key ${entry.signingKeyId} is embedded in the artifact; this run requires supplied keys.`);
441
+ }
442
+ // Signed-kid binding (engine mirror: signing_key_drift), ahead of every
443
+ // question about the key, as the engine orders it. The row's signingKeyId
444
+ // column selected the key above, but the column is a denormalized
445
+ // convenience; the kid at protected-header label 4 is signature-covered. A
446
+ // divergence means the column was rewritten after signing, e.g. to point
447
+ // verification at a key the tamperer controls.
448
+ // An accounted-for entry past its distrust cutoff (see the temporal check).
449
+ let accountedPastCutoff = null;
450
+ const signedKid = extractKid(parts.protectedBstr);
451
+ if (signedKid !== null && signedKid !== entry.signingKeyId) {
452
+ return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_DRIFT', `Row signingKeyId=${entry.signingKeyId} does not match the signature-covered kid ${signedKid} in the protected header.`);
453
+ }
454
+ // Input-gated: key anchoring (engine mirror: signing_key_unanchored). Runs
455
+ // when a key-statement walk marked the registry. A key nothing signed links
456
+ // to a pinned anchor is one anything with write access to the Server's
457
+ // database can register, so an entry under it is a forgery until shown
458
+ // otherwise, whatever its signature says.
459
+ if (key.trust !== undefined) {
460
+ optionalChecks.key_anchoring = 'applied';
461
+ if (key.trust === 'unanchored') {
462
+ // A key the auditor distrusts, retired by a key the walk trusts: an
463
+ // entry it signed before that retirement is accounted for, never
464
+ // verified. Only one whose signature verifies under the key, and whose
465
+ // key material the registry does not lie about: anything else under
466
+ // its id is bytes the database's writer wrote.
467
+ const bound = key.distrustSpan?.retiredAt ?? null;
468
+ if (bound !== null && isInstant(entry.createdAt) && rfc3339Ms(entry.createdAt) < instantMs(bound)
469
+ && !declaredAlgorithmLies(key) && verifyCoseSign1(envelopeBytes, key.spkiBase64) === 'ok') {
470
+ return accountedResult(scopeId, expectedPosition, `Entry written ${entry.createdAt} is signed by key ${entry.signingKeyId}, which distrustedKeys names and no signed key statement links to a pinned trust anchor, before ${bound}, when a key the walk trusts retired it: the distrust entry accounts for it. Not verified, and not a failure.`);
471
+ }
472
+ return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_UNANCHORED', `Key ${entry.signingKeyId} is not linked by any signed key statement to a pinned trust anchor.`);
473
+ }
474
+ if (key.trust === 'undecided') {
475
+ return fail(scopeId, expectedPosition, 'CHAIN_UNSUPPORTED_ALGORITHM', `Key ${entry.signingKeyId} is linked to a pinned anchor only through a key statement signed under an algorithm this host cannot compute, and ${describeUnsupportedAlgorithm(key.spkiBase64)}`, 'unsupported');
476
+ }
188
477
  }
189
478
  // Registry self-consistency: when the input surface declares an algorithm for
190
479
  // this key (vault_signing_keys.algorithm), it must agree with what the SPKI
191
480
  // key material commits to. A registry row that lies about its own key is the
192
481
  // signature of a mis-registered key (the pre-guard P-256 corruption shape) or
193
482
  // a rewritten registry, and nothing verified against it can be trusted.
194
- if (key.algorithm !== undefined) {
195
- const keyAlg = resolveKeyAlgorithm(key.spkiBase64);
196
- if (typeof keyAlg === 'object' &&
197
- keyAlg.name.toLowerCase() !== key.algorithm.toLowerCase()) {
198
- return fail(scopeId, expectedPosition, 'CHAIN_ALG_MISMATCH', `Key registry declares algorithm=${key.algorithm} for key ${entry.signingKeyId}, but the key material is ${keyAlg.name}.`);
199
- }
200
- }
201
- // Signed-kid binding (engine mirror: signing_key_drift). The row's
202
- // signingKeyId column selected the key above, but the column is a
203
- // denormalized convenience; the kid at protected-header label 4 is
204
- // signature-covered. A divergence means the column was rewritten after
205
- // signing, e.g. to point verification at a key the tamperer controls.
206
- const signedKid = extractKid(parts.protectedBstr);
207
- if (signedKid !== null && signedKid !== entry.signingKeyId) {
208
- return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_DRIFT', `Row signingKeyId=${entry.signingKeyId} does not match the signature-covered kid ${signedKid} in the protected header.`);
483
+ if (declaredAlgorithmLies(key)) {
484
+ return fail(scopeId, expectedPosition, 'CHAIN_ALG_MISMATCH', `Key registry declares algorithm=${key.algorithm} for key ${entry.signingKeyId}, but the key material is ${resolveKeyAlgorithm(key.spkiBase64).name}.`);
209
485
  }
210
- // Input-gated: temporal key-validity. Only when both the key window and the
211
- // entry write time are present (dump path).
212
- if (entry.createdAt && (key.activatedAt || key.retiredAt)) {
486
+ // Input-gated: temporal key-validity, whenever the key carries a window.
487
+ // Compared at millisecond precision, the precision of an entry's write time,
488
+ // truncating a microsecond window edge the way the engine does. The engine
489
+ // times every entry, so an entry with no time the walk can read cannot be
490
+ // placed inside the window, and fails closed rather than skipping it.
491
+ if (typeof key.activatedAt === 'string' || typeof key.retiredAt === 'string' || typeof key.distrustCutoff === 'string') {
213
492
  optionalChecks.key_temporal = 'applied';
493
+ // A window edge that is not RFC 3339 cannot place anything either, and
494
+ // the check fails closed on it rather than skipping that edge.
495
+ for (const [edge, value] of [['activatedAt', key.activatedAt], ['retiredAt', key.retiredAt], ['distrustCutoff', key.distrustCutoff]]) {
496
+ if (typeof value === 'string' && !isInstant(value)) {
497
+ return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', `Key ${entry.signingKeyId}'s ${edge} ${JSON.stringify(value)} is not an RFC 3339 instant, so the entry cannot be placed inside its window.`);
498
+ }
499
+ }
500
+ if (!isInstant(entry.createdAt)) {
501
+ return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', `Entry has no parseable createdAt, so it cannot be placed inside key ${entry.signingKeyId}'s window.`);
502
+ }
214
503
  const temporal = temporalKeyFailure(entry.createdAt, key);
215
504
  if (temporal) {
216
- return fail(scopeId, expectedPosition, temporal.code, temporal.detail);
505
+ // Past the instant the auditor's distrust entry gives, and before a key
506
+ // the walk trusts retired the key: accounted for, never verified. The
507
+ // signature below still has to verify.
508
+ const span = key.distrustSpan;
509
+ const written = rfc3339Ms(entry.createdAt);
510
+ if (temporal.code === 'CHAIN_KEY_EXPIRED' && span !== undefined && span.cutoff !== null && span.retiredAt !== null
511
+ && written >= instantMs(span.cutoff) && written < instantMs(span.retiredAt)) {
512
+ accountedPastCutoff = `Entry written ${entry.createdAt} is signed by key ${entry.signingKeyId} at or after ${span.cutoff}, the instant distrustedKeys gives for it, and before ${span.retiredAt}, when a key the walk trusts retired it: the distrust entry accounts for it. Not verified, and not a failure.`;
513
+ }
514
+ else {
515
+ return fail(scopeId, expectedPosition, temporal.code, temporal.detail);
516
+ }
217
517
  }
218
518
  }
219
519
  const outcome = verifyCoseSign1(envelopeBytes, key.spkiBase64);
220
520
  if (outcome === 'unsigned') {
221
- // An all-zero signature slot on an entry that CLAIMS a signing key. Under
222
- // a key policy this must fail: an auditor who demanded signed entries
223
- // (requireKeyId / requireOutOfBandKeys) must never count a zeroed
224
- // signature as green just because the policy gates above passed.
225
- if (options.requireKeyId || options.requireOutOfBandKeys) {
226
- return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', `Entry claims signingKeyId=${entry.signingKeyId} but carries an all-zero signature; this run requires signed entries (requireKeyId / requireOutOfBandKeys).`);
227
- }
228
- return { scopeId, position: expectedPosition, valid: true, signature: 'unsigned' };
521
+ // An all-zero signature slot on an entry that CLAIMS a signing key. The
522
+ // engine writes a key id only beside a signature it made with that key,
523
+ // and fails this shape `signature_invalid`, so it is a forged or wiped
524
+ // signature, never an unsigned entry. (A genuinely unsigned entry carries
525
+ // a null signingKeyId and is graded above.)
526
+ return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_INVALID', `Entry claims signingKeyId=${entry.signingKeyId} but carries an all-zero signature.`, 'invalid');
229
527
  }
230
528
  if (outcome === 'ok') {
529
+ if (accountedPastCutoff !== null)
530
+ return accountedResult(scopeId, expectedPosition, accountedPastCutoff);
231
531
  return { scopeId, position: expectedPosition, valid: true, signature: 'ok', keySource: key.source };
232
532
  }
233
533
  if (outcome === 'alg-mismatch') {
@@ -271,11 +571,11 @@ function checkOidcActor(oidc, payloadBstr, scopeId, position) {
271
571
  * investigations, and the activation side is the security-relevant one.
272
572
  */
273
573
  function temporalKeyFailure(createdAt, key) {
274
- const written = Date.parse(createdAt);
574
+ const written = rfc3339Ms(createdAt);
275
575
  if (Number.isNaN(written))
276
576
  return null;
277
- if (key.activatedAt) {
278
- const activated = Date.parse(key.activatedAt);
577
+ if (typeof key.activatedAt === 'string' && key.activatedAt) {
578
+ const activated = instantMs(key.activatedAt);
279
579
  if (!Number.isNaN(activated) && written < activated) {
280
580
  return {
281
581
  code: 'CHAIN_KEY_NOT_YET_ACTIVE',
@@ -283,8 +583,17 @@ function temporalKeyFailure(createdAt, key) {
283
583
  };
284
584
  }
285
585
  }
286
- if (key.retiredAt) {
287
- const retired = Date.parse(key.retiredAt);
586
+ if (typeof key.distrustCutoff === 'string' && key.distrustCutoff) {
587
+ const cutoff = instantMs(key.distrustCutoff);
588
+ if (!Number.isNaN(cutoff) && written > cutoff) {
589
+ return {
590
+ code: 'CHAIN_KEY_EXPIRED',
591
+ detail: `Entry written ${createdAt} postdates ${key.distrustCutoff}, the instant distrustedKeys (VAULT_DISTRUSTED_KEYS on the Server) gives for key ${key.keyId}; the key was not retired then.`,
592
+ };
593
+ }
594
+ }
595
+ if (typeof key.retiredAt === 'string' && key.retiredAt) {
596
+ const retired = instantMs(key.retiredAt);
288
597
  if (!Number.isNaN(retired) && written > retired) {
289
598
  return {
290
599
  code: 'CHAIN_KEY_EXPIRED',
@@ -9,6 +9,7 @@
9
9
  * CHAIN_* per-record (and per-org schema-event) hash-chain entry checks
10
10
  * CHECKPOINT_* vault checkpoint cross-check against the live chain
11
11
  * TENANT_* org_admin_reads Merkle log + signed tree heads
12
+ * KEY_* the vault key statements themselves (the key registry)
12
13
  * <bare> input/format-level failures that precede any chain walk
13
14
  *
14
15
  * Every code carries an actionable next step (`suggestion`) so a result is a
@@ -30,14 +31,58 @@
30
31
  * a retired/wrong-key policy hit is alertable apart
31
32
  * from a benign missing key.
32
33
  * - CHAIN_KEY_EXPIRED (new) temporal key-validity: entry written after the
33
- * signing key's retired_at.
34
+ * signing key's retired_at, or after its
35
+ * distrustedKeys cutoff.
34
36
  * - CHAIN_KEY_NOT_YET_ACTIVE entry written before the key's activated_at.
35
37
  * Split from CHAIN_KEY_EXPIRED so a consumer is
36
38
  * not told "expired" about a key that had not
37
39
  * started yet.
38
40
  * - CHAIN_EMPTY (new) a chain/vault with nothing to verify is a non-clean
39
41
  * verdict, never a silent pass.
42
+ *
43
+ * Later additions:
44
+ * - CHAIN_ENTRY_UNSIGNED engine mirror of `signature_missing`: an entry with
45
+ * no signing key id after a signed entry in its
46
+ * chain, or written at or after the earliest
47
+ * activatedAt in the key set. Earlier unsigned
48
+ * entries stay reduced coverage.
49
+ * - CHECKPOINT_UNSIGNED engine mirror of `checkpoint_unsigned`: the same
50
+ * instant, applied to an unsigned checkpoint.
51
+ * - TENANT_READ_LEAF_UNSIGNED and TENANT_CHECKPOINT_UNSIGNED the same two
52
+ * rules on the org_admin_reads log (engine
53
+ * `leaf_signature_missing`, `checkpoint_unsigned`).
54
+ * - CHAIN_SIGNING_KEY_UNANCHORED engine mirror of `signing_key_unanchored`:
55
+ * the entry's key is not linked by signed key
56
+ * statements to a pinned trust anchor. With
57
+ * CHECKPOINT_KEY_UNANCHORED,
58
+ * TENANT_READ_KEY_UNANCHORED and
59
+ * TENANT_CHECKPOINT_KEY_UNANCHORED for the
60
+ * engine's `checkpoint_key_unanchored` and
61
+ * `leaf_key_unanchored`.
62
+ * - KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID, CHAIN_KEY_WINDOW_DRIFT
63
+ * engine mirrors of the key registry findings
64
+ * `key_statement_invalid`, `key_closure_invalid`
65
+ * and `key_window_drift`. They are about the
66
+ * registry, not about any one entry.
67
+ * - CHECKPOINT_CLAIM_MISMATCH, TENANT_READ_CLAIM_MISMATCH,
68
+ * TENANT_CHECKPOINT_CLAIM_MISMATCH engine mirrors of the vault's
69
+ * `checkpoint_claim_mismatch` and the read log's
70
+ * `leaf_claim_mismatch` and
71
+ * `checkpoint_claim_mismatch`: the claim signed
72
+ * inside the envelope does not decode, or says
73
+ * something the row's columns do not.
74
+ *
75
+ * Server-side cert re-checks are not mirrored here. The engine's chain
76
+ * verification also reports `cert_missing`, `cert_actor_drift`,
77
+ * `cert_window_drift`, `cert_expired` and `agent_signature_invalid`, by
78
+ * comparing what an entry sealed in `predicate.on_behalf_of.cert` against the
79
+ * live `ephemeral_certs` row. Neither the export nor the dump carries that
80
+ * table, so an offline verifier cannot reproduce those comparisons, and it
81
+ * does not need to: it trusts only the signed bytes, which already fix the
82
+ * sealed cert id, thumbprint and expiry. The one cert-related check that can
83
+ * run offline is the agent signature, and only when the caller supplies the
84
+ * cert's public key (CHAIN_AGENT_SIGNATURE_INVALID below).
40
85
  */
41
- export type FailureCode = 'UNSUPPORTED_FORMAT' | 'CHAIN_EMPTY' | 'CHAIN_POSITION_GAP' | 'CHAIN_GENESIS_INVALID' | 'CHAIN_LINK_BROKEN' | 'CHAIN_HASH_MISMATCH' | 'CHAIN_MALFORMED_ENTRY' | 'CHAIN_COSE_DECODE_FAILED' | 'CHAIN_COSE_HEADER_MISMATCH' | 'CHAIN_PAYLOAD_BINDING_MISMATCH' | 'CHAIN_OIDC_ACTOR_MISMATCH' | 'CHAIN_SIGNATURE_INVALID' | 'CHAIN_SIGNATURE_MISSING_KEY' | 'CHAIN_KEY_POLICY_VIOLATION' | 'CHAIN_KEY_EXPIRED' | 'CHAIN_KEY_NOT_YET_ACTIVE' | 'CHAIN_ALG_MISMATCH' | 'CHAIN_UNSUPPORTED_ALGORITHM' | 'CHAIN_SIGNING_KEY_DRIFT' | 'CHECKPOINT_ROW_MISSING' | 'CHECKPOINT_HASH_MISMATCH' | 'CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_READ_LEAF_HASH_MISMATCH' | 'TENANT_READ_LEAF_INDEX_GAP' | 'TENANT_READ_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH' | 'TENANT_CHECKPOINT_ROOT_MISMATCH' | 'TENANT_CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_FORK';
86
+ export type FailureCode = 'UNSUPPORTED_FORMAT' | 'CHAIN_EMPTY' | 'CHAIN_POSITION_GAP' | 'CHAIN_GENESIS_INVALID' | 'CHAIN_LINK_BROKEN' | 'CHAIN_HASH_MISMATCH' | 'CHAIN_MALFORMED_ENTRY' | 'CHAIN_COSE_DECODE_FAILED' | 'CHAIN_COSE_HEADER_MISMATCH' | 'CHAIN_PAYLOAD_BINDING_MISMATCH' | 'CHAIN_OIDC_ACTOR_MISMATCH' | 'CHAIN_SIGNATURE_INVALID' | 'CHAIN_SIGNATURE_MISSING_KEY' | 'CHAIN_KEY_POLICY_VIOLATION' | 'CHAIN_KEY_EXPIRED' | 'CHAIN_KEY_NOT_YET_ACTIVE' | 'CHAIN_ALG_MISMATCH' | 'CHAIN_UNSUPPORTED_ALGORITHM' | 'CHAIN_SIGNING_KEY_DRIFT' | 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH' | 'CHAIN_AGENT_SIGNATURE_INVALID' | 'CHAIN_ENTRY_UNSIGNED' | 'CHAIN_SIGNING_KEY_UNANCHORED' | 'CHAIN_KEY_WINDOW_DRIFT' | 'CHECKPOINT_ROW_MISSING' | 'CHECKPOINT_HASH_MISMATCH' | 'CHECKPOINT_SIGNATURE_INVALID' | 'CHECKPOINT_UNSIGNED' | 'CHECKPOINT_KEY_UNANCHORED' | 'CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_READ_LEAF_HASH_MISMATCH' | 'TENANT_READ_LEAF_INDEX_GAP' | 'TENANT_READ_SIGNATURE_INVALID' | 'TENANT_READ_LEAF_UNSIGNED' | 'TENANT_READ_KEY_UNANCHORED' | 'TENANT_READ_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH' | 'TENANT_CHECKPOINT_ROOT_MISMATCH' | 'TENANT_CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_UNSIGNED' | 'TENANT_CHECKPOINT_KEY_UNANCHORED' | 'TENANT_CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_FORK' | 'KEY_STATEMENT_INVALID' | 'KEY_CLOSURE_INVALID';
42
87
  /** The actionable next step for a failure code. */
43
88
  export declare function suggestion(code: FailureCode): string;