@coffre/core 0.9.0 → 0.10.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/src/access.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Who may do what: seven permissions, the six project roles a grant names,
2
+ * Who may do what: eight permissions, the seven project roles a grant names,
3
3
  * and the five instance roles a person holds across every project.
4
4
  *
5
5
  * Deliberately constants and not tables or a policy language. A grant names
@@ -8,8 +8,16 @@
8
8
  * stays something you can read end to end.
9
9
  */
10
10
 
11
+ /**
12
+ * `secret.read` hands a value back: a reveal, `coffre get`, `coffre run`'s
13
+ * values. `secret.use` uses it without handing it back: a placeholder in a
14
+ * person's app, the credential proxy filling it in (docs/design/credential-proxy.md).
15
+ * Every role that reads uses too. What a person gets is the narrower of the
16
+ * two and the key's sensitivity: a sensitive key is only ever used.
17
+ */
11
18
  export const PERMISSIONS = [
12
19
  'secret.read',
20
+ 'secret.use',
13
21
  'secret.write',
14
22
  'secret.archive',
15
23
  'audit.read',
@@ -31,60 +39,100 @@ export const PROJECT_ONLY_PERMISSIONS: readonly Permission[] = [
31
39
  'project.manage',
32
40
  ];
33
41
 
42
+ /**
43
+ * What a role holds: `permissions` in an environment that is not
44
+ * protected, and on its project; `protected`, what a person holds of it in
45
+ * a protected environment (docs/design/roles.md). Project-wide permissions
46
+ * are in `permissions` alone: a project is never protected. A service
47
+ * account holds `permissions` everywhere.
48
+ */
49
+ export type RoleDefinition = {
50
+ name: string;
51
+ description: string;
52
+ permissions: readonly Permission[];
53
+ protected: readonly Permission[];
54
+ };
55
+
34
56
  export const ROLES = {
35
57
  viewer: {
36
58
  name: 'Viewer',
37
- description: 'Read secret values.',
38
- permissions: ['secret.read'],
59
+ description: 'Read and use secret values.',
60
+ permissions: ['secret.read', 'secret.use'],
61
+ protected: ['secret.use'],
62
+ },
63
+ contributor: {
64
+ name: 'Contributor',
65
+ description: 'Use and write secrets, never read them: apps get placeholders through the credential proxy.',
66
+ permissions: ['secret.use', 'secret.write'],
67
+ protected: ['secret.use', 'secret.write'],
39
68
  },
40
69
  developer: {
41
70
  name: 'Developer',
42
- description: 'Read and write secrets.',
43
- permissions: ['secret.read', 'secret.write'],
71
+ description: 'Read, use and write secrets.',
72
+ permissions: ['secret.read', 'secret.use', 'secret.write'],
73
+ protected: ['secret.use', 'secret.write'],
44
74
  },
45
75
  maintainer: {
46
76
  name: 'Maintainer',
47
- description: 'Read, write and retire secrets, and manage environments.',
48
- permissions: ['secret.read', 'secret.write', 'secret.archive', 'environment.manage'],
77
+ description: 'Read, use, write and retire secrets, and manage environments.',
78
+ permissions: ['secret.read', 'secret.use', 'secret.write', 'secret.archive', 'environment.manage'],
79
+ protected: ['secret.use', 'secret.write', 'secret.archive'],
49
80
  },
50
81
  'access-manager': {
51
82
  name: 'Access manager',
52
83
  description: 'Manage who has access. Cannot read secret values.',
53
84
  permissions: ['grant.manage'],
85
+ protected: [],
54
86
  },
55
87
  auditor: {
56
88
  name: 'Auditor',
57
89
  description: 'Read the audit log. Cannot read secret values.',
58
90
  permissions: ['audit.read'],
91
+ protected: ['audit.read'],
59
92
  },
60
93
  owner: {
61
94
  name: 'Owner',
62
95
  description: 'Everything, including reading secret values.',
63
96
  permissions: [...PERMISSIONS],
97
+ protected: [...PERMISSIONS].filter((permission) => !PROJECT_ONLY_PERMISSIONS.includes(permission)),
64
98
  },
65
- } as const satisfies Record<string, {
66
- name: string;
67
- description: string;
68
- permissions: readonly Permission[];
69
- }>;
99
+ } as const satisfies Record<string, RoleDefinition>;
100
+
101
+ /** A role coffre ships, as its default says (`ROLES`); an Owner may edit any but Owner. */
102
+ export type BuiltinRole = keyof typeof ROLES;
103
+
104
+ /** A project role by id: one coffre ships, or one an Owner made (`ROLE_ID`), as the instance's policy defines it. */
105
+ export type Role = string;
70
106
 
71
- export type Role = keyof typeof ROLES;
107
+ export const ROLE_NAMES = Object.keys(ROLES) as BuiltinRole[];
72
108
 
73
- export const ROLE_NAMES = Object.keys(ROLES) as Role[];
109
+ /** A custom role's id: lowercase, as a slug, and no built-in one's. */
110
+ export const ROLE_ID = /^[a-z][a-z0-9-]{1,31}$/;
74
111
 
75
- export function isRole(value: string): value is Role {
112
+ /** Whether `value` names a role of `policy`'s: a built-in one, as it ships, unless told. */
113
+ export function isRole(value: string, policy: Policy = DEFAULT_POLICY): value is Role {
114
+ return Object.hasOwn(policy.roles, value);
115
+ }
116
+
117
+ /** Whether `value` is one of the roles coffre ships. */
118
+ export function isBuiltinRole(value: string): value is BuiltinRole {
76
119
  return Object.hasOwn(ROLES, value);
77
120
  }
78
121
 
79
- export function roleGrants(role: Role, permission: Permission): boolean {
80
- return (ROLES[role].permissions as readonly Permission[]).includes(permission);
122
+ /** Whether `role` holds `permission` where nothing is protected, as `policy` defines it: as it ships, unless told. */
123
+ export function roleGrants(role: Role, permission: Permission, policy: Policy = DEFAULT_POLICY): boolean {
124
+ return definitionOf(policy, role)?.permissions.includes(permission) ?? false;
81
125
  }
82
126
 
83
127
  /** Roles that hold a project-only permission can only be granted on a project. */
84
- export function assignableToEnvironment(role: Role): boolean {
85
- return !ROLES[role].permissions.some((permission) =>
86
- PROJECT_ONLY_PERMISSIONS.includes(permission),
87
- );
128
+ export function assignableToEnvironment(role: Role, policy: Policy = DEFAULT_POLICY): boolean {
129
+ const definition = definitionOf(policy, role);
130
+ return definition !== undefined && !definition.permissions.some((permission) => PROJECT_ONLY_PERMISSIONS.includes(permission));
131
+ }
132
+
133
+ /** A project role's definition in `policy`, or undefined for none. */
134
+ export function definitionOf(policy: Policy, role: Role): RoleDefinition | undefined {
135
+ return Object.hasOwn(policy.roles, role) ? policy.roles[role] : undefined;
88
136
  }
89
137
 
90
138
  /**
@@ -98,32 +146,33 @@ export const INSTANCE_ROLES = {
98
146
  name: 'Member',
99
147
  description: 'None.',
100
148
  permissions: [],
149
+ protected: [],
101
150
  },
102
151
  auditor: {
103
152
  name: 'Auditor',
104
153
  description: 'Read the audit log. No secret values.',
105
154
  permissions: ['audit.read'],
155
+ protected: ['audit.read'],
106
156
  },
107
157
  developer: {
108
158
  name: 'Developer',
109
- description: 'Read and write secrets.',
110
- permissions: ['secret.read', 'secret.write'],
159
+ description: 'Read, use and write secrets.',
160
+ permissions: ['secret.read', 'secret.use', 'secret.write'],
161
+ protected: ['secret.use', 'secret.write'],
111
162
  },
112
163
  admin: {
113
164
  name: 'Admin',
114
165
  description: 'Manage people, service accounts, projects and access. No secret values.',
115
166
  permissions: ['audit.read', 'environment.manage', 'grant.manage', 'project.manage'],
167
+ protected: ['audit.read'],
116
168
  },
117
169
  owner: {
118
170
  name: 'Owner',
119
171
  description: 'Everything, every secret included.',
120
172
  permissions: [...PERMISSIONS],
173
+ protected: [...PERMISSIONS].filter((permission) => !PROJECT_ONLY_PERMISSIONS.includes(permission)),
121
174
  },
122
- } as const satisfies Record<string, {
123
- name: string;
124
- description: string;
125
- permissions: readonly Permission[];
126
- }>;
175
+ } as const satisfies Record<string, RoleDefinition>;
127
176
 
128
177
  export type InstanceRole = keyof typeof INSTANCE_ROLES;
129
178
 
@@ -133,8 +182,96 @@ export function isInstanceRole(value: string): value is InstanceRole {
133
182
  return Object.hasOwn(INSTANCE_ROLES, value);
134
183
  }
135
184
 
136
- export function instanceRoleGrants(role: InstanceRole, permission: Permission): boolean {
137
- return (INSTANCE_ROLES[role].permissions as readonly Permission[]).includes(permission);
185
+ /** Whether an instance role holds `permission` where nothing is protected, as `policy` defines it: as it ships, unless told. */
186
+ export function instanceRoleGrants(role: InstanceRole, permission: Permission, policy: Policy = DEFAULT_POLICY): boolean {
187
+ return (policy.instanceRoles[role]?.permissions ?? []).includes(permission);
188
+ }
189
+
190
+ /**
191
+ * The instance's access policy, which the vault keeps (docs/design/roles.md):
192
+ * its project roles, the built-ins as an Owner edited them and the ones an
193
+ * Owner made, its instance roles as edited, and which environments are
194
+ * protected, by id. The vault decides on it, and tells the app it with
195
+ * every member's access.
196
+ */
197
+ export type Policy = {
198
+ roles: Readonly<Record<Role, RoleDefinition>>;
199
+ instanceRoles: Readonly<Record<InstanceRole, RoleDefinition>>;
200
+ protected: readonly string[];
201
+ /**
202
+ * The protected environments by their project's id, each with its slug,
203
+ * which a scoped role's filters read: what a grant on a whole project
204
+ * reaches of them. A fork's slug is null until its row is written.
205
+ */
206
+ protectedIn: Readonly<Record<string, readonly { environmentId: string; slug: string | null }[]>>;
207
+ };
208
+
209
+ /** The policy before any Owner edits it: every role as it ships, and no environment protected. */
210
+ export const DEFAULT_POLICY: Policy = { roles: ROLES, instanceRoles: INSTANCE_ROLES, protected: [], protectedIn: {} };
211
+
212
+ /**
213
+ * How long the policy keeps an environment's id protected before its row
214
+ * is written, a fork's in flight, which writes it one call later; one with
215
+ * no row after that is a fork refused or abandoned. Until then it is a
216
+ * place a check on its project weighs (`protectedWithin`), which no scoped
217
+ * instance role's filters take in, so short. A fork writes its row only
218
+ * well within it, so no row ever brings back an id the policy dropped.
219
+ */
220
+ export const UNWRITTEN_FORK_MS = 10 * 60 * 1000;
221
+
222
+ /** The roles an Owner may not edit: Owner, which holds everything, and the instance's Member, which holds nothing. */
223
+ export const FIXED_ROLES = { roles: ['owner'] as readonly string[], instanceRoles: ['owner', 'member'] as readonly InstanceRole[] };
224
+
225
+ /**
226
+ * What is wrong with a role's definition, or null: a name and a
227
+ * description; known permissions, each once; reading implies using, in
228
+ * each column; and the protected column holds no more than the other, and
229
+ * nothing project-wide.
230
+ */
231
+ export function definitionProblem(definition: RoleDefinition): string | null {
232
+ const { name, description, permissions } = definition;
233
+ if (typeof name !== 'string' || name.trim() === '' || name.length > 40 || /[\u0000-\u001f\u007f]/.test(name)) return 'a role needs a name of 1 to 40 characters';
234
+ if (typeof description !== 'string' || description.length > 200 || /[\u0000-\u001f\u007f]/.test(description)) return 'a description is 200 characters at most';
235
+ for (const column of [permissions, definition.protected]) {
236
+ if (!Array.isArray(column) || column.some((permission) => !PERMISSIONS.includes(permission)) || new Set(column).size !== column.length) {
237
+ return `a role holds permissions from ${PERMISSIONS.join(', ')}, each once`;
238
+ }
239
+ if (column.includes('secret.read') && !column.includes('secret.use')) return 'a role that reads values uses them too: add secret.use';
240
+ }
241
+ if (definition.protected.some((permission) => PROJECT_ONLY_PERMISSIONS.includes(permission))) return 'a project-wide permission has one column: a project is never protected';
242
+ if (definition.protected.some((permission) => !permissions.includes(permission))) return 'a role holds no more in a protected environment than in one that is not';
243
+ return null;
244
+ }
245
+
246
+ /** A definition as the vault stores and compares it: each column in catalogue order. */
247
+ export function normalDefinition(definition: RoleDefinition): RoleDefinition {
248
+ const ordered = (column: readonly Permission[]) => PERMISSIONS.filter((permission) => column.includes(permission));
249
+ return { name: definition.name.trim(), description: definition.description, permissions: ordered(definition.permissions), protected: ordered(definition.protected) };
250
+ }
251
+
252
+ /**
253
+ * Whether `definition` gives `holder` `permission` at `place`: its
254
+ * protected column for a person in a protected environment, its other
255
+ * column anywhere else, and project-wide permissions from that one always.
256
+ */
257
+ export function holds(definition: RoleDefinition | undefined, permission: Permission, place: Place, holder: Pick<Holdings, 'policy' | 'service'>): boolean {
258
+ if (definition === undefined) return false;
259
+ if (PROJECT_ONLY_PERMISSIONS.includes(permission)) return definition.permissions.includes(permission);
260
+ return (guarded(holder, place) ? definition.protected : definition.permissions).includes(permission);
261
+ }
262
+
263
+ /** In a policy's `protected`, every environment: the policy the vault falls back on when it cannot read its own (`CLOSED_POLICY`). */
264
+ export const EVERY_ENVIRONMENT = '*';
265
+
266
+ /** Whether `holder` holds the protected column at `place`: a person, in an environment the policy protects. */
267
+ export function guarded(holder: Pick<Holdings, 'policy' | 'service'>, place: Place): boolean {
268
+ if (holder.service === true || place.environmentId == null) return false;
269
+ return protects(holder.policy ?? DEFAULT_POLICY, place.environmentId);
270
+ }
271
+
272
+ /** Whether `policy` protects the environment of this id: by name, or every one (`EVERY_ENVIRONMENT`). */
273
+ export function protects(policy: Policy, environmentId: string): boolean {
274
+ return policy.protected.includes(environmentId) || policy.protected.includes(EVERY_ENVIRONMENT);
138
275
  }
139
276
 
140
277
  /** The roles that manage people and access: Admin, and Owner, which adds every secret. */
@@ -286,8 +423,83 @@ export function grantKind(grant: GrantPlace): 'project' | 'environment' | null {
286
423
  * A person's personal token carries one too, each grant one they held when
287
424
  * they made it (`delegable` roles only), and is weighed the same way
288
425
  * against what they hold now, by their instance role or their grants.
426
+ *
427
+ * Each grant keeps what its role held when the credential was issued, both
428
+ * columns (`permissions`), and no more than its issuer held, so neither a
429
+ * role an Owner widens later nor its issuer widens the credential
430
+ * (docs/design/roles.md, section 8, rule 3).
431
+ */
432
+ export type CredentialScope = readonly ScopeGrant[];
433
+
434
+ /** What a role holds, or a credential's grant held when it was issued: where nothing is protected, and in a protected environment. */
435
+ export type Columns = { normal: readonly Permission[]; protected: readonly Permission[] };
436
+
437
+ /**
438
+ * One place of a credential's scope: a role there, and what it held when
439
+ * the credential was issued (`issuedGrant`). One kept by a release before
440
+ * 0.10, its role's name alone, holds that role as it ships, a constant no
441
+ * edit changes, so it never widens either: a built-in role's, or nothing
442
+ * for any other name.
443
+ */
444
+ export type ScopeGrant = GrantPlace & { role: Role; permissions?: Columns };
445
+
446
+ /**
447
+ * A grant of a scope with what its role holds now in `policy`, kept: what a
448
+ * credential issued now carries. Given what its issuer holds at its place
449
+ * (`heldColumns`), no more than that either, column by column, so that
450
+ * neither the role nor the issuer, widened later, widens the credential:
451
+ *
452
+ * viewer edited to read in prod; Ada, a Developer, uses there
453
+ * Ada's token, viewer on market read, use / use
454
+ * Developer widened to read in prod the token still only uses prod
455
+ */
456
+ export function issuedGrant(grant: GrantPlace & { role: Role }, policy: Policy = DEFAULT_POLICY, held?: Columns): ScopeGrant {
457
+ const definition = definitionOf(policy, grant.role);
458
+ const within = (column: readonly Permission[] = [], cap?: readonly Permission[]) => (cap === undefined ? [...column] : column.filter((permission) => cap.includes(permission)));
459
+ return {
460
+ projectId: grant.projectId,
461
+ environmentId: grant.environmentId,
462
+ role: grant.role,
463
+ permissions: { normal: within(definition?.permissions, held?.normal), protected: within(definition?.protected, held?.protected) },
464
+ };
465
+ }
466
+
467
+ /**
468
+ * What `holder` holds at `place` in each column a credential's grant there
469
+ * keeps (`issuedGrant`): `normal`, as if nothing were protected; `protected`,
470
+ * as a person in a protected environment. At an environment, as if it were
471
+ * protected; at a project, in an environment of it that no grant names,
472
+ * the least they hold in any of its environments, those it protects later
473
+ * included: only what covers the whole project reaches one.
474
+ *
475
+ * Ada, a Developer of market, at market read, use, write / use, write
289
476
  */
290
- export type CredentialScope = readonly (GrantPlace & { role: Role })[];
477
+ export function heldColumns(holder: Holdings, place: Place): Columns {
478
+ const policy = holder.policy ?? DEFAULT_POLICY;
479
+ const held = (protect: readonly string[], at: Place) => PERMISSIONS.filter((permission) => allows({ ...holder, policy: { ...policy, protected: protect } }, permission, at));
480
+ const anyOf: Place = place.environmentId != null ? place : { projectId: place.projectId, environmentId: '', environmentSlug: null };
481
+ return { normal: held([], place), protected: held([EVERY_ENVIRONMENT], anyOf) };
482
+ }
483
+
484
+ /**
485
+ * The protected environments a grant at `place` reaches beyond it: for a
486
+ * grant on a project, each of its environments `policy` protects, where a
487
+ * person holds the protected column and a service account the other one;
488
+ * none for a grant on an environment. Whoever checks a grant on a project
489
+ * against what someone holds checks it there too (`givesService`,
490
+ * `personalScope`): it reaches them.
491
+ */
492
+ export function protectedWithin(policy: Policy, place: Place): Place[] {
493
+ if (place.environmentId != null) return [];
494
+ return (policy.protectedIn[place.projectId] ?? []).map(({ environmentId, slug }) => ({ projectId: place.projectId, environmentId, environmentSlug: slug }));
495
+ }
496
+
497
+ /** What a scope's grant holds, as it was issued, as a role holds it: whatever the role is now, which no edit changes. */
498
+ export function scopeDefinition(grant: ScopeGrant): RoleDefinition {
499
+ if (grant.permissions !== undefined) return { name: grant.role, description: '', permissions: grant.permissions.normal, protected: grant.permissions.protected };
500
+ // Kept before 0.10: the role as it ships, whatever an Owner made of it since.
501
+ return isBuiltinRole(grant.role) ? ROLES[grant.role] : { name: grant.role, description: '', permissions: [], protected: [] };
502
+ }
291
503
 
292
504
  /** The most places a scope asked for names: far more than any credential needs, and a bound on what a request makes the app check. */
293
505
  export const MAX_SCOPE_PLACES = 1000;
@@ -299,12 +511,17 @@ export const MAX_SCOPE_PLACES = 1000;
299
511
  * than it was given. A project's Owner who wants a token for all of it
300
512
  * names `maintainer`.
301
513
  */
302
- export function delegable(role: Role): boolean {
303
- return !roleGrants(role, 'grant.manage');
514
+ export function delegable(role: Role, policy: Policy = DEFAULT_POLICY): boolean {
515
+ return isRole(role, policy) && !roleGrants(role, 'grant.manage', policy);
304
516
  }
305
517
 
306
518
  /** The roles a personal token's scope may name, in catalogue order. */
307
- export const DELEGABLE_ROLES: readonly Role[] = ROLE_NAMES.filter(delegable);
519
+ export function delegableRoles(policy: Policy = DEFAULT_POLICY): Role[] {
520
+ return Object.keys(policy.roles).filter((role) => delegable(role, policy));
521
+ }
522
+
523
+ /** The roles a personal token's scope may name, as they ship. */
524
+ export const DELEGABLE_ROLES: readonly Role[] = delegableRoles();
308
525
 
309
526
  /**
310
527
  * The longest a personal token lasts: a week. It is for an afternoon's
@@ -327,11 +544,22 @@ export function credentialScopeInWords(scope: Readonly<Record<string, string>>):
327
544
  export function isCredentialScope(value: unknown): value is CredentialScope {
328
545
  if (!Array.isArray(value)) return false;
329
546
  const places = new Set<string>();
547
+ const column = (list: unknown) => Array.isArray(list) && list.every((permission) => PERMISSIONS.includes(permission as Permission)) && new Set(list).size === list.length;
330
548
  return value.every((grant: unknown) => {
331
549
  if (typeof grant !== 'object' || grant === null || Array.isArray(grant)) return false;
332
- const { projectId, environmentId, role, ...rest } = grant as Record<string, unknown>;
333
- if (Object.keys(rest).length > 0 || typeof projectId !== 'string' || typeof role !== 'string' || !isRole(role)) return false;
334
- if (environmentId !== null && (typeof environmentId !== 'string' || !assignableToEnvironment(role))) return false;
550
+ const { projectId, environmentId, role, permissions, ...rest } = grant as Record<string, unknown>;
551
+ if (Object.keys(rest).length > 0 || typeof projectId !== 'string' || typeof role !== 'string') return false;
552
+ // As issued, both columns; or, kept before 0.10, a built-in role's name alone, which holds it as it ships.
553
+ if (!ROLE_ID.test(role)) return false;
554
+ if (permissions === undefined) {
555
+ if (!isBuiltinRole(role)) return false;
556
+ } else {
557
+ if (typeof permissions !== 'object' || permissions === null || Array.isArray(permissions)) return false;
558
+ const { normal, protected: guarded, ...more } = permissions as Record<string, unknown>;
559
+ if (Object.keys(more).length > 0 || !column(normal) || !column(guarded)) return false;
560
+ }
561
+ const definition = scopeDefinition(grant as ScopeGrant);
562
+ if (environmentId !== null && (typeof environmentId !== 'string' || definition.permissions.some((permission) => PROJECT_ONLY_PERMISSIONS.includes(permission)))) return false;
335
563
  const place = `${projectId}/${environmentId ?? ''}`;
336
564
  if (places.has(place)) return false;
337
565
  places.add(place);
@@ -359,6 +587,10 @@ export type Holdings = {
359
587
  * holder's instance role.
360
588
  */
361
589
  credentialScope?: CredentialScope | null;
590
+ /** The instance's policy, its roles and protected environments, as the vault said it: as it ships, absent. */
591
+ policy?: Policy;
592
+ /** A service account's, which holds each role's normal column everywhere; a person's holds a protected environment's column there. */
593
+ service?: boolean;
362
594
  };
363
595
 
364
596
  /** Someone who holds nothing: a stranger, a removed member, a tampered row. */
@@ -391,9 +623,10 @@ export function covers(grant: GrantPlace, place: Place): boolean {
391
623
  * `billing`.
392
624
  */
393
625
  export function allows(holder: Holdings, permission: Permission, place: Place): boolean {
394
- if (holder.credentialScope != null && !holdsAt(holder.credentialScope, permission, place)) return false;
395
- if (instanceRoleGrants(holder.role, permission) && inScope(holder.scope, place)) return true;
396
- return holdsAt(holder.grants, permission, place);
626
+ if (holder.credentialScope != null && !scopeHolds(holder, permission, place)) return false;
627
+ const policy = holder.policy ?? DEFAULT_POLICY;
628
+ if (inScope(holder.scope, place) && holds(policy.instanceRoles[holder.role], permission, place, holder)) return true;
629
+ return holder.grants.some((grant) => covers(grant, place) && holds(definitionOf(policy, grant.role), permission, place, holder));
397
630
  }
398
631
 
399
632
  /**
@@ -404,12 +637,12 @@ export function allows(holder: Holdings, permission: Permission, place: Place):
404
637
  * role its scope names there: a viewer's token reads it, and writes nothing.
405
638
  */
406
639
  export function withinCredential(holder: Holdings, permission: Permission, place: Place): boolean {
407
- return holder.credentialScope == null || holdsAt(holder.credentialScope, permission, place);
640
+ return holder.credentialScope == null || scopeHolds(holder, permission, place);
408
641
  }
409
642
 
410
- /** Whether a grant among `grants` covers `place` with a role that holds `permission`. */
411
- function holdsAt(grants: readonly (GrantPlace & { role: Role })[], permission: Permission, place: Place): boolean {
412
- return grants.some((grant) => covers(grant, place) && roleGrants(grant.role, permission));
643
+ /** Whether the credential's scope covers `place` with a grant that held `permission` there when it was issued. */
644
+ function scopeHolds(holder: Holdings, permission: Permission, place: Place): boolean {
645
+ return (holder.credentialScope ?? []).some((grant) => covers(grant, place) && holds(scopeDefinition(grant), permission, place, holder));
413
646
  }
414
647
 
415
648
  /**
@@ -451,18 +684,32 @@ export type ServiceSetting = Scope;
451
684
  * developer there, never maintainer; a grant on `market` takes holding it
452
685
  * on all of `market`. `setting` is null for a service account, which sets
453
686
  * up none; a request on a credential with a scope sets none up either,
454
- * since what it set up would outlive it.
687
+ * since what it set up would outlive it. A service account holds a role's
688
+ * normal column even in a protected environment, so a person there, who
689
+ * holds its protected column, gives none what they do not hold themselves:
690
+ * a Developer of a protected prod, who only uses it, gives no viewer there.
455
691
  */
456
- export function givesService(holder: Holdings, setting: ServiceSetting | null, role: Role, place: Place): boolean {
692
+ export function givesService(holder: Holdings, setting: ServiceSetting | null, role: Role, place: Place, kept?: RoleDefinition): boolean {
457
693
  if (mayManageAccess(holder, place)) return true;
458
- return setting !== null && holder.credentialScope == null && inScope(setting, place)
459
- && ROLES[role].permissions.every((permission) => allows(holder, permission, place));
694
+ const policy = holder.policy ?? DEFAULT_POLICY;
695
+ // What the grant holds: its role as the policy defines it, or what a credential kept of it (`issuesCredential`).
696
+ const definition = kept ?? definitionOf(policy, role);
697
+ // A role that holds nothing is given by whoever manages access there alone: by anyone else, it would be a grant an
698
+ // Owner could fill in later, and under a policy the vault cannot read, every role but Owner's holds nothing.
699
+ if (definition === undefined || definition.permissions.length === 0) return false;
700
+ if (setting === null || holder.credentialScope != null || !inScope(setting, place)) return false;
701
+ if (!definition.permissions.every((permission) => allows(holder, permission, place))) return false;
702
+ // A grant on a whole project reaches its protected environments too, where the service holds the role's normal column:
703
+ // the person giving it holds that there as well, or gives none.
704
+ const inEnvironments = definition.permissions.filter((permission) => !PROJECT_ONLY_PERMISSIONS.includes(permission));
705
+ return protectedWithin(policy, place).every((there) => inEnvironments.every((permission) => allows(holder, permission, there)));
460
706
  }
461
707
 
462
708
  /** Whether `holder` gives a service account anything anywhere among `places`: whether they set any up. */
463
709
  export function setsUpServices(holder: Holdings, setting: ServiceSetting | null, places: readonly Place[]): boolean {
464
710
  if (runsInstance(holder)) return true;
465
- return places.some((place) => ROLE_NAMES.some((role) => givesService(holder, setting, role, place)));
711
+ const roles = Object.keys((holder.policy ?? DEFAULT_POLICY).roles);
712
+ return places.some((place) => roles.some((role) => givesService(holder, setting, role, place)));
466
713
  }
467
714
 
468
715
  /** A service account as `managesService` weighs it: its live grants, where they are, and who admitted it. */
@@ -492,7 +739,9 @@ export function managesService(holder: Holdings, setting: ServiceSetting | null,
492
739
  * Whether `holder`, the member `actor`, may issue a token or a trust
493
740
  * binding of `account` whose scope is `scope`: they manage the account
494
741
  * (`managesService`), and each grant of the scope is one they could give it
495
- * (`givesService`) and one it holds, every permission of its role there.
742
+ * (`givesService`) and one it holds, every permission of its role there;
743
+ * of a grant that keeps less than its role, every permission it `kept`, as
744
+ * a binding replacing others keeps what they held.
496
745
  * For an account that holds `developer` on `market/dev`, a Developer of
497
746
  * `dev` issues `developer` or `viewer` there; nobody issues `market/prod`
498
747
  * for it, or `maintainer` on `market/dev`, until the account holds them.
@@ -502,24 +751,29 @@ export function issuesCredential(
502
751
  setting: ServiceSetting | null,
503
752
  actor: string,
504
753
  account: ServiceAccount,
505
- scope: ServiceAccount['grants'],
754
+ scope: readonly { role: Role; place: Place; kept?: RoleDefinition }[],
506
755
  ): boolean {
507
756
  if (!managesService(holder, setting, actor, account)) return false;
508
- const held: Holdings = { ...NOTHING, grants: account.grants.map(({ role, place }) => ({ projectId: place.projectId, environmentId: place.environmentId ?? null, role })) };
509
- return scope.every(({ role, place }) =>
510
- givesService(holder, setting, role, place) && ROLES[role].permissions.every((permission) => allows(held, permission, place)));
757
+ const policy = holder.policy ?? DEFAULT_POLICY;
758
+ const held: Holdings = { ...NOTHING, policy, service: true, grants: account.grants.map(({ role, place }) => ({ projectId: place.projectId, environmentId: place.environmentId ?? null, role })) };
759
+ return scope.every(({ role, place, kept }) => givesService(holder, setting, role, place, kept)
760
+ && ((kept ?? definitionOf(policy, role))?.permissions.every((permission) => allows(held, permission, place)) ?? false));
511
761
  }
512
762
 
513
763
  /**
514
764
  * Whether the holder reads the whole log, the instance's own entries
515
765
  * (sign-ins, people, service accounts, settings) with every project's, and
516
766
  * verifies it: whoever holds `audit.read` by an instance role whose scope
517
- * narrows nothing, an Auditor's included. Reading, not
518
- * running: an Auditor of the whole instance changes nothing it reads about.
519
- * Anyone else reads the places they hold `audit.read` in.
767
+ * narrows nothing, in both its columns, an Auditor's included: an Auditor
768
+ * edited to read no protected environment's log reads every other place's,
769
+ * and not the whole. Reading, not running: an Auditor of the whole
770
+ * instance changes nothing it reads about. Anyone else reads the places
771
+ * they hold `audit.read` in.
520
772
  */
521
773
  export function readsWholeLog(holder: Holdings): boolean {
522
- return holder.credentialScope == null && instanceRoleGrants(holder.role, 'audit.read') && unscoped(holder.scope);
774
+ const role = (holder.policy ?? DEFAULT_POLICY).instanceRoles[holder.role];
775
+ return holder.credentialScope == null && unscoped(holder.scope)
776
+ && role !== undefined && role.permissions.includes('audit.read') && role.protected.includes('audit.read');
523
777
  }
524
778
 
525
779
  /**
package/src/context.ts CHANGED
@@ -12,9 +12,12 @@ import { createHash } from 'node:crypto';
12
12
  * names would mean that renaming an environment or a secret key makes every
13
13
  * existing ciphertext permanently undecryptable.
14
14
  *
15
- * A personal config's values are bound to their owner too, `owner`, which
16
- * only the vault's wrap of the data key carries (docs/design/forking.md,
17
- * section 4): a forged owner column fails to open, rather than granting.
15
+ * A personal config's values are bound to their owner too, `owner`, and a
16
+ * sensitive value to being one, `sensitive`, which only the vault's wrap of
17
+ * the data key carries (docs/design/forking.md, section 4;
18
+ * docs/design/credential-proxy.md, section 2): a forged owner or sensitivity
19
+ * column fails to open, rather than granting. The value's own ciphertext
20
+ * binds the ids alone, so a version made sensitive keeps its ciphertext.
18
21
  */
19
22
  export type SecretContext = {
20
23
  projectId: string;
@@ -22,6 +25,8 @@ export type SecretContext = {
22
25
  secretId: string;
23
26
  /** A personal config's owner, as `ownerKey` hashes them. */
24
27
  owner?: string;
28
+ /** A sensitive value's: never handed back to a person (`sensitive` in @coffre/core/vault). Absent otherwise, never false. */
29
+ sensitive?: true;
25
30
  };
26
31
 
27
32
  /**
@@ -39,7 +44,7 @@ function assertUuid(value: string, field: string): void {
39
44
  }
40
45
  }
41
46
 
42
- /** Throw unless every field is a lowercase UUID, and an owner a lowercase SHA-256. */
47
+ /** Throw unless every field is a lowercase UUID, an owner a lowercase SHA-256, and `sensitive` true if there. */
43
48
  export function checkContext(ctx: SecretContext): void {
44
49
  assertUuid(ctx.projectId, 'projectId');
45
50
  assertUuid(ctx.environmentId, 'environmentId');
@@ -47,6 +52,7 @@ export function checkContext(ctx: SecretContext): void {
47
52
  if (ctx.owner !== undefined && (typeof ctx.owner !== 'string' || !OWNER_RE.test(ctx.owner))) {
48
53
  throw new Error(`context.owner must be a lowercase SHA-256, got: ${String(ctx.owner)}`);
49
54
  }
55
+ if (ctx.sensitive !== undefined && ctx.sensitive !== true) throw new Error(`context.sensitive is true or absent, got: ${String(ctx.sensitive)}`);
50
56
  }
51
57
 
52
58
  const OWNER_RE = /^[0-9a-f]{64}$/;
@@ -70,7 +76,7 @@ export function ownerKey(member: string): string {
70
76
  export function encodeAad(ctx: SecretContext): Buffer {
71
77
  checkContext(ctx);
72
78
  return Buffer.from(
73
- `${AAD_VERSION}|${ctx.projectId}|${ctx.environmentId}|${ctx.secretId}${ctx.owner === undefined ? '' : `|owner:${ctx.owner}`}`,
79
+ `${AAD_VERSION}|${ctx.projectId}|${ctx.environmentId}|${ctx.secretId}${ctx.owner === undefined ? '' : `|owner:${ctx.owner}`}${ctx.sensitive === true ? '|sensitive' : ''}`,
74
80
  'utf8',
75
81
  );
76
82
  }
package/src/envelope.ts CHANGED
@@ -42,13 +42,14 @@ export function freshDek(): Buffer {
42
42
  }
43
43
 
44
44
  /**
45
- * Encrypt a secret value under `dek`, bound to `ctx`. Whoever holds the key
46
- * encryption key wraps `dek` separately: the vault, in coffre.
45
+ * Encrypt a secret value under `dek`, bound to `ctx`'s ids. Whoever holds
46
+ * the key encryption key wraps `dek` separately: the vault, in coffre, whose
47
+ * wrap binds the owner and sensitivity too.
47
48
  */
48
- export function encrypt(plaintext: Buffer, ctx: SecretContext, dek: Buffer): Sealed {
49
+ export function encrypt(plaintext: Buffer, ctx: SecretIds, dek: Buffer): Sealed {
49
50
  const iv = randomBytes(IV_BYTES);
50
51
  const cipher = createCipheriv('aes-256-gcm', dek, iv);
51
- cipher.setAAD(encodeAad(ctx));
52
+ cipher.setAAD(valueAad(ctx));
52
53
  const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
53
54
  return { envelopeVersion: ENVELOPE_VERSION, iv, authTag: cipher.getAuthTag(), ciphertext };
54
55
  }
@@ -59,7 +60,7 @@ export function encrypt(plaintext: Buffer, ctx: SecretContext, dek: Buffer): Sea
59
60
  * the AAD will not match. This is the property that makes relocating a
60
61
  * ciphertext across environments fail closed.
61
62
  */
62
- export function decrypt(envelope: Sealed, ctx: SecretContext, dek: Buffer): Buffer {
63
+ export function decrypt(envelope: Sealed, ctx: SecretIds, dek: Buffer): Buffer {
63
64
  if (envelope.envelopeVersion !== ENVELOPE_VERSION) {
64
65
  throw new Error(`unsupported envelope version: ${envelope.envelopeVersion}`);
65
66
  }
@@ -70,11 +71,18 @@ export function decrypt(envelope: Sealed, ctx: SecretContext, dek: Buffer): Buff
70
71
  throw new Error('envelope auth tag has the wrong length');
71
72
  }
72
73
  const decipher = createDecipheriv('aes-256-gcm', dek, envelope.iv);
73
- decipher.setAAD(encodeAad(ctx));
74
+ decipher.setAAD(valueAad(ctx));
74
75
  decipher.setAuthTag(envelope.authTag);
75
76
  return Buffer.concat([decipher.update(envelope.ciphertext), decipher.final()]);
76
77
  }
77
78
 
79
+ /** What a value's own ciphertext binds: the secret's ids, never its owner or sensitivity, which only the wrap of its key does. */
80
+ export type SecretIds = Pick<SecretContext, 'projectId' | 'environmentId' | 'secretId'>;
81
+
82
+ function valueAad(ctx: SecretIds): Buffer {
83
+ return encodeAad({ projectId: ctx.projectId, environmentId: ctx.environmentId, secretId: ctx.secretId });
84
+ }
85
+
78
86
  /**
79
87
  * Encrypt a secret value under a fresh DEK, and wrap that DEK under the
80
88
  * registry's primary KEK: `encrypt` and the wrap in one, where both halves
@@ -5,7 +5,7 @@ import { createHash, randomBytes } from 'node:crypto';
5
5
  * service tokens, personal tokens, which act as the person who made
6
6
  * them within the scope they named, and handles, which reach nothing but
7
7
  * the credential proxy (`@coffre/server/plugins/credential-proxy`): the
8
- * stand-in a person's app holds in place of a secret's value.
8
+ * placeholder a person's app holds in place of a secret's value.
9
9
  *
10
10
  * A token is a kind prefix and 32 random bytes, e.g.
11
11
  * `coffre_cli_Qm9Y...`. The prefix tells a person (or a secret scanner) what a