@coffre/core 0.9.0 → 0.10.1

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.
@@ -220,6 +220,8 @@ function encryptionContext(ctx: SecretContext): Record<string, string> {
220
220
  'coffre:secret': ctx.secretId,
221
221
  // A personal config's owner, hashed: KMS refuses to decrypt under any other.
222
222
  ...(ctx.owner === undefined ? {} : { 'coffre:owner': ctx.owner }),
223
+ // A sensitive value's: KMS refuses to decrypt it as anything else.
224
+ ...(ctx.sensitive === true ? { 'coffre:sensitive': 'true' } : {}),
223
225
  };
224
226
  }
225
227
 
package/src/kek/local.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { createCipheriv, createDecipheriv, randomBytes, timingSafeEqual } from 'node:crypto';
1
+ import { createCipheriv, createDecipheriv, createSecretKey, randomBytes, timingSafeEqual, type KeyObject } from 'node:crypto';
2
2
  import type { SecretContext } from '../context.ts';
3
3
  import { encodeAad } from '../context.ts';
4
4
  import { checkOperation } from './cancellation.ts';
@@ -21,13 +21,14 @@ export class LocalKekProvider implements KekProvider {
21
21
  readonly keyId: string;
22
22
  readonly keyVersion: string;
23
23
 
24
- readonly #kek: Buffer;
24
+ /** Imported once: a raw key would be imported again for every key it wraps or opens. */
25
+ readonly #kek: KeyObject;
25
26
 
26
27
  constructor(kek: Buffer, keyId: string, keyVersion: string = '1') {
27
28
  if (kek.length !== KEK_BYTES) {
28
29
  throw new Error(`a local vault key must be ${KEK_BYTES} bytes, got ${kek.length}`);
29
30
  }
30
- this.#kek = kek;
31
+ this.#kek = createSecretKey(kek);
31
32
  this.keyId = keyId;
32
33
  this.keyVersion = keyVersion;
33
34
  }
package/src/recipe.ts CHANGED
@@ -225,10 +225,10 @@ export async function generate(recipe: Recipe): Promise<Generated> {
225
225
 
226
226
  /**
227
227
  * What a write of generated values sends, by key: each value with how it
228
- * was made, and for a regenerate the version it replaces, which the server
229
- * holds it to.
228
+ * was made, for a regenerate the version it replaces, which the server
229
+ * holds it to, and who sees it, where the write says.
230
230
  */
231
- export type GeneratedWrite = Record<string, { value: string; generated: Generation; replaces?: string }>;
231
+ export type GeneratedWrite = Record<string, { value: string; generated: Generation; replaces?: string; sensitivity?: 'secret' | 'sensitive' }>;
232
232
 
233
233
  /**
234
234
  * A value made by the recipe for `key`, as a write sends it, and for a key
package/src/schemas.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
 
3
- import { INSTANCE_ROLE_NAMES, type InstanceRole } from './access.ts';
3
+ import { INSTANCE_ROLE_NAMES, ROLE_ID, type InstanceRole } from './access.ts';
4
4
  import { PROJECT_PAGES } from './pages.ts';
5
5
 
6
6
  export const slug = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/);
@@ -60,6 +60,9 @@ export const principalType = z.enum(['user', 'service']);
60
60
  export const principalId = z.string().trim().min(1).max(320);
61
61
  export const instanceRole = z.enum(INSTANCE_ROLE_NAMES as [InstanceRole, ...InstanceRole[]]);
62
62
 
63
+ /** A project role's id: one coffre ships, or one an Owner made (`ROLE_ID`). Which the instance defines, its policy says. */
64
+ export const roleId = z.string().regex(ROLE_ID, 'a role is named by lowercase letters, digits and dashes, 2 to 32, starting with a letter');
65
+
63
66
  /** Which projects or environments a scope takes in, by slug: `all`, `{ only: [...] }` or `{ except: [...] }`. */
64
67
  export const scopeFilter = z.union([
65
68
  z.literal('all'),
package/src/vault.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { createHash } from 'node:crypto';
2
+
1
3
  import type { AccessFault } from './access-fault.ts';
2
- import type { CredentialScope, GrantPlace, InstanceRole, Role, Scope, ServiceSetting } from './access.ts';
4
+ import type { CredentialScope, GrantPlace, InstanceRole, Policy, Role, RoleDefinition, Scope, ServiceSetting } from './access.ts';
3
5
 
4
6
  export { checkpointMessage, checkpointVerifier, verifyCheckpoint } from './checkpoint.ts';
5
7
  export { describeAccessFault, type AccessFault, type FaultGrant, type FaultNames } from './access-fault.ts';
@@ -26,15 +28,20 @@ export interface Vault {
26
28
  /**
27
29
  * Wrap fresh data keys for new versions `principal` writes: all, or none.
28
30
  * `seqs` are the `key.wrap` entries, one per key, which the app's
29
- * `secret.write` entries name as related.
31
+ * `secret.write` entries name as related. `sensitive` says, per key,
32
+ * whether its wrap binds it as sensitive: a vault older than 0.10 answers
33
+ * none, binding none, and the app stores no sensitive version it wrapped.
30
34
  */
31
- wrap(input: WrapInput): Promise<Outcome<{ wrapped: WrappedKey[]; seqs: number[] }>>;
35
+ wrap(input: WrapInput): Promise<Outcome<Wrapped>>;
32
36
  /**
33
37
  * Wrap existing data keys again for new versions of the same secrets,
34
- * under the current key: restoring an old value. It needs a write grant,
35
- * not a read one, since the key never leaves the vault.
38
+ * under the current key: restoring an old value, or making one stricter.
39
+ * It needs a write grant, not a read one, since the key never leaves the
40
+ * vault. A new version is never less sensitive than the one it is made
41
+ * from, or than its secret's newest: a value is made looser only by
42
+ * being written again (`invalid`).
36
43
  */
37
- rewrap(input: RewrapInput): Promise<Outcome<{ wrapped: WrappedKey[]; seqs: number[] }>>;
44
+ rewrap(input: RewrapInput): Promise<Outcome<Wrapped>>;
38
45
 
39
46
  /**
40
47
  * Make secrets references to others: whoever can read the holder's
@@ -90,19 +97,49 @@ export interface Vault {
90
97
  /** Change the instance's settings: those who run it, never anyone else. */
91
98
  setSettings(input: SetSettingsInput): Promise<Outcome<{ settings: Settings }>>;
92
99
 
100
+ /**
101
+ * The instance's access policy (`Policy` in @coffre/core/access): its
102
+ * roles, as an Owner edited and made them, and its protected
103
+ * environments, as the vault's newest `policy.change` says, by its MAC.
104
+ * As it ships, before any. A vault older than 0.10 has none, and the app
105
+ * decides as it ships.
106
+ */
107
+ policy(): Promise<Policy>;
108
+ /**
109
+ * Change the policy by one change, its own `policy.change` entry, which
110
+ * names it and what it was (docs/design/roles.md):
111
+ * - a project or instance role defined, or put back as it ships (null),
112
+ * or, one an Owner made, deleted while no grant names it: an Owner of
113
+ * the whole instance, and never the Owner role, nor the instance's
114
+ * Member;
115
+ * - environments of one project protected, by whoever manages its
116
+ * environments, before their rows exist too (a fork's); or
117
+ * unprotected, by an Owner of the whole instance.
118
+ * The policy after it, and the newest `policy.change`, which it is as of:
119
+ * the change's own, when it changed anything.
120
+ */
121
+ changePolicy(input: ChangePolicyInput): Promise<Outcome<{ policy: Policy; seq: number | null }>>;
122
+
93
123
  /**
94
124
  * Sign the log up to its last entry, in an `audit.checkpoint` entry of
95
- * the vault's, if the chain recomputes, the vault's entries by their MACs,
96
- * and the prefix the last checkpoint signed is still there. The first
97
- * checkpoint of each hour recomputes from the first entry; the others
98
- * resume from the prefix the last one signed, which the vault recomputed
99
- * itself, while it still has every entry and ends at the hash it signed.
100
- * The vault reads the log itself: it takes nobody's word
101
- * for where it ends, or for what came before. It checks every
102
- * member's row too, as `access` would, and logs a `vault.tampered` for
103
- * each one changed around it: lists read rows without asking the vault.
104
- */
105
- checkpoint(): Promise<Outcome<{ checkpoint: Checkpoint }>>;
125
+ * the vault's, if the chain recomputes from the last checkpoint, the
126
+ * vault's entries by their MACs, and that checkpoint's prefix is still
127
+ * there, whole. The entry keeps the checkpoint's tally beside it: what a
128
+ * walk from the first entry has gathered by the prefix's end (the
129
+ * vault's keys, its key batches under way, who is a member and what they
130
+ * hold), so that the next checkpoint, and every verification, go on from
131
+ * there and read only what is new. A log longer than one walk, as after
132
+ * an upgrade from 0.10.0, is signed a stretch a call, behind its head,
133
+ * until the checkpoints catch up. Each call also rehashes a stretch of
134
+ * what was signed before, round and round, which an entry edited in place
135
+ * fails: then it refuses, and every verification reports the refusal.
136
+ * A rehash the database fails moves on next time, and `warning` says so;
137
+ * a refusal it would have cleared stands meanwhile. The vault reads the log itself: it takes nobody's word for where
138
+ * it ends, or for what came before. It checks every member's row too, as
139
+ * `access` would, and logs a `vault.tampered` for each one changed around
140
+ * it: lists read rows without asking the vault.
141
+ */
142
+ checkpoint(): Promise<Outcome<{ checkpoint: Checkpoint; warning?: string }>>;
106
143
  /**
107
144
  * What the vault's configuration says, which the app shows: the keys its
108
145
  * checkpoints verify under, by the key id each checkpoint names (the one
@@ -129,13 +166,18 @@ export interface Vault {
129
166
  */
130
167
  keyChecks(): Promise<KeyChecks>;
131
168
  /**
132
- * Check the whole log: the vault's entries by their MACs, every
133
- * checkpoint against the prefix it signed, the key batches accounted for,
134
- * and replay it to see that who is a member, and what they hold, follow
135
- * from it. The links and hashes of the chain are the caller's to
136
- * recompute through `upTo`, as the app does first; with none, the vault
137
- * recomputes them all itself. A verdict and nothing else, so anyone may
138
- * ask; the app asks for those who read the whole log (`readsWholeLog`).
169
+ * Check the log from a checkpoint's tally, the newest unless `from`
170
+ * names another, or the first entry: the vault's entries since by their
171
+ * MACs, every checkpoint among them against the prefix it signed, the key
172
+ * batches accounted for, and the members and grants replayed on from the
173
+ * tally to see that the rows follow. With `to`, a later checkpoint, the
174
+ * walk stops at the prefix it signed and must come to the tally it keeps:
175
+ * a stretch of the whole log, walked from the first entry a stretch at a
176
+ * time. The links and hashes of the chain are the caller's to recompute
177
+ * through `upTo`, as the app does first; with none, the vault recomputes
178
+ * them itself, no further than one walk. A verdict and nothing else, so
179
+ * anyone may ask; the app asks for those who read the whole log
180
+ * (`readsWholeLog`).
139
181
  */
140
182
  verifyLog(input: VerifyLogInput): Promise<LogVerification>;
141
183
  }
@@ -164,11 +206,11 @@ export type RefusalCode =
164
206
  /** The wrapped key does not belong to the secret it was presented as, or a reference is not the vault's. */
165
207
  | 'bad_claim'
166
208
  /**
167
- * A person asked for values to be handed back, where people get stand-ins
168
- * (`people: 'stand-ins'`): their apps use values through the credential
169
- * proxy instead, and only service accounts read them.
209
+ * A person asked for a sensitive value to be handed back (`handsBack`):
210
+ * nobody sees one, Owners included. Their apps use it through the
211
+ * credential proxy, and service accounts read it.
170
212
  */
171
- | 'stand_ins'
213
+ | 'sensitive'
172
214
  /**
173
215
  * The project or environment was deleted for good: nothing under it is
174
216
  * opened or wrapped again, whatever grant would cover it.
@@ -192,6 +234,11 @@ export type RefusalCode =
192
234
  | 'last_owner'
193
235
  /** Well-formed, but not something the rules allow: a project role on an environment, a service account with an instance role. */
194
236
  | 'invalid'
237
+ /**
238
+ * A change to the policy weighed from one revision of it (`revision`)
239
+ * when another came since: asked again, it is weighed as the policy is now.
240
+ */
241
+ | 'policy_changed'
195
242
  /** The vault's own log no longer carries the head the last checkpoint signed, or does not rehash since. */
196
243
  | 'log_broken'
197
244
  /**
@@ -221,8 +268,19 @@ export type SecretRef = {
221
268
  version: number;
222
269
  /** `market/prod/DATABASE_URL`. */
223
270
  path: string;
271
+ /**
272
+ * Whether the version is sensitive: its value is never handed back to a
273
+ * person, on any credential of theirs, only used for them or read by a
274
+ * service account. Its data key's wrap binds it, so a version written
275
+ * sensitive opens as nothing else. Absent, or false, for a secret or a
276
+ * plain value.
277
+ */
278
+ sensitive?: boolean;
224
279
  };
225
280
 
281
+ /** What a wrap or rewrap answers: each key as wrapped, its entry, and whether its wrap binds it sensitive. */
282
+ export type Wrapped = { wrapped: WrappedKey[]; seqs: number[]; sensitive: boolean[] };
283
+
226
284
  /** A wrapped data key and the key encryption key that wrapped it; `bytes` is base64. */
227
285
  export type WrappedKey = { kekProvider: string; kekId: string; kekVersion: string; bytes: string };
228
286
 
@@ -237,18 +295,22 @@ export type KeyChecks = { current: { kekProvider: string; kekId: string }; check
237
295
  /**
238
296
  * Why someone reads: shown in the log, and the same rules apply to each. A
239
297
  * fork reads to `copy`. The credential proxy reads to `use`, a value it
240
- * injects into a request and never hands back, or to `expose`, one the
241
- * deployment lets people's apps hold. Where people get stand-ins
242
- * (`people: 'stand-ins'`), a person opens nothing to `reveal`, `run` or
243
- * `compare` (`HANDED_BACK`).
298
+ * injects into a request and never hands back, or to `expose`, one it
299
+ * gives a person's app as it is (`coffre run`'s plan).
244
300
  */
245
301
  export type Purpose = 'reveal' | 'run' | 'compare' | 'copy' | 'use' | 'expose';
246
302
 
247
303
  /**
248
- * What a person never opens where people get stand-ins: values handed back
249
- * to them, and a dry run's `compare`, which tells them whether a guess was right.
304
+ * Whether a read hands values back to whoever asked, which a person never
305
+ * gets of a sensitive value: every purpose but the proxy's `use` and a
306
+ * fork's `copy` that keeps them sensitive (`keepsSensitive`), a dry run's
307
+ * `compare` included, which tells them whether a guess was right, and any
308
+ * purpose a later app may name.
250
309
  */
251
- export const HANDED_BACK: readonly Purpose[] = ['reveal', 'run', 'compare'];
310
+ export function handsBack(read: { purpose: string; keepsSensitive?: boolean }): boolean {
311
+ if (read.purpose === 'use') return false;
312
+ return !(read.purpose === 'copy' && read.keepsSensitive === true);
313
+ }
252
314
 
253
315
  /** Ties the vault's entries to the app's request and audit rows. */
254
316
  type Correlation = {
@@ -277,6 +339,13 @@ export type Through = { credentialScope?: CredentialScope | null };
277
339
  export type UnwrapInput = Correlation & Through & {
278
340
  principal: string;
279
341
  purpose: Purpose;
342
+ /**
343
+ * That a `copy` keeps each sensitive value sensitive in what it writes:
344
+ * the vault opens a sensitive value to copy for a person only when told
345
+ * so, which an app older than 0.10, that would write it as a secret
346
+ * anyone with read sees, never says.
347
+ */
348
+ keepsSensitive?: boolean;
280
349
  /**
281
350
  * `via` reads a source's current version through a reference: the vault
282
351
  * checks the reader's grants on the holder's environment, as its
@@ -350,6 +419,8 @@ export type Access = {
350
419
  /** When the status last changed, and who changed it; null for strangers. */
351
420
  since: string | null;
352
421
  by: string | null;
422
+ /** The instance's policy, which every decision about them reads: absent from a vault older than 0.10, which decides as it ships. */
423
+ policy?: Policy;
353
424
  };
354
425
 
355
426
  /**
@@ -411,6 +482,47 @@ export type SetSettingsInput = Correlation & Through & {
411
482
  settings: Settings;
412
483
  };
413
484
 
485
+ /** One change to the policy (`changePolicy`). */
486
+ export type PolicyChange =
487
+ | { kind: 'role'; role: Role; definition: RoleDefinition | null }
488
+ | { kind: 'instance-role'; role: InstanceRole; definition: RoleDefinition | null }
489
+ | { kind: 'protect'; projectId: string; environmentIds: string[]; protected: boolean };
490
+
491
+ /**
492
+ * A policy's revision, as a decision made from it names it: its newest
493
+ * `policy.change` (null for none), and the slug of each environment it
494
+ * protects, by id, which a scoped instance role's filters match, and
495
+ * which a rename or a deletion changes with no `policy.change` of its own
496
+ * (docs/design/roles.md, "What changes the policy"). Equal revisions decide
497
+ * alike.
498
+ *
499
+ * 57.3f9a0c2e81b4d7a6 change 57, prod protected as `prod`
500
+ * 57.b20e94d1c6a8f305 change 57, prod renamed `staging`
501
+ */
502
+ export function policyRevision(seq: number | bigint | null, policy: Pick<Policy, 'protectedIn'>): string {
503
+ const places = Object.values(policy.protectedIn).flat()
504
+ .map(({ environmentId, slug }) => `${environmentId}=${slug ?? ''}`)
505
+ .sort();
506
+ return `${seq === null ? 'none' : String(seq)}.${createHash('sha256').update(places.join('\n')).digest('hex').slice(0, 16)}`;
507
+ }
508
+
509
+ /** A revision as `policyRevision` writes it. */
510
+ export const POLICY_REVISION = /^(none|[1-9][0-9]{0,15})\.[0-9a-f]{16}$/;
511
+
512
+ export type ChangePolicyInput = Correlation & Through & {
513
+ actor: string;
514
+ change: PolicyChange;
515
+ /**
516
+ * The policy the caller decided from, as its revision
517
+ * (`policyRevision`): its newest `policy.change` and the rows of the
518
+ * environments it protects. Refused, `policy_changed`, unless the policy
519
+ * under the vault's head is still that one, so that a request carries on
520
+ * from the policy it made (`seq`) only where nothing came between, and a
521
+ * change previewed is made as previewed. Unchecked when absent.
522
+ */
523
+ revision?: string;
524
+ };
525
+
414
526
  /**
415
527
  * A prefix of the log the vault signed: every entry up to `seq`, the last
416
528
  * of which has `hash`, which pins every byte before it. Kept as the vault's
@@ -442,19 +554,35 @@ export type VerifyLogInput = {
442
554
  * The last entry the app verified, every link and hash up to it
443
555
  * recomputed and its own entries checked by its key: the vault checks the
444
556
  * log still holds it, so between them both authors' entries are
445
- * authenticated over the same prefix, and the vault leaves the links to
557
+ * authenticated over the same stretch, and the vault leaves the links to
446
558
  * the app.
447
559
  */
448
560
  upTo?: LogHead | null;
561
+ /**
562
+ * Where the vault's walk starts: the seq of one of its `audit.checkpoint`
563
+ * entries that keeps a tally, or `start`, the first entry. The newest
564
+ * such checkpoint when absent, and a vault older than 0.10.1 walks from
565
+ * the first entry whatever it says.
566
+ */
567
+ from?: number | 'start';
568
+ /**
569
+ * A later checkpoint's entry, whose prefix `upTo` is: the walk ends
570
+ * there, and must come to the tally it keeps. The members' rows and the
571
+ * key batches are as they are now, not then, so only a walk without one
572
+ * holds them to the log.
573
+ */
574
+ to?: number;
449
575
  };
450
576
 
451
577
  /**
452
- * Whether the vault's log holds, with the number of entries in it. On a
453
- * failure, the entry where it breaks, or null when the chain holds but the
454
- * members and grants do not follow from it. Then `fault` says which, as
455
- * facts the app can word with names: `reason` has only ids.
456
- * Full checks report live key batches in `pending`; overdue ones fail.
578
+ * Whether the vault's log holds, with the number of its entries through
579
+ * where the walk ended, `through`: `upTo`, the prefix `to` signed, or as
580
+ * far as one walk goes. On a failure, the entry where it breaks, or null
581
+ * when the chain holds but the members and grants do not follow from it.
582
+ * Then `fault` says which, as facts the app can word with names: `reason`
583
+ * has only ids. A walk that ends at the present reports live key batches in
584
+ * `pending`; overdue ones fail.
457
585
  */
458
586
  export type LogVerification =
459
- | { ok: true; entries: number; pending?: number }
587
+ | { ok: true; entries: number; pending?: number; through?: number }
460
588
  | { ok: false; failedAtSeq: number | null; reason: string; fault?: AccessFault };