@fabrika/iam 0.9.0-dev.36 → 0.9.0-dev.37

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.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  type CreateGrantRequest,
3
3
  type GrantChangeResponse,
4
+ type GrantDto,
4
5
  type OkResponse,
5
6
  type PendingGrantChange,
6
7
  type UpdateGrantInput,
@@ -10,7 +11,7 @@ import { ExternalGrantError, type GrantRow } from '../db'
10
11
  import { parseStoredPermissions } from '../stored-permissions'
11
12
  import { type AdminContext, adminEvent, fail } from './context'
12
13
  import { type GrantChangeRequest, grantsWait, requestGrantChange } from './grant-requests'
13
- import { appField, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDto } from './grant-support'
14
+ import { appField, grantIdOf, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDto } from './grant-support'
14
15
  import { requireGrantablePrincipal, requireManagedApp } from './user-admin'
15
16
 
16
17
  export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantChangeResponse> {
@@ -31,7 +32,7 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
31
32
  }
32
33
  const scope = parseScope(input)
33
34
  if (!scope.ok) {
34
- return fail(400, 'scopeType and scopeValue must be both set or both omitted')
35
+ return fail(400, scope.message)
35
36
  }
36
37
  const principal = await c.services.repositories.principals.getPrincipalById(principalId)
37
38
  if (!principal) {
@@ -52,13 +53,15 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
52
53
  if (external !== null) {
53
54
  return fail(409, external)
54
55
  }
55
- const values = { principalId, app, scopeType: scope.scopeType, scopeValue: scope.scopeValue, grantedBy: c.admin.id, expiresAt }
56
+ const { scopeType, scopeValues } = scope
57
+ const values = { principalId, app, scopeType, grantedBy: c.admin.id, expiresAt }
56
58
  const roleKey = roleOrInline.roleKey
57
59
  if (app !== null && await grantsWait(c.services, app)) {
58
60
  if (roleKey !== null) {
59
- const held = await findHeldRoleGrant(c, { ...values, roleKey })
60
- if (held !== undefined && (held.expires_at === null || held.expires_at > Math.floor(Date.now() / 1000))) {
61
- return fail(409, `principal ${principalId} already holds this grant: ${held.id}`)
61
+ const held = await findHeldRoleGrant(c, { ...values, roleKey, scopeValues })
62
+ // An expired app-wide grant is renewed in place; a scoped value is refused by the unique index, expired or not.
63
+ if (held !== undefined && (scopeValues !== null || held.expires_at === null || held.expires_at > Math.floor(Date.now() / 1000))) {
64
+ return fail(409, `principal ${principalId} already holds this grant: ${grantIdOf(held)}`)
62
65
  }
63
66
  }
64
67
  return await pendingChange(c, {
@@ -68,8 +71,8 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
68
71
  grantId: null,
69
72
  roleKey,
70
73
  permissions: roleOrInline.permissions,
71
- scopeType: scope.scopeType,
72
- scopeValue: scope.scopeValue,
74
+ scopeType,
75
+ scopeValues,
73
76
  grantExpiresAt: expiresAt,
74
77
  requestedBy: c.admin.id,
75
78
  })
@@ -83,45 +86,72 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
83
86
  principalId,
84
87
  roleKey: roleOrInline.roleKey,
85
88
  permissions: roleOrInline.permissions,
86
- scopeType: scope.scopeType,
87
- scopeValue: scope.scopeValue,
89
+ scopeType,
90
+ scopeValue: scopeValues?.[0] ?? null,
91
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
88
92
  app,
89
93
  },
90
94
  })
91
- let grant: GrantRow
95
+ const heldMessage = (held: GrantRow | undefined) =>
96
+ `principal ${principalId} already holds this grant${held === undefined ? '' : `: ${grantIdOf(held)}`}`
97
+ const findHeld = (key: string) => findHeldRoleGrant(c, { ...values, roleKey: key, scopeValues }).catch(() => undefined)
98
+ let rows: GrantRow[]
92
99
  try {
93
- if (roleKey === null) {
94
- grant = await c.services.repositories.grants.createGrant({ ...values, permissions: roleOrInline.permissions }, record)
95
- } else {
96
- const created = await c.services.repositories.grants.createRoleGrantUnlessHeld({ ...values, roleKey }, record)
97
- if (created === null) {
98
- const held = await findHeldRoleGrant(c, { ...values, roleKey }).catch(() => undefined)
99
- const naming = held === undefined ? '' : `: ${held.id}`
100
- return fail(409, `principal ${principalId} already holds this grant${naming}`)
100
+ if (scopeValues !== null && scopeValues.length > 1) {
101
+ // One row per value: a value the principal already holds this role in fails the unique index, so name it first.
102
+ const held = roleKey === null ? undefined : await findHeld(roleKey)
103
+ if (held !== undefined) return fail(409, heldMessage(held))
104
+ try {
105
+ rows = await c.services.repositories.grants.createGrantSet({ ...values, roleKey, permissions: roleOrInline.permissions, scopeValues }, record)
106
+ } catch (cause) {
107
+ if (cause instanceof ExternalGrantError || roleKey === null) throw cause
108
+ const raced = await findHeld(roleKey)
109
+ if (raced !== undefined) return fail(409, heldMessage(raced))
110
+ throw cause
101
111
  }
102
- grant = created
112
+ } else if (roleKey === null) {
113
+ rows = [
114
+ await c.services.repositories.grants.createGrant(
115
+ { ...values, scopeValue: scopeValues?.[0] ?? null, permissions: roleOrInline.permissions },
116
+ record,
117
+ ),
118
+ ]
119
+ } else {
120
+ const created = await c.services.repositories.grants.createRoleGrantUnlessHeld(
121
+ { ...values, scopeValue: scopeValues?.[0] ?? null, roleKey },
122
+ record,
123
+ )
124
+ if (created === null) return fail(409, heldMessage(await findHeld(roleKey)))
125
+ rows = [created]
103
126
  }
104
127
  } catch (cause) {
105
128
  // A reconcile narrowed the role between the check above and the write, which carries the condition itself.
106
129
  if (cause instanceof ExternalGrantError) return fail(409, cause.message)
107
130
  throw cause
108
131
  }
109
- const cache = new RoleKnownCache(c.services)
110
- return toGrantDto(grant, cache)
132
+ return grantDto(rows, new RoleKnownCache(c.services))
133
+ }
134
+
135
+ function grantDto(rows: readonly GrantRow[], cache: RoleKnownCache): Promise<GrantDto> {
136
+ const [first, ...rest] = rows
137
+ if (first === undefined) return fail(409, 'The access changed. Refresh and try again.')
138
+ return toGrantDto([first, ...rest], cache)
111
139
  }
112
140
 
113
141
  export async function deleteGrantUseCase(c: AdminContext, input: { id: string }): Promise<OkResponse & Partial<PendingGrantChange>> {
114
- const id = input.id
115
- const grant = await c.services.repositories.grants.getGrantById(id)
116
- if (!grant) {
142
+ const read = await c.services.repositories.grants.getGrantSet(input.id)
143
+ if (read === null) {
117
144
  return fail(404, 'grant not found')
118
145
  }
146
+ const [grant] = read.rows
119
147
  requireManagedApp(c, grant.app)
120
148
  const principal = await c.services.repositories.principals.getPrincipalById(grant.principal_id)
121
149
  if (!principal) {
122
150
  return fail(404, 'grant not found')
123
151
  }
124
152
  requireGrantablePrincipal(c, principal)
153
+ const id = grantIdOf(grant)
154
+ const scopeValues = scopeValuesOf(read.rows)
125
155
  if (grant.app !== null && await grantsWait(c.services, grant.app)) {
126
156
  return {
127
157
  ok: true,
@@ -129,18 +159,19 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
129
159
  app: grant.app,
130
160
  kind: 'revoke',
131
161
  principalId: grant.principal_id,
132
- grantId: grant.id,
162
+ grantId: id,
133
163
  roleKey: grant.role_key,
134
164
  permissions: grant.permissions === null ? null : parseStoredPermissions(grant.permissions),
135
165
  scopeType: grant.scope_type,
136
- scopeValue: grant.scope_value,
166
+ scopeValues,
137
167
  grantExpiresAt: grant.expires_at,
138
168
  requestedBy: c.admin.id,
139
169
  }),
140
170
  }
141
171
  }
142
- await c.services.repositories.grants.deleteGrant(
172
+ await c.services.repositories.grants.deleteGrantSet(
143
173
  id,
174
+ grant.principal_id,
144
175
  adminEvent(c, {
145
176
  action: 'iam.grant.revoke',
146
177
  resourceType: 'grant',
@@ -149,7 +180,8 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
149
180
  principalId: grant.principal_id,
150
181
  roleKey: grant.role_key,
151
182
  scopeType: grant.scope_type,
152
- scopeValue: grant.scope_value,
183
+ scopeValue: scopeValues?.[0] ?? null,
184
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
153
185
  },
154
186
  }),
155
187
  )
@@ -158,8 +190,9 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
158
190
 
159
191
  /** Edit a grant in place within its original application. Both paths use the same role, scope and external-person rules. */
160
192
  export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantChangeResponse> {
161
- const grant = await c.services.repositories.grants.getGrantById(input.id)
162
- if (grant === null) return fail(404, 'grant not found')
193
+ const read = await c.services.repositories.grants.getGrantSet(input.id)
194
+ if (read === null) return fail(404, 'grant not found')
195
+ const [grant] = read.rows
163
196
  requireManagedApp(c, grant.app)
164
197
  const principal = await c.services.repositories.principals.getPrincipalById(grant.principal_id)
165
198
  if (principal === null) return fail(404, 'principal not found')
@@ -167,7 +200,7 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
167
200
  const authorization = await parseRoleOrInline(c, input, grant.app)
168
201
  if (!authorization.ok) return fail(400, authorization.message)
169
202
  const scope = parseScope(input)
170
- if (!scope.ok) return fail(400, 'scopeType and scopeValue must be both set or both omitted')
203
+ if (!scope.ok) return fail(400, scope.message)
171
204
  const problem = await contractGrantProblem(
172
205
  c.services.repositories.appSchema,
173
206
  grant.app,
@@ -178,19 +211,23 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
178
211
  if (problem !== null) return fail(409, problem)
179
212
  const expiresAt = input.expiresAt ?? null
180
213
  if (expiresAt !== null && expiresAt <= Math.floor(Date.now() / 1000)) return fail(400, 'Choose an expiration in the future, or no expiration.')
181
- const values = { principalId: principal.id, app: grant.app, ...authorization, ...scope, expiresAt }
214
+ const id = grantIdOf(grant)
215
+ const before = scopeValuesOf(read.rows)
216
+ const { scopeType, scopeValues } = scope
182
217
  if (
183
218
  grant.role_key === authorization.roleKey
184
219
  && grant.permissions === (authorization.permissions === null ? null : JSON.stringify(authorization.permissions))
185
- && grant.scope_type === scope.scopeType && grant.scope_value === scope.scopeValue && grant.expires_at === expiresAt
220
+ && grant.scope_type === scopeType && sameValues(before, scopeValues)
221
+ && read.rows.every((row) => row.expires_at === expiresAt)
186
222
  ) {
187
- return toGrantDto(grant, new RoleKnownCache(c.services))
223
+ return toGrantDto(read.rows, new RoleKnownCache(c.services))
188
224
  }
189
225
  const duplicate = async () =>
190
226
  authorization.roleKey !== null
191
227
  && (await c.services.repositories.grants.listGrants(principal.id)).some((other) =>
192
- other.id !== grant.id && other.app === grant.app && other.role_key === authorization.roleKey
193
- && other.scope_type === scope.scopeType && other.scope_value === scope.scopeValue
228
+ grantIdOf(other) !== id && other.app === grant.app && other.role_key === authorization.roleKey
229
+ && other.scope_type === scopeType
230
+ && (scopeValues === null ? other.scope_value === null : other.scope_value !== null && scopeValues.includes(other.scope_value))
194
231
  )
195
232
  const held = principal.type === 'user'
196
233
  ? 'This user already has that role in this scope. Edit the existing access instead.'
@@ -201,62 +238,84 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
201
238
  app: grant.app,
202
239
  kind: 'update',
203
240
  principalId: principal.id,
204
- grantId: grant.id,
241
+ grantId: id,
205
242
  roleKey: authorization.roleKey,
206
243
  permissions: authorization.permissions,
207
- scopeType: scope.scopeType,
208
- scopeValue: scope.scopeValue,
244
+ scopeType,
245
+ scopeValues,
209
246
  grantExpiresAt: expiresAt,
210
247
  requestedBy: c.admin.id,
211
248
  })
212
249
  }
213
- let updated: GrantRow | null
250
+ let updated: GrantRow[] | null
214
251
  try {
215
- updated = await c.services.repositories.grants.updateGrant(
216
- grant,
217
- values,
252
+ updated = await c.services.repositories.grants.replaceGrantSet(
253
+ read,
254
+ {
255
+ principalId: principal.id,
256
+ app: grant.app,
257
+ ...authorization,
258
+ scopeType,
259
+ scopeValues,
260
+ grantedBy: grant.granted_by,
261
+ expiresAt,
262
+ createdAt: Math.min(...read.rows.map((row) => row.created_at)),
263
+ },
218
264
  adminEvent(c, {
219
265
  action: 'iam.grant.update',
220
266
  resourceType: 'grant',
221
- resourceId: grant.id,
267
+ resourceId: id,
222
268
  metadata: { principalId: principal.id, app: grant.app },
223
269
  diff: {
224
270
  before: {
225
271
  roleKey: grant.role_key,
226
272
  permissions: grant.permissions === null ? null : JSON.parse(grant.permissions),
227
273
  scopeType: grant.scope_type,
228
- scopeValue: grant.scope_value,
274
+ scopeValue: before?.[0] ?? null,
275
+ ...(before !== null && before.length > 1 ? { scopeValues: before } : {}),
229
276
  expiresAt: grant.expires_at,
230
277
  },
231
278
  after: {
232
279
  roleKey: authorization.roleKey,
233
280
  permissions: authorization.permissions,
234
- scopeType: scope.scopeType,
235
- scopeValue: scope.scopeValue,
281
+ scopeType,
282
+ scopeValue: scopeValues?.[0] ?? null,
283
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
236
284
  expiresAt,
237
285
  },
238
286
  },
239
287
  }),
240
288
  )
241
289
  } catch (cause) {
290
+ if (cause instanceof ExternalGrantError) return fail(409, cause.message)
242
291
  if (await duplicate()) return fail(409, held)
243
292
  throw cause
244
293
  }
245
294
  if (updated === null) return fail(409, 'The access changed or is no longer allowed. Refresh and try again.')
246
- return toGrantDto(updated, new RoleKnownCache(c.services))
295
+ return grantDto(updated, new RoleKnownCache(c.services))
296
+ }
297
+
298
+ /** The sorted values of a grant's rows; null for a global grant. */
299
+ function scopeValuesOf(rows: readonly GrantRow[]): string[] | null {
300
+ const values = rows.flatMap((row) => row.scope_value === null ? [] : [row.scope_value])
301
+ return values.length === 0 ? null : values.sort((a, b) => a < b ? -1 : a > b ? 1 : 0)
302
+ }
303
+
304
+ function sameValues(a: readonly string[] | null, b: readonly string[] | null): boolean {
305
+ return a === null || b === null ? a === b : a.length === b.length && a.every((value, index) => value === b[index])
247
306
  }
248
307
 
249
- /** The held grant a refused role grant duplicates, to name it in the 409; it may be gone by the time this reads. */
308
+ /** A held grant a refused role grant duplicates in one of its values, to name it in the 409; it may be gone by the time this reads. */
250
309
  async function findHeldRoleGrant(
251
310
  c: AdminContext,
252
- candidate: { principalId: string; app: string | null; roleKey: string; scopeType: string | null; scopeValue: string | null },
311
+ candidate: { principalId: string; app: string | null; roleKey: string; scopeType: string | null; scopeValues: readonly string[] | null },
253
312
  ): Promise<GrantRow | undefined> {
254
313
  const held = await c.services.repositories.grants.listGrants(candidate.principalId)
255
314
  return held.find((row) =>
256
315
  row.role_key === candidate.roleKey
257
316
  && row.app === candidate.app
258
317
  && row.scope_type === candidate.scopeType
259
- && row.scope_value === candidate.scopeValue
318
+ && (candidate.scopeValues === null ? row.scope_value === null : row.scope_value !== null && candidate.scopeValues.includes(row.scope_value))
260
319
  )
261
320
  }
262
321
 
package/src/admin/rpc.ts CHANGED
@@ -34,6 +34,7 @@ const authorization = {
34
34
  permissions: z.array(nonEmpty).optional(),
35
35
  scopeType: optionalNullableString,
36
36
  scopeValue: optionalNullableString,
37
+ scopeValues: z.array(z.string()).optional(),
37
38
  app: optionalNullableString,
38
39
  expiresAt: z.number().finite().optional().nullable(),
39
40
  }
package/src/db.ts CHANGED
@@ -46,7 +46,7 @@ export { type InstallationBrandImages, InstallationBrandRepository, type Install
46
46
  export { type CredentialGrantRow, CredentialRepository, type CredentialRow } from './repositories/credentials'
47
47
  export { DeviceAuthorizationRepository, type DeviceAuthorizationRow, type DeviceReceiptRow } from './repositories/device'
48
48
  export { type CreateGrantRequestInput, GrantRequestRepository, type GrantRequestRow } from './repositories/grant-requests'
49
- export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow } from './repositories/grants'
49
+ export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow, type GrantSetRead } from './repositories/grants'
50
50
  export { type AuthCodeRow, HandoffRepository } from './repositories/handoff'
51
51
  export {
52
52
  type DelegationGrantRow,
@@ -1,4 +1,4 @@
1
- import { parseJsonStringArray, terminalIdentifyProblem, type WorkloadKind } from '@fabrika/auth-core'
1
+ import { type DimensionValue, parseJsonStringArray, terminalIdentifyProblem, type WorkloadKind } from '@fabrika/auth-core'
2
2
  import { type SqlDatabase, type SqlStatement } from '@fabrika/platform'
3
3
 
4
4
  import { type AuditEventInput, auditEventStatement, AuditWriter } from './audit'
@@ -40,6 +40,8 @@ export interface AppScopeRow {
40
40
  members_directory: 'labels' | null
41
41
  /** A JSON array of the actions that look up one member (`findMember`), or null for none. */
42
42
  members_lookup: string | null
43
+ /** A JSON array of the `{ value, label? }` the console offers for a grant here (ADR-0085), or null for none. */
44
+ value_list: string | null
43
45
  }
44
46
 
45
47
  /** A share-link mount (the `app_link_mounts` table). `grants` is a JSON array of exact actions. */
@@ -350,6 +352,7 @@ export class AppSchemaRepository {
350
352
  creatorRole?: string | null
351
353
  members?: { manage: string; list: string } | null
352
354
  directory?: 'labels' | null
355
+ values?: readonly DimensionValue[] | null
353
356
  lookups?: string[] | null
354
357
  }[]
355
358
  actions: { action: string; description?: string | null }[]
@@ -436,8 +439,8 @@ export class AppSchemaRepository {
436
439
  statements.push(
437
440
  this.db
438
441
  .prepare(
439
- `INSERT INTO app_scopes (app, scope_type, label, parent_scope, creator_role, members_manage, members_list, members_directory, members_lookup)
440
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
442
+ `INSERT INTO app_scopes (app, scope_type, label, parent_scope, creator_role, members_manage, members_list, members_directory, members_lookup, value_list)
443
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
441
444
  ON CONFLICT (app, scope_type) DO UPDATE SET
442
445
  label = excluded.label,
443
446
  parent_scope = excluded.parent_scope,
@@ -445,7 +448,8 @@ export class AppSchemaRepository {
445
448
  members_manage = excluded.members_manage,
446
449
  members_list = excluded.members_list,
447
450
  members_directory = excluded.members_directory,
448
- members_lookup = excluded.members_lookup`,
451
+ members_lookup = excluded.members_lookup,
452
+ value_list = excluded.value_list`,
449
453
  )
450
454
  .bind(
451
455
  app,
@@ -457,6 +461,7 @@ export class AppSchemaRepository {
457
461
  scope.members?.list ?? null,
458
462
  scope.directory ?? null,
459
463
  scope.lookups == null || scope.lookups.length === 0 ? null : JSON.stringify(scope.lookups),
464
+ scope.values == null ? null : JSON.stringify(scope.values),
460
465
  ),
461
466
  )
462
467
  }
@@ -16,7 +16,10 @@ export interface GrantRequestRow {
16
16
  /** Inline action-pattern set (JSON array); XOR `role_key`. */
17
17
  permissions: string | null
18
18
  scope_type: string | null
19
+ /** The first of the requested values, or the only one; null for a global grant. */
19
20
  scope_value: string | null
21
+ /** Every requested value (JSON array) when there are several (ADR-0085); read through `requestScopeValues`. */
22
+ scope_values: string | null
20
23
  grant_expires_at: number | null
21
24
  requested_by: string
22
25
  requested_at: number
@@ -36,7 +39,8 @@ export interface CreateGrantRequestInput {
36
39
  roleKey: string | null
37
40
  permissions: string[] | null
38
41
  scopeType: string | null
39
- scopeValue: string | null
42
+ /** Sorted and distinct; null for a global grant. */
43
+ scopeValues: string[] | null
40
44
  grantExpiresAt: number | null
41
45
  requestedBy: string
42
46
  requestedAt: number
@@ -87,8 +91,8 @@ export class GrantRequestRepository {
87
91
  const id = uuidv7()
88
92
  const [created] = await this.writer.run<GrantRequestRow>([{
89
93
  sql: `INSERT INTO grant_requests (id, app, kind, principal_id, grant_id, role_key, permissions, scope_type, scope_value,
90
- grant_expires_at, requested_by, requested_at, expires_at)
91
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
94
+ scope_values, grant_expires_at, requested_by, requested_at, expires_at)
95
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
92
96
  binds: [
93
97
  id,
94
98
  input.app,
@@ -98,7 +102,8 @@ export class GrantRequestRepository {
98
102
  input.roleKey,
99
103
  input.permissions === null ? null : JSON.stringify(input.permissions),
100
104
  input.scopeType,
101
- input.scopeValue,
105
+ input.scopeValues?.[0] ?? null,
106
+ input.scopeValues !== null && input.scopeValues.length > 1 ? JSON.stringify(input.scopeValues) : null,
102
107
  input.grantExpiresAt,
103
108
  input.requestedBy,
104
109
  input.requestedAt,