@coffre/core 0.15.0 → 0.16.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.
Files changed (70) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-CgQTlUMz.js → access-CF8UG59J.js} +70 -95
  3. package/dist/{access-DqLJjnLM.d.ts → access-ERdGGHG7.d.ts} +45 -64
  4. package/dist/access.d.ts +2 -2
  5. package/dist/access.js +2 -2
  6. package/dist/envelope.d.ts +28 -9
  7. package/dist/envelope.js +25 -8
  8. package/dist/identity.d.ts +3 -1018
  9. package/dist/identity.js +885 -623
  10. package/dist/index-DuG9p3GH.d.ts +1233 -0
  11. package/dist/kek.d.ts +10 -16
  12. package/dist/kek.js +26 -41
  13. package/dist/log.d.ts +114 -0
  14. package/dist/log.js +291 -0
  15. package/dist/mcp.d.ts +27 -4
  16. package/dist/mcp.js +31 -10
  17. package/dist/recipe-BgJpmJum.d.ts +128 -0
  18. package/dist/recipe.d.ts +2 -127
  19. package/dist/{registry-D7X-x202.d.ts → registry-B7_LUDsJ.d.ts} +30 -5
  20. package/dist/schemas.d.ts +14 -12
  21. package/dist/schemas.js +16 -14
  22. package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
  23. package/dist/vault.d.ts +1771 -1419
  24. package/dist/vault.js +96 -302
  25. package/dist/{workloads-D049JH0M.d.ts → workloads-CW2dK4AW.d.ts} +1 -9
  26. package/dist/workloads.d.ts +2 -2
  27. package/dist/workloads.js +1 -9
  28. package/package.json +7 -7
  29. package/src/access.ts +63 -95
  30. package/src/changes/access.ts +140 -0
  31. package/src/changes/freezes.ts +40 -0
  32. package/src/changes/mcp.ts +150 -0
  33. package/src/changes/places.ts +219 -0
  34. package/src/changes/secrets.ts +235 -0
  35. package/src/changes/signin.ts +197 -0
  36. package/src/changes/workloads.ts +166 -0
  37. package/src/context.ts +18 -2
  38. package/src/envelope.ts +35 -12
  39. package/src/identity/auth.ts +11 -3
  40. package/src/identity/aws.ts +62 -0
  41. package/src/identity/github-app.ts +45 -24
  42. package/src/identity/index.ts +3 -2
  43. package/src/identity/{profile-rules.ts → profiles.ts} +1 -9
  44. package/src/identity/proofs.ts +306 -0
  45. package/src/identity/signin/config.ts +1 -1
  46. package/src/identity/tokens.ts +10 -3
  47. package/src/identity/verifier.ts +73 -14
  48. package/src/identity/workload-token.ts +4 -0
  49. package/src/identity/workloads.ts +0 -11
  50. package/src/kek/aws-kms.ts +18 -13
  51. package/src/kek/check.ts +16 -46
  52. package/src/kek/index.ts +2 -2
  53. package/src/kek/types.ts +15 -3
  54. package/src/log/index.ts +7 -0
  55. package/src/{audit → log}/tiles.ts +18 -49
  56. package/src/{audit → log}/tree.ts +2 -2
  57. package/src/mcp.ts +36 -9
  58. package/src/schemas.ts +15 -12
  59. package/src/vault.ts +251 -1150
  60. package/dist/merkle.d.ts +0 -456
  61. package/dist/merkle.js +0 -964
  62. package/src/answers.ts +0 -209
  63. package/src/audit/leaf.ts +0 -81
  64. package/src/audit/merkle.ts +0 -13
  65. package/src/audit/note.ts +0 -187
  66. package/src/audit/pair.ts +0 -86
  67. package/src/audit/verify.ts +0 -393
  68. package/src/audit/witness.ts +0 -50
  69. package/src/checkpoint.ts +0 -22
  70. package/src/identity/run-proof.ts +0 -159
@@ -1,393 +0,0 @@
1
- import { entryLeaf, leafData, type LeafValue } from './leaf.ts';
2
- import { MAX_NUMBER } from './note.ts';
3
- import { openPair, samePair, TREES, type Pair, type PairNotes, type PairVerifiers, type TreeName } from './pair.ts';
4
- import { Edge, edgeOf, nodesFrom, tileMap, tilesFor, type Tile, type TileKey } from './tiles.ts';
5
- import { consistencyProof, EMPTY_ROOT, inclusionProof, verifyConsistency, verifyInclusion, type Hash } from './tree.ts';
6
-
7
- /**
8
- * The two trees, verified from what the database holds and the pairs held
9
- * outside it (the signer's, a witness's, an archive's). It walks the entries
10
- * in number order from a start it trusts, never one the database picks: the
11
- * genesis pair, or a pair the caller verified before (`from`). On the way it
12
- * rebuilds both trees and requires every stored pair and every pair held
13
- * outside, both heads each: so every sealed entry is there, unchanged, at its
14
- * place and in its tree, nothing was added, and the database shows the one
15
- * history the outside pairs saw. A database that ends before an outside pair
16
- * lost entries or checkpoints.
17
- *
18
- * It needs the trees' public keys alone. What an entry's columns mean (its
19
- * MAC, its request ID) is the caller's to check, through `check`, which sees
20
- * every entry walked, in number order. The cost is the entries since the
21
- * start: a caller that keeps the `head` it verified walks only what came
22
- * after (R25).
23
- *
24
- * Retention (plan PR 7, formal/Seal.tla) drops days of uses, and the uses
25
- * tree's tiles, below a cut that a retention change names; changes are kept
26
- * for good. With `cut`, which says whether a change is one and its cut, the
27
- * walk takes the newest retention change (the reader's `retention`), requires
28
- * it sealed in the changes tree, never merely held (CutSealed), and walks the
29
- * changes tree from the start but the uses tree from that cut: from the cut's
30
- * uses head, which the kept tiles at its edge must give, through the
31
- * checkpoint at the cut, which must hold that head. A use at or below the cut
32
- * is not walked: a straggler (one of the next day's, numbered below it) can go
33
- * unseen until its own day does.
34
- */
35
- export type LogEntry = { tree: TreeName; number: bigint; at: number; columns: readonly LeafValue[] };
36
-
37
- /** A checkpoint row: one pair's two notes, at the `upto` the row says. */
38
- export type StoredPair = { upto: bigint; notes: PairNotes };
39
-
40
- export type LogReader = {
41
- /** The rows above `after`, by `upto`, at most `limit`. */
42
- pairs(after: bigint, limit: number): Promise<StoredPair[]>;
43
- /** The row at exactly `upto`, if any. */
44
- pair(upto: bigint): Promise<StoredPair | null>;
45
- /**
46
- * The entries numbered in (after, upto], by number, both trees. Uses are
47
- * read from `floor`, the floor of `at` signed in the pair at `after`, when
48
- * the caller gives it: a reader that takes it from its rows lets a writer
49
- * hide what lies above (FloorChecked). With `limit`, the first that many.
50
- */
51
- entries(after: bigint, upto: bigint, options?: { floor?: number; limit?: number }): Promise<LogEntry[]>;
52
- tiles(tree: TreeName, keys: readonly TileKey[]): Promise<Tile[]>;
53
- /** The newest retention change, if any, and its leaf index in the changes tree (plan PR 7). */
54
- retention?(): Promise<{ entry: LogEntry; index: number } | null>;
55
- };
56
-
57
- /** Where retention cut the uses tree: the pair at `upto`, signed at `at`, whose uses head every later one extends. */
58
- export type Cut = { upto: bigint; at: number; uses: { size: number; root: Hash } };
59
-
60
- export type Verdict = {
61
- ok: boolean;
62
- problems: string[];
63
- /** Rows walked, entries sealed under them, entries above the newest. */
64
- checkpoints: number;
65
- sealed: number;
66
- unsealed: number;
67
- /** The newest pair walked, when the walk found nothing wrong: the `from` of the next one. */
68
- head: PairNotes | null;
69
- /** `head` opened, as the walk opened it: its place and time without its signatures checked again. */
70
- headPair: Pair | null;
71
- /**
72
- * Whether the database ends before a pair held outside: deleted entries or
73
- * checkpoints, or the signer's own write a moment away (it remembers a pair
74
- * before the database holds it), which a caller may tell apart by asking
75
- * again a tick later.
76
- */
77
- behind: boolean;
78
- /**
79
- * Whether more than `above` entries lie above the newest pair: the walk
80
- * checked that many and stopped short of the head, which is no problem
81
- * of the log (a checkpointer behind), and no verdict on the rest either.
82
- */
83
- capped: boolean;
84
- };
85
-
86
- type Stop = { pair: Pair; notes: PairNotes; row: boolean };
87
-
88
- const PAGE = 100;
89
-
90
- type Options = {
91
- verifiers: PairVerifiers;
92
- from?: PairNotes;
93
- /**
94
- * The database's newest row, as the caller read it in the walk's own
95
- * snapshot, to start from instead of `from`: its row is not read again,
96
- * nor the rows above it, which there are none of (PR 8 review r3).
97
- */
98
- newest?: StoredPair;
99
- anchors?: readonly PairNotes[];
100
- check?: (entry: LogEntry) => string | null;
101
- /** Whether a change is a retention change, and the cut it names; null for any other entry. */
102
- cut?: (entry: LogEntry) => Cut | null;
103
- /**
104
- * The most entries above the newest pair a walk checks, for a caller bound
105
- * in time: past it, `capped`, and the rest unread. A checkpointer stalled,
106
- * or a writer's planted rows, grow what lies there without bound.
107
- */
108
- above?: number;
109
- };
110
-
111
- export async function verifyLog(reader: LogReader, opts: Options): Promise<Verdict> {
112
- const problems: string[] = [];
113
- const verdict = { checkpoints: 0, sealed: 0, unsealed: 0, behind: false, capped: false };
114
- const done = (head: Stop | null): Verdict => {
115
- const ok = problems.length === 0;
116
- return { ok, problems, ...verdict, head: ok ? (head?.notes ?? null) : null, headPair: ok ? (head?.pair ?? null) : null };
117
- };
118
- // What the database holds is the adversary's to shape: anything the walk cannot read is a problem, never a crash.
119
- try {
120
- return await walk(reader, opts, problems, verdict, done);
121
- } catch (error) {
122
- problems.push(`verification stopped on what the database holds: ${(error as Error).message}`);
123
- return done(null);
124
- }
125
- }
126
-
127
- async function walk(
128
- reader: LogReader,
129
- opts: Options,
130
- problems: string[],
131
- verdict: { checkpoints: number; sealed: number; unsealed: number; behind: boolean; capped: boolean },
132
- done: (head: Stop | null) => Verdict,
133
- ): Promise<Verdict> {
134
- // The start's pair and those held outside, each opened once: a page's check starts at the pair the signer holds, which
135
- // is also its row, and four signature checks of one pair were a third of its cost. Rows past them are opened as read.
136
- const held = new Map<string, Promise<Pair | null>>();
137
- const noted = (notes: PairNotes) => `${notes.changes}\0${notes.uses}`;
138
- const openHeld = (notes: PairNotes) => {
139
- const key = noted(notes);
140
- if (!held.has(key)) held.set(key, openPair(notes, opts.verifiers));
141
- return held.get(key)!;
142
- };
143
- const open = async (row: StoredPair): Promise<Pair | null> => {
144
- const pair = await (held.get(noted(row.notes)) ?? openPair(row.notes, opts.verifiers));
145
- if (pair === null) problems.push(`checkpoint ${row.upto}: not a pair signed by the log`);
146
- else if (pair.upto !== row.upto) problems.push(`checkpoint ${row.upto}: its row does not match its notes (up to ${pair.upto})`);
147
- else return pair;
148
- return null;
149
- };
150
-
151
- // The start: a pair the caller trusts, which must be the row at its place, or the genesis row.
152
- let start: Stop;
153
- const from = opts.newest?.notes ?? opts.from;
154
- if (from !== undefined) {
155
- const trusted = await openHeld(from);
156
- if (trusted === null) return (problems.push('the pair to start from is not signed by the log'), done(null));
157
- const row = opts.newest ?? (await reader.pair(trusted.upto));
158
- const pair = row === null ? null : await open(row);
159
- if (pair === null || !sameNotes(pair, trusted)) return (problems.push(`no checkpoint at ${trusted.upto} with the pair to start from: checkpoints were deleted or replaced`), done(null));
160
- start = { pair, notes: row!.notes, row: true };
161
- } else {
162
- const [row] = await reader.pairs(-1n, 1);
163
- const pair = row === undefined ? null : await open(row);
164
- const genesis = pair !== null && pair.upto === 0n && TREES.every((tree) => pair[tree].size === 0 && pair[tree].root.equals(EMPTY_ROOT));
165
- if (!genesis) return (problems.push('no genesis checkpoint to start from: checkpoints were deleted or replaced'), done(null));
166
- start = { pair: pair!, notes: row!.notes, row: true };
167
- }
168
- // The newest retention change: sealed in the changes tree, below the start by a proof from its tiles, above it on the
169
- // walk (Seal.tla's CutSealed); its cut names where the uses tree is walked from, when that is past the start.
170
- const retained = opts.cut === undefined || reader.retention === undefined ? null : await reader.retention();
171
- const cut = retained === null ? null : opts.cut!(retained.entry);
172
- if (retained !== null) {
173
- const { entry, index } = retained;
174
- if (cut === null) return (problems.push(`${entry.number}: the newest retention change names no cut`), done(null));
175
- if (cut.upto >= entry.number) return (problems.push(`${entry.number}: a retention change at or below its own cut (${cut.upto})`), done(null));
176
- if (entry.number <= start.pair.upto) {
177
- const size = start.pair.changes.size;
178
- const proof = Number.isSafeInteger(index) && index >= 0 && index < size
179
- ? inclusionProof(nodesFrom(tileMap(await reader.tiles('changes', tilesFor((n) => inclusionProof(n, index, size))))), index, size)
180
- : null;
181
- if (proof === null || !verifyInclusion(entryLeaf('changes', entry.number, entry.columns), index, size, proof, start.pair.changes.root)) {
182
- return (problems.push(`${entry.number}: the retention change cutting the uses at ${cut.upto} is not in the changes tree the walk starts from`), done(null));
183
- }
184
- }
185
- }
186
- // Past the start, the uses tree starts at the cut: its edge from the kept tiles, held to the cut's head.
187
- const ahead = cut !== null && cut.upto > start.pair.upto ? cut : null;
188
- const dropped = (e: { tree: TreeName; number: bigint }) => ahead !== null && e.tree === 'uses' && e.number <= ahead.upto;
189
- // Tiles that do not give their signed head are a problem to report, and the walk goes on where it can.
190
- const load = async (pair: Pair) => {
191
- const edges = {} as Record<TreeName, Edge>;
192
- for (const tree of TREES) {
193
- const head = tree === 'uses' && ahead !== null && pair.upto < ahead.upto ? ahead.uses : pair[tree];
194
- edges[tree] = await loadEdge(reader, tree, head.size, head.root, pair.upto);
195
- }
196
- return edges;
197
- };
198
- const reload = (pair: Pair) => load(pair).catch((error: Error) => (problems.push(error.message), null));
199
-
200
- // Pairs held outside below the start, in order, then the start: their times and floors never come down.
201
- const below = (await Promise.all((opts.anchors ?? []).map(openHeld)))
202
- .filter((a): a is Pair => a !== null && a.upto <= start.pair.upto)
203
- .sort((a, b) => (a.upto < b.upto ? -1 : 1));
204
- for (const [i, a] of below.entries()) {
205
- const next = below[i + 1] ?? start.pair;
206
- if (next.at < a.at || next.floor < a.floor) problems.push(`the pair held outside up to ${a.upto}: its time or floor is past the next pair's (up to ${next.upto}): time runs back`);
207
- // Two pairs held for one place must be one signing.
208
- if (next.upto === a.upto && (next.at !== a.at || next.floor !== a.floor || next.prev !== a.prev)) problems.push(`two pairs held outside up to ${a.upto}, signed at two times, floors or prevs`);
209
- }
210
-
211
- // Pairs held outside. Those at or below the start are not walked (verified before), but each must still be the row
212
- // at its place, if there is one, and, whether or not there is, a prefix of the start, by a consistency proof from the
213
- // tiles, in both trees.
214
- const above: Stop[] = [];
215
- for (const notes of opts.anchors ?? []) {
216
- const anchor = await openHeld(notes);
217
- if (anchor === null) {
218
- problems.push('a pair held outside is not signed by the log');
219
- } else if (anchor.upto > start.pair.upto) {
220
- above.push({ pair: anchor, notes, row: false });
221
- } else if (sameNotes(anchor, start.pair)) {
222
- // The start itself, as a page's check starts at the pair the signer holds: its row is the start's, and a head is
223
- // a prefix of itself.
224
- } else {
225
- const row = await reader.pair(anchor.upto);
226
- const pair = row === null ? null : await open(row);
227
- if (pair !== null && !sameNotes(pair, anchor)) problems.push(`checkpoint ${anchor.upto}: not the pair held outside for that place: ${samePair(pair, anchor) ? 'the same heads signed at another time or floor' : 'a second history'}`);
228
- // A row that agrees proves nothing by itself: a fork can be both the row and the pair held outside. Below a cut, the
229
- // uses tree's tiles are gone: its consistency is proved from the cut on only.
230
- // Both trees' proofs at once (R42), their problems in the trees' order.
231
- const forks = await Promise.all(TREES.map(async (tree) => {
232
- if (tree === 'uses' && cut !== null && anchor.uses.size < cut.uses.size) return null;
233
- const [from, to] = [anchor[tree], start.pair[tree]];
234
- const proof = from.size > to.size ? null : await proveConsistency(reader, tree, from.size, to.size).catch(() => null);
235
- return proof === null || !verifyConsistency(from.size, to.size, from.root, to.root, proof) ? tree : null;
236
- }));
237
- for (const tree of forks) {
238
- if (tree !== null) problems.push(`the pair held outside up to ${anchor.upto}: its ${tree} head is not a prefix of the start's: a second history, or tiles deleted`);
239
- }
240
- }
241
- }
242
- above.sort((a, b) => (a.pair.upto < b.pair.upto ? -1 : 1));
243
- // The trees' edges at the start, from its tiles, which a window is appended to. A walk from the newest row has no
244
- // window to walk (no row above it, and a pair held outside above it is `behind`), so it reads none (PR 8 review r5).
245
- let edges: Record<TreeName, Edge> | null = null;
246
- if (opts.newest === undefined) {
247
- edges = await reload(start.pair);
248
- if (edges === null) return done(null);
249
- }
250
-
251
- // The walk: a page of rows at a time, with the outside pairs that fall among them, entries read once per page.
252
- // `last` is the newest row walked, `cursor` how far entries have gone into the trees (an outside pair can be past it).
253
- let last = start;
254
- let cursor = start.pair.upto;
255
- let previous = start.pair.upto;
256
- let time = start.pair.at;
257
- let floor = start.pair.floor;
258
- // Whether the walk met the retention change it starts the uses tree from, and the checkpoint at its cut.
259
- let retainedMet = retained === null || retained.entry.number <= start.pair.upto;
260
- let cutMet = ahead === null;
261
- const walkEntries = (entries: readonly LogEntry[]) => {
262
- for (const e of entries) {
263
- // The retention change the walk starts the uses tree from, met on the way. A newer one is not looked for: it can be
264
- // appended, or sealed, while the walk runs, and an older cut only makes the walk cover more uses. (A day dropped
265
- // below a newer cut while the walk still reads those uses shows as uses gone: walk again.)
266
- if (e.tree === 'changes' && retained !== null && e.number === retained.entry.number) {
267
- if (!sameEntry(e, retained.entry)) problems.push(`${e.number}: not the retention change the database names at its number`);
268
- else retainedMet = true;
269
- }
270
- if (e.number <= previous) problems.push(`${e.number}: numbered at or below the entry before (${previous}): two entries with one number, or out of order`);
271
- if (!TREES.includes(e.tree)) problems.push(`${e.number}: in no tree (${String(e.tree)})`);
272
- const problem = opts.check?.(e) ?? null;
273
- if (problem !== null) problems.push(`${e.number}: ${problem}`);
274
- previous = e.number > previous ? e.number : previous;
275
- }
276
- };
277
- for (let rows = opts.newest === undefined ? await reader.pairs(start.pair.upto, PAGE) : []; ; rows = await reader.pairs(rows.at(-1)!.upto, PAGE)) {
278
- const stops: Stop[] = [];
279
- for (const row of rows) {
280
- const pair = await open(row);
281
- if (pair !== null) stops.push({ pair, notes: row.notes, row: true });
282
- }
283
- const final = rows.length < PAGE;
284
- const newest = (stops.at(-1) ?? last).pair.upto;
285
- while (above.length > 0 && (final || above[0]!.pair.upto <= rows.at(-1)!.upto)) {
286
- const anchor = above.shift()!;
287
- const row = stops.find((s) => s.pair.upto === anchor.pair.upto);
288
- if (row !== undefined) {
289
- if (!sameNotes(row.pair, anchor.pair)) problems.push(`checkpoint ${anchor.pair.upto}: not the pair held outside for that place: ${samePair(row.pair, anchor.pair) ? 'the same heads signed at another time or floor' : 'a second history'}`);
290
- } else if (final && anchor.pair.upto > newest) {
291
- verdict.behind = true;
292
- problems.push(`the database ends up to ${newest}; a pair held outside seals up to ${anchor.pair.upto}: entries or checkpoints were deleted`);
293
- } else {
294
- stops.push(anchor);
295
- }
296
- }
297
- stops.sort((a, b) => (a.pair.upto < b.pair.upto ? -1 : 1));
298
- if (stops.length > 0) {
299
- if (edges === null) {
300
- edges = await reload(start.pair);
301
- if (edges === null) return done(null);
302
- }
303
- // From the floor the pair at `cursor` signed, never its row's (review r9).
304
- const entries = (await reader.entries(cursor, stops.at(-1)!.pair.upto, { floor })).filter((e) => !dropped(e));
305
- let at = 0;
306
- for (const stop of stops) {
307
- const window: LogEntry[] = [];
308
- while (at < entries.length && entries[at]!.number <= stop.pair.upto) window.push(entries[at++]!);
309
- walkEntries(window);
310
- for (const tree of TREES) edges[tree].append(window.filter((e) => e.tree === tree).map((e) => entryLeaf(tree, e.number, e.columns)));
311
- verdict.sealed += window.length;
312
- // Time never runs back along one history: retention's freshness step rests on it. Equal is honest (a window of
313
- // gaps keeps the time).
314
- if (stop.pair.at < time) problems.push(`${stop.row ? 'checkpoint' : 'the pair held outside up to'} ${stop.pair.upto}: signed at ${stop.pair.at}, before the pair before it (${time}): time runs back`);
315
- if (stop.pair.floor < floor) problems.push(`${stop.row ? 'checkpoint' : 'the pair held outside up to'} ${stop.pair.upto}: its floor of at (${stop.pair.floor}) is below the one before it (${floor})`);
316
- time = Math.max(time, stop.pair.at);
317
- floor = Math.max(floor, stop.pair.floor);
318
- cursor = stop.pair.upto;
319
- // Below the cut the uses tree is not walked; the checkpoint at the cut must hold the cut's uses head itself.
320
- const walked = TREES.filter((tree) => tree === 'changes' || ahead === null || stop.pair.upto >= ahead.upto);
321
- if (ahead !== null && stop.pair.upto === ahead.upto) {
322
- if (stop.pair.uses.size !== ahead.uses.size || !stop.pair.uses.root.equals(ahead.uses.root)) {
323
- problems.push(`${stop.row ? 'checkpoint' : 'the pair held outside up to'} ${stop.pair.upto}: not the uses head the retention change cuts at`);
324
- } else if (stop.row) cutMet = true;
325
- }
326
- if (ahead !== null && stop.pair.upto > ahead.upto && !cutMet) {
327
- problems.push(`no checkpoint at the retention cut (${ahead.upto}): checkpoints were deleted or replaced`);
328
- cutMet = true;
329
- }
330
- const grown = edges;
331
- const wrong = walked.filter((tree) => grown[tree].size !== stop.pair[tree].size || !grown[tree].root().equals(stop.pair[tree].root));
332
- if (wrong.length > 0) {
333
- problems.push(`${stop.row ? 'checkpoint' : 'the pair held outside up to'} ${stop.pair.upto}: the ${wrong.join(' and ')} head${wrong.length > 1 ? 's' : ''} differ from the entries: entries deleted, added, changed or moved, or a second history`);
334
- // Carry on from the signed row, so one problem is reported once.
335
- if (stop.row) edges = (await reload(stop.pair)) ?? edges;
336
- }
337
- if (stop.row) {
338
- verdict.checkpoints += 1;
339
- last = stop;
340
- }
341
- }
342
- }
343
- if (final) break;
344
- }
345
- // Above the newest pair, no tree to hold the entries to: the signed floor is all that bounds the read (review r9). A
346
- // database behind a pair held outside is broken already: what lies above its newest pair, which deleted checkpoints can
347
- // make the whole log, is not read (PR 8 review r1).
348
- if (!verdict.behind) {
349
- const limit = opts.above === undefined ? {} : { limit: opts.above + 1 };
350
- const unsealed = (await reader.entries(cursor, MAX_NUMBER, { floor, ...limit })).filter((e) => !dropped(e));
351
- const checked = opts.above === undefined ? unsealed : unsealed.slice(0, opts.above);
352
- walkEntries(checked);
353
- verdict.unsealed = checked.length;
354
- // More lie there: not checked to the head, which says nothing against the log (PR 8 review r4 of W240).
355
- verdict.capped = checked.length < unsealed.length;
356
- }
357
- if (!cutMet) problems.push(`no checkpoint at the retention cut (${ahead!.upto}): checkpoints were deleted or replaced`);
358
- // Above the start, the retention change must be on the walk and sealed: in a window a checkpoint verified.
359
- if (!retainedMet || (retained !== null && retained.entry.number > last.pair.upto)) {
360
- problems.push(`${retained!.entry.number}: the retention change cutting the uses at ${cut!.upto} is not sealed in the changes tree`);
361
- }
362
- return done(last);
363
- }
364
-
365
- /**
366
- * Whether a pair held outside is the row at its place: the same heads, and
367
- * the same time and floor. Two notes for one place signed at two times take the
368
- * signer's key twice; honest pairs held outside are copies of rows.
369
- */
370
- const sameNotes = (a: Pair, b: Pair) => samePair(a, b) && a.at === b.at && a.floor === b.floor && a.prev === b.prev;
371
-
372
- /** Both trees' edges at a pair, from their tiles; throws unless each gives its signed head. */
373
- export async function loadEdges(reader: Pick<LogReader, 'tiles'>, pair: Pair): Promise<Record<TreeName, Edge>> {
374
- const edges = {} as Record<TreeName, Edge>;
375
- for (const tree of TREES) edges[tree] = await loadEdge(reader, tree, pair[tree].size, pair[tree].root, pair.upto);
376
- return edges;
377
- }
378
-
379
- /** One tree's edge at `size`, from its tiles; throws unless it gives `root`, the head signed up to `upto`. */
380
- async function loadEdge(reader: Pick<LogReader, 'tiles'>, tree: TreeName, size: number, root: Hash, upto: bigint): Promise<Edge> {
381
- const edge = Edge.load(size, tileMap(await reader.tiles(tree, edgeOf(size).filter((e) => e.width > 0))));
382
- if (!edge.root().equals(root)) throw new Error(`checkpoint ${upto}: the ${tree} tiles at its edge do not give its signed head`);
383
- return edge;
384
- }
385
-
386
- /** Whether two entries are one, whole: the same leaf. */
387
- const sameEntry = (a: LogEntry, b: LogEntry) => leafData(a.tree, a.number, a.columns).equals(leafData(b.tree, b.number, b.columns));
388
-
389
- /** A consistency proof between two sizes of one tree, from its tiles. */
390
- export async function proveConsistency(reader: Pick<LogReader, 'tiles'>, tree: TreeName, from: number, to: number) {
391
- const nodes = nodesFrom(tileMap(await reader.tiles(tree, tilesFor((n) => consistencyProof(n, from, to)))));
392
- return consistencyProof(nodes, from, to);
393
- }
@@ -1,50 +0,0 @@
1
- import { cosignNote, type NoteSigner } from './note.ts';
2
- import { openPair, samePair, TREES, type Pair, type PairNotes, type PairVerifiers, type TreeName } from './pair.ts';
3
- import { verifyConsistency, type Hash } from './tree.ts';
4
-
5
- /**
6
- * A witness of the pair, as transparency-dev's and Sigsum's witnesses work on
7
- * one log: it holds the newest pair it has seen, and cosigns a new one only if
8
- * both trees prove they extend what it holds. So the log cannot show two
9
- * parties two histories (a split view) and get both witnessed, in either tree.
10
- * The witness's Durable Object runs this, and so do the tests.
11
- *
12
- * It takes both notes in one request and answers for both: a pair whose
13
- * changes head extends the one held while its uses head forks is refused
14
- * whole. (A standard C2SP witness takes one origin; given each tree's note,
15
- * it checks that tree alone, which is all it needs to.)
16
- */
17
- export type WitnessState = { pair: Pair; notes: PairNotes } | null;
18
-
19
- /** `cosigned`: the pair as the witness cosigned it; none from an archive, which stores what it is sent and checks nothing. */
20
- export type WitnessAnswer = { ok: true; cosigned?: PairNotes } | { ok: false; reason: string };
21
-
22
- /** Consistency proofs from the sizes the witness holds to the new pair's, one per tree. */
23
- export type PairProofs = Record<TreeName, readonly Hash[]>;
24
-
25
- export async function witnessPair(
26
- state: WitnessState,
27
- notes: PairNotes,
28
- proofs: PairProofs,
29
- log: PairVerifiers,
30
- self: NoteSigner,
31
- ): Promise<{ state: WitnessState; answer: WitnessAnswer }> {
32
- const pair = await openPair(notes, log);
33
- if (pair === null) return { state, answer: { ok: false, reason: 'not a pair signed by the log' } };
34
- if (state !== null) {
35
- const held = state.pair;
36
- if (pair.upto < held.upto) return { state, answer: { ok: false, reason: `older than the pair held (up to ${held.upto})` } };
37
- if (pair.at < held.at) return { state, answer: { ok: false, reason: `signed at ${pair.at}, before the pair held (${held.at}): time runs back` } };
38
- if (pair.floor < held.floor) return { state, answer: { ok: false, reason: `its floor of at (${pair.floor}) is below the pair held's (${held.floor})` } };
39
- // One place, one pair: the same `upto` with other heads is a second history, however consistent.
40
- if (pair.upto === held.upto && !samePair(pair, held)) return { state, answer: { ok: false, reason: `split view: a second pair up to ${pair.upto}` } };
41
- for (const tree of TREES) {
42
- const [from, to] = [held[tree], pair[tree]];
43
- if (!verifyConsistency(from.size, to.size, from.root, to.root, proofs[tree])) {
44
- return { state, answer: { ok: false, reason: `split view: ${tree} at ${to.size} leaves up to ${pair.upto} does not extend ${from.size} up to ${held.upto}` } };
45
- }
46
- }
47
- }
48
- const [changes, uses] = await Promise.all(TREES.map((tree) => cosignNote(notes[tree], self)));
49
- return { state: { pair, notes }, answer: { ok: true, cosigned: { changes: changes!, uses: uses! } } };
50
- }
package/src/checkpoint.ts DELETED
@@ -1,22 +0,0 @@
1
- import type { Checkpoint } from './vault.ts';
2
-
3
- /** What a checkpoint's signature covers: the prefix of the log up to entry `seq`, and when. */
4
- export function checkpointMessage(checkpoint: Omit<Checkpoint, 'signature' | 'keyId'>): Uint8Array<ArrayBuffer> {
5
- const { seq, hash, signedAt } = checkpoint;
6
- return new Uint8Array(new TextEncoder().encode(`coffre.checkpoint.v3|${seq}|${hash}|${signedAt}`));
7
- }
8
-
9
- /** Whether `checkpoint` was signed by the key whose raw public half is `publicKey`. */
10
- export async function verifyCheckpoint(checkpoint: Checkpoint, publicKey: string): Promise<boolean> {
11
- return (await checkpointVerifier(publicKey))(checkpoint);
12
- }
13
-
14
- /**
15
- * `verifyCheckpoint` for many checkpoints signed by one key, the key
16
- * imported once: a full verification checks every checkpoint, one every
17
- * five minutes.
18
- */
19
- export async function checkpointVerifier(publicKey: string): Promise<(checkpoint: Checkpoint) => Promise<boolean>> {
20
- const key = await crypto.subtle.importKey('raw', new Uint8Array(Buffer.from(publicKey, 'base64')), { name: 'Ed25519' }, false, ['verify']);
21
- return (checkpoint) => crypto.subtle.verify('Ed25519', key, new Uint8Array(Buffer.from(checkpoint.signature, 'base64')), checkpointMessage(checkpoint));
22
- }
@@ -1,159 +0,0 @@
1
- import { expectedAudiences, PROFILE_RULES } from './profile-rules.ts';
2
- import { CLOCK_TOLERANCE_SECONDS, decodeWorkloadToken, MAX_TOKEN_AGE_SECONDS, uploadedKeys, verifyWorkloadToken, WorkloadTokenRefused, type JSONWebKeySet } from './workload-token.ts';
3
- import { claimAt, differingClaims, REPEATING_PROFILES, type BindingClaims, type BindingPolicy, type WorkloadProfile } from './workloads.ts';
4
-
5
- /**
6
- * The claims of the run a credential was issued for, as the issuer
7
- * asserted them: in the sign-in's record, so that a read leads back to its
8
- * run. What the issuer says, not proof of which run sent the request.
9
- */
10
- export const RUN_CLAIMS = [
11
- 'sub', 'jti', 'actor', 'event_name', 'ref', 'base_ref', 'head_ref', 'sha', 'repository', 'repository_id', 'run_id', 'run_attempt',
12
- 'workflow_ref', 'job_workflow_ref', 'job_workflow_sha', 'environment',
13
- 'project_path', 'project_id', 'namespace_id', 'pipeline_id', 'pipeline_source', 'job_id',
14
- 'kubernetes.io.pod.name',
15
- ] as const;
16
- const MAX_RUN_CLAIM = 256;
17
-
18
- /** A binding's `jwks_uri` when it carries its issuer's keys: the SHA-256 of those keys (`UploadedKeys`), where a fetched set's URL would be. */
19
- export const UPLOADED_KEYS = 'sha256:';
20
-
21
- /** The run's claims, as the issuer stated them: those that say which run, each bounded. */
22
- export function runClaims(claims: Record<string, unknown>): Record<string, string | number> {
23
- const run: Record<string, string | number> = {};
24
- for (const name of RUN_CLAIMS) {
25
- const value = claimAt(claims, name);
26
- if (typeof value === 'string') run[name] = value.slice(0, MAX_RUN_CLAIM);
27
- else if (typeof value === 'number' && Number.isFinite(value)) run[name] = value;
28
- }
29
- return run;
30
- }
31
-
32
- /** A token's one audience, or null for none or several: a token for several parties is no single party's. */
33
- export function soleAudience(aud: unknown): string | null {
34
- if (typeof aud === 'string') return aud;
35
- return Array.isArray(aud) && aud.length === 1 && typeof aud[0] === 'string' ? aud[0] : null;
36
- }
37
-
38
- /**
39
- * A binding as the vault weighs a sign-in through it (T149, PR 3b): its
40
- * sealed object's columns, the instance it was made on (`origin`), and the
41
- * keys uploaded with it as its row keeps them, which must be the ones its
42
- * `jwksUri` digests. Only such a binding's: the vault fetches nothing, so
43
- * the tokens of an issuer that publishes its keys are the app's to verify.
44
- */
45
- export type RunBinding = {
46
- profile: WorkloadProfile;
47
- issuer: string;
48
- origin: string;
49
- jwksUri: string;
50
- jwks: string;
51
- claims: string;
52
- policy: string | null;
53
- };
54
-
55
- /** Why a run's proof buys nothing, as the app's refusals say it (`ExchangeReason`), with the key a refused token named. */
56
- export class RunProofRefused extends Error {
57
- readonly reason: string;
58
- readonly kid: string | null;
59
- constructor(reason: string, message: string, kid: string | null = null) {
60
- super(message);
61
- this.name = 'RunProofRefused';
62
- this.reason = reason;
63
- this.kid = kid;
64
- }
65
- }
66
-
67
- /** What a run's proof says, verified: what the credential it buys is held to. */
68
- export type RunProof = {
69
- claims: Record<string, unknown>;
70
- /** The run's claims, for the sign-in's record. */
71
- run: Record<string, string | number>;
72
- /** The token's signing input's hash, spent once; null for a token its platform hands out again, or one that names the session's key. */
73
- spent: Buffer | null;
74
- /** The last instant the token holds by its own times, ms: a CI run's (its `exp`, its `iat`'s hour); null for a workload's session. */
75
- validUntil: number | null;
76
- /** A workload's session's hard end by the token, ms (its `exp`); null when the token names the session's key, or for a CI run. */
77
- notAfter: number | null;
78
- };
79
-
80
- /** A token's `kid`, at most 64 characters, for a refusal and the alert it raises; the token is unverified. */
81
- function shownKid(header: Record<string, unknown>): string | null {
82
- return typeof header.kid === 'string' ? header.kid.slice(0, 64) : null;
83
- }
84
-
85
- /**
86
- * Verify a CI run's or a workload's ID token against one binding, sealed
87
- * (D148), whose keys were uploaded with it: the vault's own check, which
88
- * no app can steer, and which asks no one. The binding's keys, held to the
89
- * digest its seal covers (a key they lack is refused, never looked for),
90
- * its issuer, its audience (the instance it was made on, or, for a
91
- * platform whose caller names the session's key, that key: `jkt`, from the
92
- * DPoP proof the vault verified, never from the app), the token's times,
93
- * the binding's claims and its profile's rules. Throws `RunProofRefused`.
94
- */
95
- export async function verifyRunToken(
96
- token: string,
97
- binding: RunBinding,
98
- context: { now: Date; workload: { jkt: string } | null },
99
- ): Promise<RunProof> {
100
- let decoded: ReturnType<typeof decodeWorkloadToken>;
101
- try {
102
- decoded = decodeWorkloadToken(token);
103
- } catch (error) {
104
- throw refusedBy(error);
105
- }
106
- const { claims: unverified, header } = decoded;
107
- if (unverified.iss !== binding.issuer) throw new RunProofRefused('no_match', `the token is from ${unverified.iss}, which this binding does not trust`);
108
- const policy = binding.policy === null ? null : (JSON.parse(binding.policy) as BindingPolicy);
109
- if ((context.workload === null) !== (policy === null)) throw new RunProofRefused('no_match', 'a CI run signs in through a binding with no policy, a workload through one with');
110
- // The audience the binding takes: the instance's, or, for a workload, its profile's (the session's key among them).
111
- const accepted = context.workload === null
112
- ? [binding.origin]
113
- : expectedAudiences(binding.profile, policy!, { publicUrl: binding.origin, jkt: context.workload.jkt });
114
- const named = soleAudience(unverified.aud);
115
- const audience = named !== null && accepted.includes(named) ? named : accepted[0]!;
116
- const repeating = context.workload !== null && REPEATING_PROFILES.includes(binding.profile);
117
- const expected = { issuer: binding.issuer, audience, now: context.now, ...(repeating ? { maxAge: null } : {}) };
118
- let claims: Record<string, unknown>;
119
- try {
120
- // The very keys its seal digests, never others the app names (a forged set).
121
- const uploaded = await uploadedKeys(JSON.parse(binding.jwks) as unknown);
122
- if (`${UPLOADED_KEYS}${uploaded.digest}` !== binding.jwksUri) throw new RunProofRefused('keys', 'the keys are not those the binding was made with');
123
- // No issuer to ask whether a token still stands, so none lives past the hour.
124
- claims = await verifyWorkloadToken(token, JSON.parse(uploaded.jwks) as JSONWebKeySet, { ...expected, maxLifetime: MAX_TOKEN_AGE_SECONDS });
125
- } catch (error) {
126
- if (error instanceof RunProofRefused) throw error;
127
- if (error instanceof WorkloadTokenRefused && error.reason === 'unknown_key') {
128
- throw new RunProofRefused('unknown_key', error.message, shownKid(header));
129
- }
130
- throw refusedBy(error);
131
- }
132
- const differ = differingClaims(binding.profile, JSON.parse(binding.claims) as BindingClaims, claims);
133
- if (differ.length > 0) throw new RunProofRefused('no_match', `the binding does not trust these claims: ${differ.join(', ')} differ`);
134
- if (context.workload !== null) {
135
- const ruled = PROFILE_RULES[binding.profile]?.token(claims, { issuer: binding.issuer, claims: JSON.parse(binding.claims) as BindingClaims, policy: policy! }) ?? null;
136
- if (ruled !== null) throw new RunProofRefused('no_match', ruled);
137
- }
138
- const run = runClaims(claims);
139
- if (context.workload === null) {
140
- // The token's own times, held to again in the statement: its `exp`, and its `iat`'s hour, whole ms, down.
141
- const validUntil = Math.floor(Math.min((decoded.claims.exp + CLOCK_TOLERANCE_SECONDS) * 1000, (decoded.claims.iat + MAX_TOKEN_AGE_SECONDS) * 1000));
142
- return { claims, run, spent: decoded.signingInputHash, validUntil, notAfter: null };
143
- }
144
- // A token that names the session's key, or one its platform hands out again, is never spent; any other once. One that
145
- // does not name the key ends the session at its own `exp`.
146
- const namesKey = policy!.keyAudience === true;
147
- return {
148
- claims, run,
149
- spent: namesKey || repeating ? null : decoded.signingInputHash,
150
- validUntil: null,
151
- notAfter: namesKey ? null : decoded.claims.exp * 1000,
152
- };
153
- }
154
-
155
- function refusedBy(error: unknown): RunProofRefused {
156
- if (error instanceof WorkloadTokenRefused) return new RunProofRefused(error.reason, error.message);
157
- if (error instanceof RunProofRefused) return error;
158
- return new RunProofRefused('malformed', (error as Error)?.message ?? 'the token is not one coffre reads');
159
- }