@agledger/verify-core 1.5.0 → 2.1.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,31 @@
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 { canonicalizeJson, checkFederationWire, extractFederationWire } from './federation-wire.js';
39
+ import { createHash } from 'node:crypto';
40
+ import { instantMs, rfc3339Ms } from './instant.js';
41
+ import { assertKnownOptions } from './options.js';
42
+ /**
43
+ * Index keys by key id. A key whose `spkiBase64` is not a non-empty string
44
+ * carries no key material (a registry row with its public key nulled), so it
45
+ * is left out: an entry naming it fails CHAIN_SIGNATURE_MISSING_KEY.
46
+ */
32
47
  export function buildKeyRegistry(keys) {
33
48
  const map = new Map();
34
- for (const k of keys)
49
+ for (const k of keys) {
50
+ if (typeof k.spkiBase64 !== 'string' || k.spkiBase64 === '')
51
+ continue;
35
52
  map.set(k.keyId, k);
53
+ }
36
54
  return map;
37
55
  }
38
56
  /**
@@ -57,14 +75,87 @@ export function buildAgentKeyRegistry(jwks) {
57
75
  });
58
76
  return map;
59
77
  }
78
+ /** The code an {@link AccountedEntry} carries. Not a {@link FailureCode}: it never fails a verdict. */
79
+ export const ACCOUNTED_ENTRY_CODE = 'CHAIN_SIGNED_BY_DISTRUSTED_KEY';
80
+ const PLATFORM_OPS_RECORD_ID = '00000000-0000-0000-0000-000000000000';
81
+ /** Name a chain scope (a record id or a dump `chain_key`) as {@link AccountedEntry} does. */
82
+ export function chainOfScope(scopeId) {
83
+ if (scopeId.startsWith('schema:')) {
84
+ const org = scopeId.slice('schema:'.length);
85
+ return { chain: 'schema', recordId: null, orgId: org === '__platform__' ? null : org };
86
+ }
87
+ if (scopeId.toLowerCase() === PLATFORM_OPS_RECORD_ID)
88
+ return { chain: 'admin', recordId: null, orgId: null };
89
+ return { chain: 'record', recordId: scopeId, orgId: null };
90
+ }
91
+ /**
92
+ * The earliest `activatedAt` among `keys`, as the ISO string it was given in,
93
+ * or `null` when no key carries a parseable one. This is the instant from
94
+ * which the engine treats every chain entry and checkpoint as required to be
95
+ * signed; pass every key the verifier knows, retired ones included, since the
96
+ * engine reads it as `min(activated_at)` over its whole key registry.
97
+ */
98
+ export function earliestKeyActivation(keys) {
99
+ let earliest = null;
100
+ for (const k of keys) {
101
+ if (typeof k.activatedAt !== 'string')
102
+ continue;
103
+ const at = instantMs(k.activatedAt);
104
+ if (Number.isNaN(at))
105
+ continue;
106
+ if (earliest === null || at < earliest.at)
107
+ earliest = { at, iso: k.activatedAt };
108
+ }
109
+ return earliest?.iso ?? null;
110
+ }
111
+ /**
112
+ * Whether a row with no signing key id, written at `writtenAt`, falls inside
113
+ * the era in which the install signs everything: at or after `signingSince`
114
+ * (see `earliestKeyActivation`). This is the rule for an unsigned checkpoint
115
+ * (CHECKPOINT_UNSIGNED) and an unsigned read-log leaf or tree head, and the
116
+ * time half of the rule for an unsigned entry (CHAIN_ENTRY_UNSIGNED).
117
+ *
118
+ * False when `signingSince` is absent or unparseable: with no instant from
119
+ * which the install signs, nothing has to be signed. True when `signingSince`
120
+ * is known and `writtenAt` is missing or not strict RFC 3339: the engine times every
121
+ * row, so a row with no readable time was edited, and it cannot be placed
122
+ * before signing began. It fails closed rather than reading as early history.
123
+ */
124
+ export function writtenWhileSigning(writtenAt, signingSince) {
125
+ if (typeof signingSince !== 'string')
126
+ return false;
127
+ const since = instantMs(signingSince);
128
+ if (Number.isNaN(since))
129
+ return false;
130
+ const written = typeof writtenAt === 'string' ? rfc3339Ms(writtenAt) : Number.NaN;
131
+ if (Number.isNaN(written))
132
+ return true;
133
+ return written >= since;
134
+ }
135
+ /** Whether `value` is a strict RFC 3339 instant the walk can place. */
136
+ function isInstant(value) {
137
+ return typeof value === 'string' && !Number.isNaN(rfc3339Ms(value));
138
+ }
139
+ /**
140
+ * The order the walk sorts entries in: by `chainPosition`, an entry whose
141
+ * position is not a safe integer after every one whose is, ties in input
142
+ * order. Such an entry then fails CHAIN_POSITION_GAP at its place.
143
+ */
144
+ function positionKey(position) {
145
+ return Number.isSafeInteger(position) ? position : Number.POSITIVE_INFINITY;
146
+ }
60
147
  /**
61
148
  * Verify a single hash chain. `entries` are all the entries for one scope; they
62
149
  * are sorted by chainPosition internally (so a reordered export array still
63
150
  * validates the true chain; tampering surfaces through the hash links).
64
151
  */
65
152
  export function verifyChain(entries, keys, options = {}) {
153
+ assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'federationKeys', 'signingSince']);
66
154
  const scopeId = entries[0]?.scopeId ?? '(empty)';
67
- const sorted = [...entries].sort((a, b) => a.chainPosition - b.chainPosition);
155
+ const sorted = entries
156
+ .map((entry, at) => ({ entry, at, key: positionKey(entry.chainPosition) }))
157
+ .sort((a, b) => (a.key === b.key ? a.at - b.at : a.key < b.key ? -1 : 1))
158
+ .map(({ entry }) => entry);
68
159
  const entryResults = [];
69
160
  const coverage = { signed: 0, unsigned: 0, skipped: 0, total: sorted.length };
70
161
  const optionalChecks = {
@@ -73,11 +164,17 @@ export function verifyChain(entries, keys, options = {}) {
73
164
  actor_attribution: 'skipped_no_input',
74
165
  key_temporal: 'skipped_no_input',
75
166
  agent_signature: 'skipped_no_input',
167
+ key_anchoring: 'skipped_no_input',
168
+ federation_wire: 'skipped_no_input',
169
+ evidence_binding: 'skipped_no_input',
76
170
  };
77
- const keyProvenance = { outOfBand: 0, embedded: 0 };
171
+ const keyProvenance = { supplied: 0, embedded: 0 };
78
172
  const agentSignatures = { present: 0, verified: 0 };
173
+ const federationWire = { present: 0, verified: 0, failed: 0, afterRetirement: 0 };
174
+ const evidenceBinding = { present: 0, verified: 0, clientHashed: 0, failed: 0 };
79
175
  let verifiedEntries = 0;
80
176
  let brokenAt;
177
+ const accounted = [];
81
178
  if (sorted.length === 0) {
82
179
  return {
83
180
  scopeId,
@@ -86,22 +183,56 @@ export function verifyChain(entries, keys, options = {}) {
86
183
  verifiedEntries: 0,
87
184
  brokenAt: { position: 0, code: 'CHAIN_EMPTY', detail: 'No entries to verify.' },
88
185
  entries: [],
186
+ accounted: [],
89
187
  signatureCoverage: coverage,
90
188
  optionalChecks,
91
189
  keyProvenance,
92
190
  agentSignatures,
191
+ federationWire,
192
+ evidenceBinding,
93
193
  };
94
194
  }
195
+ let signingSince;
196
+ if (options.signingSince === undefined) {
197
+ signingSince = earliestKeyActivation(keys.values());
198
+ }
199
+ else {
200
+ signingSince = options.signingSince;
201
+ if (signingSince !== null && Number.isNaN(instantMs(signingSince))) {
202
+ throw new TypeError(`signingSince must be an RFC 3339 instant or null (got ${JSON.stringify(signingSince)}).`);
203
+ }
204
+ }
205
+ const mustSign = { signedBefore: false, signingSince };
95
206
  let previousHash = null;
96
207
  for (let i = 0; i < sorted.length; i++) {
97
208
  const entry = sorted[i];
98
209
  const expectedPosition = i + 1;
99
- let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks);
100
- if (result.valid) {
210
+ let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks, mustSign);
211
+ // As the engine's walk does: any earlier row naming a key, whatever its own
212
+ // verdict, means this chain was already being signed.
213
+ if (entry.signingKeyId !== null)
214
+ mustSign.signedBefore = true;
215
+ if (result.valid && result.accounted === undefined) {
101
216
  result = checkAgentSignature(entry, result, options.agentKeys, optionalChecks, agentSignatures);
102
217
  }
218
+ if (result.valid && result.accounted === undefined && entry.binding !== undefined) {
219
+ result = checkSealedFederationWire(entry, result, options.federationKeys, optionalChecks, federationWire);
220
+ }
221
+ if (result.valid && result.accounted === undefined && entry.inlinedEvidence !== undefined) {
222
+ result = checkInlinedEvidence(entry, result, optionalChecks, evidenceBinding);
223
+ }
103
224
  entryResults.push(result);
104
- if (result.valid)
225
+ if (result.accounted !== undefined) {
226
+ accounted.push({
227
+ code: result.accounted.code,
228
+ ...chainOfScope(scopeId),
229
+ scopeId,
230
+ position: result.position,
231
+ keyId: entry.signingKeyId ?? '',
232
+ detail: result.accounted.detail,
233
+ });
234
+ }
235
+ else if (result.valid)
105
236
  verifiedEntries++;
106
237
  else if (!brokenAt && result.failure) {
107
238
  brokenAt = { position: result.position, code: result.failure.code, detail: result.failure.detail };
@@ -109,8 +240,8 @@ export function verifyChain(entries, keys, options = {}) {
109
240
  switch (result.signature) {
110
241
  case 'ok':
111
242
  coverage.signed++;
112
- if (result.keySource === 'out-of-band')
113
- keyProvenance.outOfBand++;
243
+ if (result.keySource === 'supplied')
244
+ keyProvenance.supplied++;
114
245
  else if (result.keySource === 'embedded')
115
246
  keyProvenance.embedded++;
116
247
  break;
@@ -126,18 +257,104 @@ export function verifyChain(entries, keys, options = {}) {
126
257
  }
127
258
  previousHash = entry.payloadHash;
128
259
  }
260
+ // The caller walked the key statements (every key carries a verdict), but no
261
+ // entry got as far as the anchoring check.
262
+ if (optionalChecks.key_anchoring === 'skipped_no_input' && [...keys.values()].some((k) => k.trust !== undefined)) {
263
+ optionalChecks.key_anchoring = 'not_checked';
264
+ }
129
265
  return {
130
266
  scopeId,
131
- valid: verifiedEntries === sorted.length,
267
+ valid: verifiedEntries + accounted.length === sorted.length,
132
268
  totalEntries: sorted.length,
133
269
  verifiedEntries,
134
270
  brokenAt,
135
271
  entries: entryResults,
272
+ accounted,
136
273
  signatureCoverage: coverage,
137
274
  optionalChecks,
138
275
  keyProvenance,
139
276
  agentSignatures,
277
+ federationWire,
278
+ evidenceBinding,
279
+ };
280
+ }
281
+ /** The payload field each entry type signs an inlined evidence body's hash under. */
282
+ const EVIDENCE_HASH_FIELD = {
283
+ COMPLETION_SUBMITTED: 'evidenceHash',
284
+ DISPUTE_EVIDENCE: 'payloadHash',
285
+ };
286
+ /**
287
+ * Re-bind an inlined evidence body to the hash its entry signs, on an entry
288
+ * that already passed every other check (so `binding.payload` is what the
289
+ * Server signed): SHA-256 hex over the RFC 8785 form of the body, the
290
+ * Server's `hashPayload`, against `payload.evidenceHash` (completion) or
291
+ * `payload.payloadHash` (dispute evidence). An encrypted-mode completion
292
+ * signs a hash its submitter computed over the cleartext, and the export
293
+ * inlines the ciphertext, so it is counted and left unbound.
294
+ */
295
+ function checkInlinedEvidence(entry, result, optionalChecks, counts) {
296
+ optionalChecks.evidence_binding = 'applied';
297
+ counts.present++;
298
+ const failed = (detail) => {
299
+ counts.failed++;
300
+ return failAfterSignature(entry, result, 'CHAIN_EVIDENCE_BINDING_MISMATCH', detail);
140
301
  };
302
+ const body = entry.inlinedEvidence.value;
303
+ if (entry.binding === undefined) {
304
+ return failed('The entry inlines an evidence body but carries no payload, so no signed hash binds the body to the chain.');
305
+ }
306
+ const { entryType, payload } = entry.binding;
307
+ const field = EVIDENCE_HASH_FIELD[entryType];
308
+ if (field === undefined) {
309
+ return failed(`A ${entryType} entry inlines an evidence body. The Server inlines evidence only on COMPLETION_SUBMITTED and DISPUTE_EVIDENCE entries, and nothing this entry signs binds a body.`);
310
+ }
311
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
312
+ return failed(`The inlined evidence is ${body === null ? 'null' : Array.isArray(body) ? 'an array' : typeof body}, not the JSON object the entry's payload.${field} was computed over.`);
313
+ }
314
+ const signed = payload[field];
315
+ if (typeof signed !== 'string' || !/^[0-9a-f]{64}$/i.test(signed)) {
316
+ return failed(`The entry inlines an evidence body but signs no payload.${field} to bind it to.`);
317
+ }
318
+ if (entryType === 'COMPLETION_SUBMITTED' && payload.verifiedBy === 'client') {
319
+ counts.clientHashed++;
320
+ return result;
321
+ }
322
+ const digest = createHash('sha256').update(canonicalizeJson(body), 'utf8').digest('hex');
323
+ if (digest !== signed.toLowerCase()) {
324
+ return failed(`The inlined evidence body hashes to ${digest} under RFC 8785 and SHA-256, and the entry signs payload.${field} ${signed.toLowerCase()}: the body was edited after export, or is not the one submitted.`);
325
+ }
326
+ counts.verified++;
327
+ return result;
328
+ }
329
+ /**
330
+ * The sealed federation message on an entry that already passed every other
331
+ * check (so `binding.payload` is what the receiver signed): its body hash,
332
+ * its agreement with the entry, and, under a supplied key for the sending
333
+ * hub, its signature. See `federation-wire.ts`.
334
+ */
335
+ function checkSealedFederationWire(entry, result, federationKeys, optionalChecks, counts) {
336
+ if (entry.binding === undefined)
337
+ return result;
338
+ const wire = extractFederationWire(entry.binding.payload);
339
+ if (wire === null)
340
+ return result;
341
+ optionalChecks.federation_wire = 'applied';
342
+ if (wire === 'malformed') {
343
+ return failAfterSignature(entry, result, 'CHAIN_FEDERATION_WIRE_INVALID', 'payload.wire is present but is not a sealed federation message (an object with scheme, senderHubId, senderPublicKey, recipientHubId, method, path, bodyHash, timestamp, nonce, signature and an object body).');
344
+ }
345
+ counts.present++;
346
+ const outcome = checkFederationWire(entry.binding.entryType, entry.binding.recordId, entry.binding.payload, wire, federationKeys);
347
+ if (outcome.outcome === 'ok') {
348
+ if (outcome.signatureChecked)
349
+ counts.verified++;
350
+ if (outcome.afterRetirement)
351
+ counts.afterRetirement++;
352
+ return result;
353
+ }
354
+ if (outcome.outcome === 'unchecked')
355
+ return result;
356
+ counts.failed++;
357
+ return failAfterSignature(entry, result, outcome.outcome === 'unsupported' ? 'CHAIN_UNSUPPORTED_ALGORITHM' : 'CHAIN_FEDERATION_WIRE_INVALID', outcome.detail);
141
358
  }
142
359
  /**
143
360
  * Offline re-check of a sealed agent signature, on an entry that already
@@ -170,22 +387,40 @@ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
170
387
  }
171
388
  const certLabel = claim.certId ?? claim.certThumbprint;
172
389
  if (outcome === 'unsupported') {
173
- 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);
390
+ return failAfterSignature(entry, result, '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.`);
174
391
  }
175
- return fail(entry.scopeId, result.position, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
392
+ return failAfterSignature(entry, result, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
176
393
  ? `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
- : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`, result.signature);
394
+ : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`);
395
+ }
396
+ function accountedResult(scopeId, position, detail) {
397
+ return { scopeId, position, valid: true, accounted: { code: ACCOUNTED_ENTRY_CODE, detail }, signature: 'accounted' };
398
+ }
399
+ /** The registry declares an algorithm for the key that its key material does not commit to. */
400
+ function declaredAlgorithmLies(key) {
401
+ if (typeof key.algorithm !== 'string')
402
+ return false;
403
+ const keyAlg = resolveKeyAlgorithm(key.spkiBase64);
404
+ return typeof keyAlg === 'object' && keyAlg.name.toLowerCase() !== key.algorithm.toLowerCase();
405
+ }
406
+ function fail(scopeId, position, code, detail, signature = 'not-checked', keySource) {
407
+ return { scopeId, position, valid: false, failure: { code, detail }, signature, ...(keySource !== undefined ? { keySource } : {}) };
178
408
  }
179
- function fail(scopeId, position, code, detail, signature = 'not-checked') {
180
- return { scopeId, position, valid: false, failure: { code, detail }, signature };
409
+ /**
410
+ * Fail an entry a check after the signature check refused: it keeps the
411
+ * signature state and the key it verified under, so `keyProvenance` still
412
+ * counts every signed entry (`signed = supplied + embedded`).
413
+ */
414
+ function failAfterSignature(entry, result, code, detail) {
415
+ return fail(entry.scopeId, result.position, code, detail, result.signature, result.keySource);
181
416
  }
182
- function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks) {
417
+ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
183
418
  const { scopeId } = entry;
184
419
  if (entry.chainPosition !== expectedPosition) {
185
420
  return fail(scopeId, entry.chainPosition, 'CHAIN_POSITION_GAP', `Expected chainPosition ${expectedPosition}, got ${entry.chainPosition}.`);
186
421
  }
187
- if (!entry.coseSign1 || !entry.payloadHash) {
188
- return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', 'Entry is missing coseSign1 or payloadHash.');
422
+ if (typeof entry.coseSign1 !== 'string' || typeof entry.payloadHash !== 'string' || !entry.coseSign1 || !entry.payloadHash) {
423
+ return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', 'Entry is missing coseSign1 or payloadHash, or carries one that is not a string.');
189
424
  }
190
425
  const envelopeBytes = Buffer.from(entry.coseSign1, 'base64');
191
426
  const recomputed = sha256Hex(envelopeBytes);
@@ -268,12 +503,31 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
268
503
  // and fails CHAIN_SIGNATURE_MISSING_KEY below: a truthiness shortcut here
269
504
  // would let a tampered signingKeyId:"" row skip its signature check.
270
505
  if (entry.signingKeyId === null) {
506
+ // Engine mirror of `signature_missing`. An unsigned entry is reduced
507
+ // coverage only where the install had not yet begun to sign: before any
508
+ // signed entry in this chain, and before the earliest key activation.
509
+ // Anywhere else no process of the install could have written it; it is
510
+ // what a writer holding no key leaves on the tip, or a signed row whose
511
+ // key id was nulled. Checked ahead of the caller's key policy because it
512
+ // is evidence about the chain itself, whatever policy the run applies.
513
+ if (mustSign.signedBefore) {
514
+ return fail(scopeId, expectedPosition, 'CHAIN_ENTRY_UNSIGNED', 'Entry has no signingKeyId but follows a signed entry in the same chain.');
515
+ }
516
+ // The engine times every entry. Without a time the walk can read, an
517
+ // unsigned entry cannot be placed before signing began, so it is not
518
+ // early history: it fails closed.
519
+ if (mustSign.signingSince !== null && !isInstant(entry.createdAt)) {
520
+ 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}.`);
521
+ }
522
+ if (writtenWhileSigning(entry.createdAt, mustSign.signingSince)) {
523
+ 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}.`);
524
+ }
271
525
  // 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
526
+ // specific key (or supplied keys) must NOT accept an unsigned/null-key
273
527
  // entry as valid; otherwise an attacker forges an entry, nulls its
274
528
  // 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).');
529
+ if (options.requireKeyId || options.requireSuppliedKeys) {
530
+ return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', 'Entry has no signingKeyId but this run requires a signed entry (requireKeyId / requireSuppliedKeys).');
277
531
  }
278
532
  return { scopeId, position: expectedPosition, valid: true, signature: 'skipped' };
279
533
  }
@@ -284,51 +538,98 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
284
538
  if (!key) {
285
539
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_MISSING_KEY', `No public key available for signingKeyId=${entry.signingKeyId}.`);
286
540
  }
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.`);
541
+ if (options.requireSuppliedKeys && key.source !== 'supplied') {
542
+ return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', `Key ${entry.signingKeyId} is embedded in the artifact; this run requires supplied keys.`);
543
+ }
544
+ // Signed-kid binding (engine mirror: signing_key_drift), ahead of every
545
+ // question about the key, as the engine orders it. The row's signingKeyId
546
+ // column selected the key above, but the column is a denormalized
547
+ // convenience; the kid at protected-header label 4 is signature-covered. A
548
+ // divergence means the column was rewritten after signing, e.g. to point
549
+ // verification at a key the tamperer controls.
550
+ // An accounted-for entry past its distrust cutoff (see the temporal check).
551
+ let accountedPastCutoff = null;
552
+ const signedKid = extractKid(parts.protectedBstr);
553
+ if (signedKid !== null && signedKid !== entry.signingKeyId) {
554
+ return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_DRIFT', `Row signingKeyId=${entry.signingKeyId} does not match the signature-covered kid ${signedKid} in the protected header.`);
555
+ }
556
+ // Input-gated: key anchoring (engine mirror: signing_key_unanchored). Runs
557
+ // when a key-statement walk marked the registry. A key nothing signed links
558
+ // to a pinned anchor is one anything with write access to the Server's
559
+ // database can register, so an entry under it is a forgery until shown
560
+ // otherwise, whatever its signature says.
561
+ if (key.trust !== undefined) {
562
+ optionalChecks.key_anchoring = 'applied';
563
+ if (key.trust === 'unanchored') {
564
+ // A key the auditor distrusts, retired by a key the walk trusts: an
565
+ // entry it signed before that retirement is accounted for, never
566
+ // verified. Only one whose signature verifies under the key, and whose
567
+ // key material the registry does not lie about: anything else under
568
+ // its id is bytes the database's writer wrote.
569
+ const bound = key.distrustSpan?.retiredAt ?? null;
570
+ if (bound !== null && isInstant(entry.createdAt) && rfc3339Ms(entry.createdAt) < instantMs(bound)
571
+ && !declaredAlgorithmLies(key) && verifyCoseSign1(envelopeBytes, key.spkiBase64) === 'ok') {
572
+ 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.`);
573
+ }
574
+ return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_UNANCHORED', `Key ${entry.signingKeyId} is not linked by any signed key statement to a pinned trust anchor.`);
575
+ }
576
+ if (key.trust === 'undecided') {
577
+ 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');
578
+ }
289
579
  }
290
580
  // Registry self-consistency: when the input surface declares an algorithm for
291
581
  // this key (vault_signing_keys.algorithm), it must agree with what the SPKI
292
582
  // key material commits to. A registry row that lies about its own key is the
293
583
  // signature of a mis-registered key (the pre-guard P-256 corruption shape) or
294
584
  // 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.`);
585
+ if (declaredAlgorithmLies(key)) {
586
+ 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
587
  }
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)) {
588
+ // Input-gated: temporal key-validity, whenever the key carries a window.
589
+ // Compared at millisecond precision, the precision of an entry's write time,
590
+ // truncating a microsecond window edge the way the engine does. The engine
591
+ // times every entry, so an entry with no time the walk can read cannot be
592
+ // placed inside the window, and fails closed rather than skipping it.
593
+ if (typeof key.activatedAt === 'string' || typeof key.retiredAt === 'string' || typeof key.distrustCutoff === 'string') {
314
594
  optionalChecks.key_temporal = 'applied';
595
+ // A window edge that is not RFC 3339 cannot place anything either, and
596
+ // the check fails closed on it rather than skipping that edge.
597
+ for (const [edge, value] of [['activatedAt', key.activatedAt], ['retiredAt', key.retiredAt], ['distrustCutoff', key.distrustCutoff]]) {
598
+ if (typeof value === 'string' && !isInstant(value)) {
599
+ 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.`);
600
+ }
601
+ }
602
+ if (!isInstant(entry.createdAt)) {
603
+ return fail(scopeId, expectedPosition, 'CHAIN_MALFORMED_ENTRY', `Entry has no parseable createdAt, so it cannot be placed inside key ${entry.signingKeyId}'s window.`);
604
+ }
315
605
  const temporal = temporalKeyFailure(entry.createdAt, key);
316
606
  if (temporal) {
317
- return fail(scopeId, expectedPosition, temporal.code, temporal.detail);
607
+ // Past the instant the auditor's distrust entry gives, and before a key
608
+ // the walk trusts retired the key: accounted for, never verified. The
609
+ // signature below still has to verify.
610
+ const span = key.distrustSpan;
611
+ const written = rfc3339Ms(entry.createdAt);
612
+ if (temporal.code === 'CHAIN_KEY_EXPIRED' && span !== undefined && span.cutoff !== null && span.retiredAt !== null
613
+ && written >= instantMs(span.cutoff) && written < instantMs(span.retiredAt)) {
614
+ 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.`;
615
+ }
616
+ else {
617
+ return fail(scopeId, expectedPosition, temporal.code, temporal.detail);
618
+ }
318
619
  }
319
620
  }
320
621
  const outcome = verifyCoseSign1(envelopeBytes, key.spkiBase64);
321
622
  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' };
623
+ // An all-zero signature slot on an entry that CLAIMS a signing key. The
624
+ // engine writes a key id only beside a signature it made with that key,
625
+ // and fails this shape `signature_invalid`, so it is a forged or wiped
626
+ // signature, never an unsigned entry. (A genuinely unsigned entry carries
627
+ // a null signingKeyId and is graded above.)
628
+ return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_INVALID', `Entry claims signingKeyId=${entry.signingKeyId} but carries an all-zero signature.`, 'invalid');
330
629
  }
331
630
  if (outcome === 'ok') {
631
+ if (accountedPastCutoff !== null)
632
+ return accountedResult(scopeId, expectedPosition, accountedPastCutoff);
332
633
  return { scopeId, position: expectedPosition, valid: true, signature: 'ok', keySource: key.source };
333
634
  }
334
635
  if (outcome === 'alg-mismatch') {
@@ -372,11 +673,11 @@ function checkOidcActor(oidc, payloadBstr, scopeId, position) {
372
673
  * investigations, and the activation side is the security-relevant one.
373
674
  */
374
675
  function temporalKeyFailure(createdAt, key) {
375
- const written = Date.parse(createdAt);
676
+ const written = rfc3339Ms(createdAt);
376
677
  if (Number.isNaN(written))
377
678
  return null;
378
- if (key.activatedAt) {
379
- const activated = Date.parse(key.activatedAt);
679
+ if (typeof key.activatedAt === 'string' && key.activatedAt) {
680
+ const activated = instantMs(key.activatedAt);
380
681
  if (!Number.isNaN(activated) && written < activated) {
381
682
  return {
382
683
  code: 'CHAIN_KEY_NOT_YET_ACTIVE',
@@ -384,8 +685,17 @@ function temporalKeyFailure(createdAt, key) {
384
685
  };
385
686
  }
386
687
  }
387
- if (key.retiredAt) {
388
- const retired = Date.parse(key.retiredAt);
688
+ if (typeof key.distrustCutoff === 'string' && key.distrustCutoff) {
689
+ const cutoff = instantMs(key.distrustCutoff);
690
+ if (!Number.isNaN(cutoff) && written > cutoff) {
691
+ return {
692
+ code: 'CHAIN_KEY_EXPIRED',
693
+ 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.`,
694
+ };
695
+ }
696
+ }
697
+ if (typeof key.retiredAt === 'string' && key.retiredAt) {
698
+ const retired = instantMs(key.retiredAt);
389
699
  if (!Number.isNaN(retired) && written > retired) {
390
700
  return {
391
701
  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_FEDERATION_WIRE_INVALID' | 'CHAIN_EVIDENCE_BINDING_MISMATCH' | '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;