@fabrika/iam 0.9.0-dev.35 → 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,5 +1,5 @@
1
1
  import { isActionAllowed, isReservedScopeType, parseJsonStringArray, type RoleDef } from '@fabrika/auth-core'
2
- import { type CreateGrantRequest, type GrantDto } from '@fabrika/iam-contract'
2
+ import { type CreateGrantRequest, type GrantDto, MAX_GRANT_SCOPE_VALUES } from '@fabrika/iam-contract'
3
3
  import { type GrantRow, type RoleRow } from '../db'
4
4
  import { BUILTIN_ROLES, isKnownRole } from '../roles'
5
5
  import { type Services } from '../services'
@@ -44,28 +44,55 @@ export class RoleKnownCache {
44
44
  }
45
45
  }
46
46
 
47
- export async function toGrantDto(row: GrantRow, roleCache: RoleKnownCache): Promise<GrantDto> {
47
+ /** The id of the grant a row belongs to: its set's, or its own for a grant of one value (ADR-0085). */
48
+ export function grantIdOf(row: Pick<GrantRow, 'id' | 'scope_set'>): string {
49
+ return row.scope_set ?? row.id
50
+ }
51
+
52
+ /** Rows grouped into grants by `grantIdOf`, in the order each grant's first row appears. */
53
+ export function grantSets(rows: readonly GrantRow[]): GrantRow[][] {
54
+ const sets = new Map<string, GrantRow[]>()
55
+ for (const row of rows) {
56
+ const id = grantIdOf(row)
57
+ const set = sets.get(id)
58
+ if (set === undefined) sets.set(id, [row])
59
+ else set.push(row)
60
+ }
61
+ return [...sets.values()]
62
+ }
63
+
64
+ /**
65
+ * One grant's DTO from the rows of its set. A row an assignment renewed may expire later than the rest, so the latest
66
+ * expiry counts (none wins): the grant reads as expired only once none of its values grants anything.
67
+ */
68
+ export async function toGrantDto(rows: readonly [GrantRow, ...GrantRow[]], roleCache: RoleKnownCache): Promise<GrantDto> {
69
+ const [row] = rows
48
70
  const dangling = row.role_key !== null && !(await roleCache.isKnown(row.role_key, row.app))
71
+ const scopeValues = row.scope_type === null
72
+ ? null
73
+ : rows.flatMap((each) => each.scope_value === null ? [] : [each.scope_value]).sort((a, b) => a < b ? -1 : a > b ? 1 : 0)
49
74
  return {
50
- id: row.id,
75
+ id: grantIdOf(row),
51
76
  principalId: row.principal_id,
52
77
  roleKey: row.role_key,
53
78
  permissions: row.permissions === null ? null : rolePermissions(row.permissions),
54
79
  scopeType: row.scope_type,
55
- scopeValue: row.scope_value,
80
+ scopeValue: scopeValues?.[0] ?? null,
81
+ scopeValues,
56
82
  app: row.app,
57
83
  grantedBy: row.granted_by,
58
- expiresAt: row.expires_at,
59
- createdAt: row.created_at,
84
+ expiresAt: rows.some((each) => each.expires_at === null) ? null : Math.max(...rows.flatMap((each) => each.expires_at ?? [])),
85
+ createdAt: Math.min(...rows.map((each) => each.created_at)),
60
86
  dangling,
61
87
  }
62
88
  }
63
89
 
64
- /** Map a list of grant rows to DTOs sharing one role-known cache (one query per app). */
90
+ /** Map grant rows to one DTO per grant, sharing one role-known cache (one query per app). */
65
91
  export async function toGrantDtos(rows: GrantRow[], services: Services, cache: RoleKnownCache = new RoleKnownCache(services)): Promise<GrantDto[]> {
66
92
  const out: GrantDto[] = []
67
- for (const row of rows) {
68
- out.push(await toGrantDto(row, cache))
93
+ for (const set of grantSets(rows)) {
94
+ const [first, ...rest] = set
95
+ if (first !== undefined) out.push(await toGrantDto([first, ...rest], cache))
69
96
  }
70
97
  return out
71
98
  }
@@ -119,22 +146,33 @@ async function loadAppRoleMap(c: AdminContext, app: string | null): Promise<Reco
119
146
  }
120
147
 
121
148
  /**
122
- * Validate the scope coordinate on a grant/key request: `scopeType`/`scopeValue` are
123
- * both-or-neither (both null = global). A half-set pair is a 400.
149
+ * Validate the scope coordinate on a grant/key request: `scopeType` with `scopeValue` or `scopeValues` (ADR-0085), or
150
+ * none of them (global). The values come back sorted, so a set reads the same whatever order the request listed.
124
151
  */
125
152
  export function parseScope(
126
- body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue'>,
127
- ): { ok: true; scopeType: string | null; scopeValue: string | null } | { ok: false } {
153
+ body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue' | 'scopeValues'>,
154
+ ): { ok: true; scopeType: string | null; scopeValues: string[] | null } | { ok: false; message: string } {
128
155
  const scopeType = body.scopeType ?? null
129
- const scopeValue = body.scopeValue ?? null
130
- if ((scopeType === null) !== (scopeValue === null)) {
131
- return { ok: false }
156
+ if (body.scopeValues !== undefined && body.scopeValue != null) {
157
+ return { ok: false, message: 'give scopeValue or scopeValues, not both' }
158
+ }
159
+ const scopeValues = body.scopeValues ?? (body.scopeValue == null ? null : [body.scopeValue])
160
+ if ((scopeType === null) !== (scopeValues === null)) {
161
+ return { ok: false, message: 'scopeType and scopeValue must be both set or both omitted' }
132
162
  }
133
163
  // A `~` scope type is IAM's derived pseudo-scope (`~rel`); a stored grant never names one.
134
164
  if (scopeType !== null && isReservedScopeType(scopeType)) {
135
- return { ok: false }
165
+ return { ok: false, message: 'scopeType and scopeValue must be both set or both omitted' }
166
+ }
167
+ if (scopeValues === null) return { ok: true, scopeType, scopeValues }
168
+ if (scopeValues.length === 0 || scopeValues.length > MAX_GRANT_SCOPE_VALUES) {
169
+ return { ok: false, message: `scopeValues must list 1 to ${MAX_GRANT_SCOPE_VALUES} values` }
136
170
  }
137
- return { ok: true, scopeType, scopeValue }
171
+ if (body.scopeValues !== undefined && scopeValues.includes('')) return { ok: false, message: 'a scope value must not be empty' }
172
+ const sorted = [...scopeValues].sort((a, b) => a < b ? -1 : a > b ? 1 : 0)
173
+ const repeated = sorted.find((value, index) => index > 0 && sorted[index - 1] === value)
174
+ if (repeated !== undefined) return { ok: false, message: `scopeValues lists '${repeated}' twice` }
175
+ return { ok: true, scopeType, scopeValues: sorted }
138
176
  }
139
177
 
140
178
  /**
@@ -1,11 +1,20 @@
1
- import { type CreateGrantRequest, type GrantDto, type OkResponse, type UpdateGrantInput } from '@fabrika/iam-contract'
1
+ import {
2
+ type CreateGrantRequest,
3
+ type GrantChangeResponse,
4
+ type GrantDto,
5
+ type OkResponse,
6
+ type PendingGrantChange,
7
+ type UpdateGrantInput,
8
+ } from '@fabrika/iam-contract'
2
9
  import { contractGrantProblem, externalGrantProblem } from '../contract-rules'
3
10
  import { ExternalGrantError, type GrantRow } from '../db'
11
+ import { parseStoredPermissions } from '../stored-permissions'
4
12
  import { type AdminContext, adminEvent, fail } from './context'
5
- import { appField, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDto } from './grant-support'
13
+ import { type GrantChangeRequest, grantsWait, requestGrantChange } from './grant-requests'
14
+ import { appField, grantIdOf, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDto } from './grant-support'
6
15
  import { requireGrantablePrincipal, requireManagedApp } from './user-admin'
7
16
 
8
- export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantDto> {
17
+ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantChangeResponse> {
9
18
  const principalId = input.principalId
10
19
  if (principalId.trim() === '') return fail(400, 'principalId required')
11
20
  if (await c.services.repositories.grants.isWorkloadPrincipal(principalId)) {
@@ -23,7 +32,7 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
23
32
  }
24
33
  const scope = parseScope(input)
25
34
  if (!scope.ok) {
26
- return fail(400, 'scopeType and scopeValue must be both set or both omitted')
35
+ return fail(400, scope.message)
27
36
  }
28
37
  const principal = await c.services.repositories.principals.getPrincipalById(principalId)
29
38
  if (!principal) {
@@ -44,8 +53,30 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
44
53
  if (external !== null) {
45
54
  return fail(409, external)
46
55
  }
47
- 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 }
48
58
  const roleKey = roleOrInline.roleKey
59
+ if (app !== null && await grantsWait(c.services, app)) {
60
+ if (roleKey !== null) {
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)}`)
65
+ }
66
+ }
67
+ return await pendingChange(c, {
68
+ app,
69
+ kind: 'create',
70
+ principalId,
71
+ grantId: null,
72
+ roleKey,
73
+ permissions: roleOrInline.permissions,
74
+ scopeType,
75
+ scopeValues,
76
+ grantExpiresAt: expiresAt,
77
+ requestedBy: c.admin.id,
78
+ })
79
+ }
49
80
  const record = (grantId: string) =>
50
81
  adminEvent(c, {
51
82
  action: 'iam.grant.create',
@@ -55,47 +86,92 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
55
86
  principalId,
56
87
  roleKey: roleOrInline.roleKey,
57
88
  permissions: roleOrInline.permissions,
58
- scopeType: scope.scopeType,
59
- scopeValue: scope.scopeValue,
89
+ scopeType,
90
+ scopeValue: scopeValues?.[0] ?? null,
91
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
60
92
  app,
61
93
  },
62
94
  })
63
- 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[]
64
99
  try {
65
- if (roleKey === null) {
66
- grant = await c.services.repositories.grants.createGrant({ ...values, permissions: roleOrInline.permissions }, record)
67
- } else {
68
- const created = await c.services.repositories.grants.createRoleGrantUnlessHeld({ ...values, roleKey }, record)
69
- if (created === null) {
70
- const held = await findHeldRoleGrant(c, { ...values, roleKey }).catch(() => undefined)
71
- const naming = held === undefined ? '' : `: ${held.id}`
72
- 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
73
111
  }
74
- 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]
75
126
  }
76
127
  } catch (cause) {
77
128
  // A reconcile narrowed the role between the check above and the write, which carries the condition itself.
78
129
  if (cause instanceof ExternalGrantError) return fail(409, cause.message)
79
130
  throw cause
80
131
  }
81
- const cache = new RoleKnownCache(c.services)
82
- return toGrantDto(grant, cache)
132
+ return grantDto(rows, new RoleKnownCache(c.services))
83
133
  }
84
134
 
85
- export async function deleteGrantUseCase(c: AdminContext, input: { id: string }): Promise<OkResponse> {
86
- const id = input.id
87
- const grant = await c.services.repositories.grants.getGrantById(id)
88
- if (!grant) {
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)
139
+ }
140
+
141
+ export async function deleteGrantUseCase(c: AdminContext, input: { id: string }): Promise<OkResponse & Partial<PendingGrantChange>> {
142
+ const read = await c.services.repositories.grants.getGrantSet(input.id)
143
+ if (read === null) {
89
144
  return fail(404, 'grant not found')
90
145
  }
146
+ const [grant] = read.rows
91
147
  requireManagedApp(c, grant.app)
92
148
  const principal = await c.services.repositories.principals.getPrincipalById(grant.principal_id)
93
149
  if (!principal) {
94
150
  return fail(404, 'grant not found')
95
151
  }
96
152
  requireGrantablePrincipal(c, principal)
97
- await c.services.repositories.grants.deleteGrant(
153
+ const id = grantIdOf(grant)
154
+ const scopeValues = scopeValuesOf(read.rows)
155
+ if (grant.app !== null && await grantsWait(c.services, grant.app)) {
156
+ return {
157
+ ok: true,
158
+ ...await pendingChange(c, {
159
+ app: grant.app,
160
+ kind: 'revoke',
161
+ principalId: grant.principal_id,
162
+ grantId: id,
163
+ roleKey: grant.role_key,
164
+ permissions: grant.permissions === null ? null : parseStoredPermissions(grant.permissions),
165
+ scopeType: grant.scope_type,
166
+ scopeValues,
167
+ grantExpiresAt: grant.expires_at,
168
+ requestedBy: c.admin.id,
169
+ }),
170
+ }
171
+ }
172
+ await c.services.repositories.grants.deleteGrantSet(
98
173
  id,
174
+ grant.principal_id,
99
175
  adminEvent(c, {
100
176
  action: 'iam.grant.revoke',
101
177
  resourceType: 'grant',
@@ -104,7 +180,8 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
104
180
  principalId: grant.principal_id,
105
181
  roleKey: grant.role_key,
106
182
  scopeType: grant.scope_type,
107
- scopeValue: grant.scope_value,
183
+ scopeValue: scopeValues?.[0] ?? null,
184
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
108
185
  },
109
186
  }),
110
187
  )
@@ -112,9 +189,10 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
112
189
  }
113
190
 
114
191
  /** Edit a grant in place within its original application. Both paths use the same role, scope and external-person rules. */
115
- export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantDto> {
116
- const grant = await c.services.repositories.grants.getGrantById(input.id)
117
- if (grant === null) return fail(404, 'grant not found')
192
+ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantChangeResponse> {
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
118
196
  requireManagedApp(c, grant.app)
119
197
  const principal = await c.services.repositories.principals.getPrincipalById(grant.principal_id)
120
198
  if (principal === null) return fail(404, 'principal not found')
@@ -122,7 +200,7 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
122
200
  const authorization = await parseRoleOrInline(c, input, grant.app)
123
201
  if (!authorization.ok) return fail(400, authorization.message)
124
202
  const scope = parseScope(input)
125
- 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)
126
204
  const problem = await contractGrantProblem(
127
205
  c.services.repositories.appSchema,
128
206
  grant.app,
@@ -133,70 +211,120 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
133
211
  if (problem !== null) return fail(409, problem)
134
212
  const expiresAt = input.expiresAt ?? null
135
213
  if (expiresAt !== null && expiresAt <= Math.floor(Date.now() / 1000)) return fail(400, 'Choose an expiration in the future, or no expiration.')
136
- 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
137
217
  if (
138
218
  grant.role_key === authorization.roleKey
139
219
  && grant.permissions === (authorization.permissions === null ? null : JSON.stringify(authorization.permissions))
140
- && 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)
141
222
  ) {
142
- return toGrantDto(grant, new RoleKnownCache(c.services))
223
+ return toGrantDto(read.rows, new RoleKnownCache(c.services))
143
224
  }
144
225
  const duplicate = async () =>
145
226
  authorization.roleKey !== null
146
227
  && (await c.services.repositories.grants.listGrants(principal.id)).some((other) =>
147
- other.id !== grant.id && other.app === grant.app && other.role_key === authorization.roleKey
148
- && 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))
149
231
  )
150
232
  const held = principal.type === 'user'
151
233
  ? 'This user already has that role in this scope. Edit the existing access instead.'
152
234
  : 'This key already has that role in this scope. Edit the existing grant instead.'
153
235
  if (await duplicate()) return fail(409, held)
154
- let updated: GrantRow | null
236
+ if (grant.app !== null && await grantsWait(c.services, grant.app)) {
237
+ return await pendingChange(c, {
238
+ app: grant.app,
239
+ kind: 'update',
240
+ principalId: principal.id,
241
+ grantId: id,
242
+ roleKey: authorization.roleKey,
243
+ permissions: authorization.permissions,
244
+ scopeType,
245
+ scopeValues,
246
+ grantExpiresAt: expiresAt,
247
+ requestedBy: c.admin.id,
248
+ })
249
+ }
250
+ let updated: GrantRow[] | null
155
251
  try {
156
- updated = await c.services.repositories.grants.updateGrant(
157
- grant,
158
- 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
+ },
159
264
  adminEvent(c, {
160
265
  action: 'iam.grant.update',
161
266
  resourceType: 'grant',
162
- resourceId: grant.id,
267
+ resourceId: id,
163
268
  metadata: { principalId: principal.id, app: grant.app },
164
269
  diff: {
165
270
  before: {
166
271
  roleKey: grant.role_key,
167
272
  permissions: grant.permissions === null ? null : JSON.parse(grant.permissions),
168
273
  scopeType: grant.scope_type,
169
- scopeValue: grant.scope_value,
274
+ scopeValue: before?.[0] ?? null,
275
+ ...(before !== null && before.length > 1 ? { scopeValues: before } : {}),
170
276
  expiresAt: grant.expires_at,
171
277
  },
172
278
  after: {
173
279
  roleKey: authorization.roleKey,
174
280
  permissions: authorization.permissions,
175
- scopeType: scope.scopeType,
176
- scopeValue: scope.scopeValue,
281
+ scopeType,
282
+ scopeValue: scopeValues?.[0] ?? null,
283
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
177
284
  expiresAt,
178
285
  },
179
286
  },
180
287
  }),
181
288
  )
182
289
  } catch (cause) {
290
+ if (cause instanceof ExternalGrantError) return fail(409, cause.message)
183
291
  if (await duplicate()) return fail(409, held)
184
292
  throw cause
185
293
  }
186
294
  if (updated === null) return fail(409, 'The access changed or is no longer allowed. Refresh and try again.')
187
- 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])
188
306
  }
189
307
 
190
- /** 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. */
191
309
  async function findHeldRoleGrant(
192
310
  c: AdminContext,
193
- 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 },
194
312
  ): Promise<GrantRow | undefined> {
195
313
  const held = await c.services.repositories.grants.listGrants(candidate.principalId)
196
314
  return held.find((row) =>
197
315
  row.role_key === candidate.roleKey
198
316
  && row.app === candidate.app
199
317
  && row.scope_type === candidate.scopeType
200
- && row.scope_value === candidate.scopeValue
318
+ && (candidate.scopeValues === null ? row.scope_value === null : row.scope_value !== null && candidate.scopeValues.includes(row.scope_value))
319
+ )
320
+ }
321
+
322
+ /** Record a grant change at an application whose grants wait (ADR-0083): nothing changes until another administrator approves. */
323
+ async function pendingChange(c: AdminContext, change: GrantChangeRequest): Promise<PendingGrantChange> {
324
+ const pending = await requestGrantChange(
325
+ c.services,
326
+ change,
327
+ (requestId, metadata) => adminEvent(c, { action: 'iam.grant.request', resourceType: 'grant_request', resourceId: requestId, metadata }),
201
328
  )
329
+ return { pending }
202
330
  }
package/src/admin/rpc.ts CHANGED
@@ -8,6 +8,14 @@ import { logError } from '../log'
8
8
  import { recordAdminAccess, rpcProcedureOf } from './access'
9
9
  import { grantAppRole, listAdministeredApps, listAppPeople, revokeAppRole } from './app-people'
10
10
  import { listConnections, revokeConnection } from './connections'
11
+ import {
12
+ decideGrantRequestUseCase,
13
+ type GrantRequester,
14
+ listGrantRequestsUseCase,
15
+ listOwnGrantRequestsUseCase,
16
+ setGrantApprovalUseCase,
17
+ withdrawOwnGrantRequestUseCase,
18
+ } from './grant-requests'
11
19
  import type { AdminContext } from './handlers'
12
20
  import { adminUseCases } from './handlers'
13
21
  import { ADMIN_ACTION, extractCredentials, IAM_APP, resolveAdmin } from './router'
@@ -26,6 +34,7 @@ const authorization = {
26
34
  permissions: z.array(nonEmpty).optional(),
27
35
  scopeType: optionalNullableString,
28
36
  scopeValue: optionalNullableString,
37
+ scopeValues: z.array(z.string()).optional(),
29
38
  app: optionalNullableString,
30
39
  expiresAt: z.number().finite().optional().nullable(),
31
40
  }
@@ -97,6 +106,28 @@ export const adminRpcRouter: RpcRouterFor<IamAppContext, IamAdminRpcContract> =
97
106
  .mutation(({ ctx, input }) => adminUseCases.updateGrant(context(ctx), input)),
98
107
  delete: t.procedure.input(z.object({ id: nonEmpty })).mutation(({ ctx, input }) => adminUseCases.deleteGrant(context(ctx), input)),
99
108
  }),
109
+ // No `iam.admin` here: an administrator of each request's application decides it (ADR-0083), a person in a session.
110
+ grantRequests: t.router({
111
+ list: t.procedure.input(z.object({ app: nonEmpty.optional() }).default({})).query(({ ctx, input }) => {
112
+ const requester = ownRequester(ctx)
113
+ return requester === null ? listGrantRequestsUseCase(context(ctx), input) : listOwnGrantRequestsUseCase(requester, input)
114
+ }),
115
+ decide: t.procedure
116
+ .input(z.object({ id: nonEmpty, decision: z.enum(['approve', 'reject']) }))
117
+ .mutation(({ ctx, input }) => {
118
+ const requester = ownRequester(ctx)
119
+ return requester === null
120
+ ? decideGrantRequestUseCase(context(ctx), ctx.admin?.type === 'user' && ctx.admin.session, input)
121
+ : withdrawOwnGrantRequestUseCase(requester, input)
122
+ }),
123
+ }),
124
+ // Control's, with the provisioning key: whether an application environment's grants wait (ADR-0083).
125
+ grantApproval: t.router({
126
+ set: t.procedure
127
+ .input(z.object({ app: nonEmpty, required: z.boolean(), revision: z.number().int().nonnegative() }).strict())
128
+ .require(ADMIN_ACTION)
129
+ .mutation(({ ctx, input }) => setGrantApprovalUseCase(context(ctx), input)),
130
+ }),
100
131
  apps: t.router({
101
132
  list: t.procedure.query(({ ctx }) => adminUseCases.listApps(context(ctx))),
102
133
  getSchema: t.procedure.input(appInput).query(({ ctx, input }) => adminUseCases.getAppSchema(context(ctx), input)),
@@ -369,6 +400,12 @@ function authContext(admin: NonNullable<IamAppContext['admin']>): AuthContext {
369
400
  }
370
401
 
371
402
  /** The context of a caller with an administration; anyone else is refused before the use case runs. */
403
+ /** A caller with no IAM administration reaches only the grant requests it made itself (ADR-0083); null otherwise. */
404
+ function ownRequester(ctx: IamAppContext): GrantRequester | null {
405
+ if (ctx.admin === null) throw new UnauthorizedError()
406
+ return administrationOf(ctx.admin) === null ? { services: ctx.services, requestId: ctx.requestId, admin: ctx.admin } : null
407
+ }
408
+
372
409
  function context(ctx: IamAppContext): AdminContext {
373
410
  if (ctx.admin === null) throw new UnauthorizedError()
374
411
  const administration = administrationOf(ctx.admin)
package/src/db.ts CHANGED
@@ -5,6 +5,7 @@ import { AuditRepository, AuditWriter, type SqlDialect } from './repositories/au
5
5
  import { InstallationBrandRepository } from './repositories/brand'
6
6
  import { CredentialRepository } from './repositories/credentials'
7
7
  import { DeviceAuthorizationRepository } from './repositories/device'
8
+ import { GrantRequestRepository } from './repositories/grant-requests'
8
9
  import { GrantRepository } from './repositories/grants'
9
10
  import { HandoffRepository } from './repositories/handoff'
10
11
  import { MembershipRepository } from './repositories/membership'
@@ -44,7 +45,8 @@ export {
44
45
  export { type InstallationBrandImages, InstallationBrandRepository, type InstallationBrandRow } from './repositories/brand'
45
46
  export { type CredentialGrantRow, CredentialRepository, type CredentialRow } from './repositories/credentials'
46
47
  export { DeviceAuthorizationRepository, type DeviceAuthorizationRow, type DeviceReceiptRow } from './repositories/device'
47
- export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow } from './repositories/grants'
48
+ export { type CreateGrantRequestInput, GrantRequestRepository, type GrantRequestRow } from './repositories/grant-requests'
49
+ export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow, type GrantSetRead } from './repositories/grants'
48
50
  export { type AuthCodeRow, HandoffRepository } from './repositories/handoff'
49
51
  export {
50
52
  type DelegationGrantRow,
@@ -86,6 +88,7 @@ export interface IamRepositories {
86
88
  device: DeviceAuthorizationRepository
87
89
  principals: PrincipalRepository
88
90
  grants: GrantRepository
91
+ grantRequests: GrantRequestRepository
89
92
  appSchema: AppSchemaRepository
90
93
  credentials: CredentialRepository
91
94
  sessions: SessionRepository
@@ -116,6 +119,7 @@ export function createIamRepositories(
116
119
  device: replacements.device ?? new DeviceAuthorizationRepository(db),
117
120
  principals: replacements.principals ?? new PrincipalRepository(db, writer),
118
121
  grants: replacements.grants ?? new GrantRepository(db, writer),
122
+ grantRequests: replacements.grantRequests ?? new GrantRequestRepository(db, writer),
119
123
  appSchema: replacements.appSchema ?? new AppSchemaRepository(db, writer),
120
124
  credentials: replacements.credentials ?? new CredentialRepository(db, writer),
121
125
  sessions: replacements.sessions ?? new SessionRepository(db, writer),
package/src/oauth-http.ts CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  import { decodeJwt } from 'jose'
18
18
  import { readForm, redirectHeaders, sameOrigin } from './auth/http'
19
19
  import { currentSession } from './auth/sessions'
20
- import { principalStatus } from './db'
20
+ import { type PrincipalRow, principalStatus } from './db'
21
21
  import type { Env } from './env'
22
22
  import { escapeHtml } from './html'
23
23
  import { installationBrand } from './installation-brand'
@@ -26,6 +26,7 @@ import {
26
26
  establishClient,
27
27
  exchangeOAuthToken,
28
28
  grantAuthorization,
29
+ heldIdentityRoles,
29
30
  type ManagedClient,
30
31
  revokeOAuthToken,
31
32
  scopeCeiling,
@@ -142,6 +143,16 @@ function checkIdentityAuthorization(
142
143
  return { kind: 'valid', request, client, resource: identity, scopes, ceiling: [] }
143
144
  }
144
145
 
146
+ /** An external application that declares roles admits only a person holding one of them there. */
147
+ async function refusedByIdentityRoles(
148
+ services: Services,
149
+ check: Extract<AuthorizationCheck, { kind: 'valid' }>,
150
+ principal: PrincipalRow,
151
+ ): Promise<boolean> {
152
+ const roles = check.client.registration.identity?.roles
153
+ return roles !== undefined && await heldIdentityRoles(services, principal, check.resource.app, roles) === null
154
+ }
155
+
145
156
  async function showConsent(request: Request, services: Services, config: OAuthConfig): Promise<Response> {
146
157
  const url = new URL(request.url)
147
158
  const check = await checkAuthorization(services.config.issuer, config, singleValued(url.searchParams))
@@ -156,6 +167,9 @@ async function showConsent(request: Request, services: Services, config: OAuthCo
156
167
  if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') {
157
168
  return errorPage(services, 'This account cannot authorize applications.', 403)
158
169
  }
170
+ if (await refusedByIdentityRoles(services, check, principal)) {
171
+ return clientRedirect(services.config.issuer, check.request, { error: 'access_denied' })
172
+ }
159
173
  return consentPage(services, check, principal.label)
160
174
  }
161
175
 
@@ -172,6 +186,10 @@ async function decideConsent(request: Request, services: Services, config: OAuth
172
186
  if (decision !== 'approve') return errorPage(services, 'The consent decision is missing.', 400)
173
187
  const session = await currentSession(request, services)
174
188
  if (session === null) return errorPage(services, 'Your sign-in has ended. Start the authorization again.', 401)
189
+ const principal = await services.repositories.principals.getPrincipalById(session.principal_id)
190
+ if (principal === null || await refusedByIdentityRoles(services, check, principal)) {
191
+ return clientRedirect(issuer, check.request, { error: 'access_denied' })
192
+ }
175
193
  const code = await grantAuthorization(services, { request: check.request, resource: check.resource, scopes: check.scopes, session, requestId })
176
194
  return clientRedirect(issuer, check.request, { code })
177
195
  }
@@ -262,7 +280,9 @@ async function consentPage(services: Services, check: Extract<AuthorizationCheck
262
280
  })
263
281
  const asks = client.registration.identity === undefined
264
282
  ? `<p><strong>${escapeHtml(clientName)}</strong> asks to act as you in <strong>${escapeHtml(resource.app)}</strong>.</p>`
265
- : `<p><strong>${escapeHtml(clientName)}</strong> asks to know who you are. It receives your account and name, and no permission.</p>`
283
+ : `<p><strong>${escapeHtml(clientName)}</strong> asks to know who you are. It receives who you are${
284
+ client.registration.identity.roles === undefined ? '' : ` and the roles you hold in <strong>${escapeHtml(resource.app)}</strong>`
285
+ }, and no permission.</p>`
266
286
  const grants = client.registration.identity === undefined
267
287
  ? `<p>At most these permissions, and only those you hold yourself:</p>
268
288
  <ul>${permissions.join('')}</ul>`