@agledger/verify-core 1.5.0 → 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
@@ -17,7 +17,8 @@
17
17
  * protected-header chain-claim cross-check, and the Ed25519 signature.
18
18
  * - INPUT-GATED (only when the normalized entry, or the caller, supplies the
19
19
  * inputs): binding-integrity, OIDC-actor cross-check, temporal
20
- * key-validity, and the agent-signature re-check. The first three run on
20
+ * key-validity, the agent-signature re-check, and key anchoring (a
21
+ * registry marked by `applyKeyTrust`). The first three run on
21
22
  * the dump and on any export from an engine that ships the row fields
22
23
  * (>= v0.26.x). The agent-signature check needs the cert's public key,
23
24
  * which neither surface carries, so it runs only when the caller passes
@@ -25,14 +26,29 @@
25
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.
30
36
  */
31
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.
44
+ */
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
  }
38
54
  /**
@@ -57,14 +73,87 @@ export function buildAgentKeyRegistry(jwks) {
57
73
  });
58
74
  return map;
59
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
+ }
60
145
  /**
61
146
  * Verify a single hash chain. `entries` are all the entries for one scope; they
62
147
  * are sorted by chainPosition internally (so a reordered export array still
63
148
  * validates the true chain; tampering surfaces through the hash links).
64
149
  */
65
150
  export function verifyChain(entries, keys, options = {}) {
151
+ assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'signingSince']);
66
152
  const scopeId = entries[0]?.scopeId ?? '(empty)';
67
- 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);
68
157
  const entryResults = [];
69
158
  const coverage = { signed: 0, unsigned: 0, skipped: 0, total: sorted.length };
70
159
  const optionalChecks = {
@@ -73,11 +162,13 @@ export function verifyChain(entries, keys, options = {}) {
73
162
  actor_attribution: 'skipped_no_input',
74
163
  key_temporal: 'skipped_no_input',
75
164
  agent_signature: 'skipped_no_input',
165
+ key_anchoring: 'skipped_no_input',
76
166
  };
77
- const keyProvenance = { outOfBand: 0, embedded: 0 };
167
+ const keyProvenance = { supplied: 0, embedded: 0 };
78
168
  const agentSignatures = { present: 0, verified: 0 };
79
169
  let verifiedEntries = 0;
80
170
  let brokenAt;
171
+ const accounted = [];
81
172
  if (sorted.length === 0) {
82
173
  return {
83
174
  scopeId,
@@ -86,22 +177,48 @@ export function verifyChain(entries, keys, options = {}) {
86
177
  verifiedEntries: 0,
87
178
  brokenAt: { position: 0, code: 'CHAIN_EMPTY', detail: 'No entries to verify.' },
88
179
  entries: [],
180
+ accounted: [],
89
181
  signatureCoverage: coverage,
90
182
  optionalChecks,
91
183
  keyProvenance,
92
184
  agentSignatures,
93
185
  };
94
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 };
95
198
  let previousHash = null;
96
199
  for (let i = 0; i < sorted.length; i++) {
97
200
  const entry = sorted[i];
98
201
  const expectedPosition = i + 1;
99
- let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks);
100
- if (result.valid) {
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) {
101
208
  result = checkAgentSignature(entry, result, options.agentKeys, optionalChecks, agentSignatures);
102
209
  }
103
210
  entryResults.push(result);
104
- 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)
105
222
  verifiedEntries++;
106
223
  else if (!brokenAt && result.failure) {
107
224
  brokenAt = { position: result.position, code: result.failure.code, detail: result.failure.detail };
@@ -109,8 +226,8 @@ export function verifyChain(entries, keys, options = {}) {
109
226
  switch (result.signature) {
110
227
  case 'ok':
111
228
  coverage.signed++;
112
- if (result.keySource === 'out-of-band')
113
- keyProvenance.outOfBand++;
229
+ if (result.keySource === 'supplied')
230
+ keyProvenance.supplied++;
114
231
  else if (result.keySource === 'embedded')
115
232
  keyProvenance.embedded++;
116
233
  break;
@@ -126,13 +243,19 @@ export function verifyChain(entries, keys, options = {}) {
126
243
  }
127
244
  previousHash = entry.payloadHash;
128
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
+ }
129
251
  return {
130
252
  scopeId,
131
- valid: verifiedEntries === sorted.length,
253
+ valid: verifiedEntries + accounted.length === sorted.length,
132
254
  totalEntries: sorted.length,
133
255
  verifiedEntries,
134
256
  brokenAt,
135
257
  entries: entryResults,
258
+ accounted,
136
259
  signatureCoverage: coverage,
137
260
  optionalChecks,
138
261
  keyProvenance,
@@ -176,16 +299,26 @@ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
176
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).`
177
300
  : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`, result.signature);
178
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
+ }
179
312
  function fail(scopeId, position, code, detail, signature = 'not-checked') {
180
313
  return { scopeId, position, valid: false, failure: { code, detail }, signature };
181
314
  }
182
- function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks) {
315
+ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
183
316
  const { scopeId } = entry;
184
317
  if (entry.chainPosition !== expectedPosition) {
185
318
  return fail(scopeId, entry.chainPosition, 'CHAIN_POSITION_GAP', `Expected chainPosition ${expectedPosition}, got ${entry.chainPosition}.`);
186
319
  }
187
- if (!entry.coseSign1 || !entry.payloadHash) {
188
- 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.');
189
322
  }
190
323
  const envelopeBytes = Buffer.from(entry.coseSign1, 'base64');
191
324
  const recomputed = sha256Hex(envelopeBytes);
@@ -268,12 +401,31 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
268
401
  // and fails CHAIN_SIGNATURE_MISSING_KEY below: a truthiness shortcut here
269
402
  // would let a tampered signingKeyId:"" row skip its signature check.
270
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
+ }
271
423
  // Fail closed under a key policy: a high-assurance run that requires a
272
- // 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
273
425
  // entry as valid; otherwise an attacker forges an entry, nulls its
274
426
  // signingKeyId, and slips past the policy the auditor explicitly set.
275
- if (options.requireKeyId || options.requireOutOfBandKeys) {
276
- 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).');
277
429
  }
278
430
  return { scopeId, position: expectedPosition, valid: true, signature: 'skipped' };
279
431
  }
@@ -284,51 +436,98 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
284
436
  if (!key) {
285
437
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_MISSING_KEY', `No public key available for signingKeyId=${entry.signingKeyId}.`);
286
438
  }
287
- if (options.requireOutOfBandKeys && key.source !== 'out-of-band') {
288
- 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
+ }
289
477
  }
290
478
  // Registry self-consistency: when the input surface declares an algorithm for
291
479
  // this key (vault_signing_keys.algorithm), it must agree with what the SPKI
292
480
  // key material commits to. A registry row that lies about its own key is the
293
481
  // signature of a mis-registered key (the pre-guard P-256 corruption shape) or
294
482
  // a rewritten registry, and nothing verified against it can be trusted.
295
- if (key.algorithm !== undefined) {
296
- const keyAlg = resolveKeyAlgorithm(key.spkiBase64);
297
- if (typeof keyAlg === 'object' &&
298
- keyAlg.name.toLowerCase() !== key.algorithm.toLowerCase()) {
299
- return fail(scopeId, expectedPosition, 'CHAIN_ALG_MISMATCH', `Key registry declares algorithm=${key.algorithm} for key ${entry.signingKeyId}, but the key material is ${keyAlg.name}.`);
300
- }
301
- }
302
- // Signed-kid binding (engine mirror: signing_key_drift). The row's
303
- // signingKeyId column selected the key above, but the column is a
304
- // denormalized convenience; the kid at protected-header label 4 is
305
- // signature-covered. A divergence means the column was rewritten after
306
- // signing, e.g. to point verification at a key the tamperer controls.
307
- const signedKid = extractKid(parts.protectedBstr);
308
- if (signedKid !== null && signedKid !== entry.signingKeyId) {
309
- 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}.`);
310
485
  }
311
- // Input-gated: temporal key-validity. Only when both the key window and the
312
- // entry write time are present (dump path).
313
- 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') {
314
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
+ }
315
503
  const temporal = temporalKeyFailure(entry.createdAt, key);
316
504
  if (temporal) {
317
- 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
+ }
318
517
  }
319
518
  }
320
519
  const outcome = verifyCoseSign1(envelopeBytes, key.spkiBase64);
321
520
  if (outcome === 'unsigned') {
322
- // An all-zero signature slot on an entry that CLAIMS a signing key. Under
323
- // a key policy this must fail: an auditor who demanded signed entries
324
- // (requireKeyId / requireOutOfBandKeys) must never count a zeroed
325
- // signature as green just because the policy gates above passed.
326
- if (options.requireKeyId || options.requireOutOfBandKeys) {
327
- 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).`);
328
- }
329
- 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');
330
527
  }
331
528
  if (outcome === 'ok') {
529
+ if (accountedPastCutoff !== null)
530
+ return accountedResult(scopeId, expectedPosition, accountedPastCutoff);
332
531
  return { scopeId, position: expectedPosition, valid: true, signature: 'ok', keySource: key.source };
333
532
  }
334
533
  if (outcome === 'alg-mismatch') {
@@ -372,11 +571,11 @@ function checkOidcActor(oidc, payloadBstr, scopeId, position) {
372
571
  * investigations, and the activation side is the security-relevant one.
373
572
  */
374
573
  function temporalKeyFailure(createdAt, key) {
375
- const written = Date.parse(createdAt);
574
+ const written = rfc3339Ms(createdAt);
376
575
  if (Number.isNaN(written))
377
576
  return null;
378
- if (key.activatedAt) {
379
- const activated = Date.parse(key.activatedAt);
577
+ if (typeof key.activatedAt === 'string' && key.activatedAt) {
578
+ const activated = instantMs(key.activatedAt);
380
579
  if (!Number.isNaN(activated) && written < activated) {
381
580
  return {
382
581
  code: 'CHAIN_KEY_NOT_YET_ACTIVE',
@@ -384,8 +583,17 @@ function temporalKeyFailure(createdAt, key) {
384
583
  };
385
584
  }
386
585
  }
387
- if (key.retiredAt) {
388
- 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);
389
597
  if (!Number.isNaN(retired) && written > retired) {
390
598
  return {
391
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,7 +31,8 @@
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
@@ -38,6 +40,38 @@
38
40
  * - CHAIN_EMPTY (new) a chain/vault with nothing to verify is a non-clean
39
41
  * verdict, never a silent pass.
40
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
+ *
41
75
  * Server-side cert re-checks are not mirrored here. The engine's chain
42
76
  * verification also reports `cert_missing`, `cert_actor_drift`,
43
77
  * `cert_window_drift`, `cert_expired` and `agent_signature_invalid`, by
@@ -49,6 +83,6 @@
49
83
  * run offline is the agent signature, and only when the caller supplies the
50
84
  * cert's public key (CHAIN_AGENT_SIGNATURE_INVALID below).
51
85
  */
52
- 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' | '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';
53
87
  /** The actionable next step for a failure code. */
54
88
  export declare function suggestion(code: FailureCode): string;