@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.
@@ -0,0 +1,41 @@
1
+ -- A console grant that waits for a second administrator (ADR-0083). SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0035_grant_requests.sql` states the same outcome.
3
+ --
4
+ -- `app_grant_approvals` holds whether grant changes at an application id (`<app>@<env>`) wait (`required`). Only Control
5
+ -- writes it, with the provisioning key, when an environment chooses or drops the `grants` approval category; `revision`
6
+ -- is the environment's protection revision in Control, and an older one never overwrites a newer. No row, as for every
7
+ -- application before this file, means a grant change applies at once.
8
+ CREATE TABLE app_grant_approvals (
9
+ app TEXT PRIMARY KEY,
10
+ required INTEGER NOT NULL CHECK (required IN (0, 1)),
11
+ revision INTEGER NOT NULL,
12
+ updated_at INTEGER NOT NULL
13
+ );
14
+
15
+ -- One requested grant change. Nothing that resolves permissions reads this table: a request has no effect until an
16
+ -- approval writes the change itself, in the transaction that claims the request (`decision_id`). The grant fields are
17
+ -- the new grant for `create` and `update`, the revoked one for `revoke`; `grant_id` names the grant an `update` or a
18
+ -- `revoke` acts on. An open request is `pending` before `expires_at`.
19
+ CREATE TABLE grant_requests (
20
+ id TEXT PRIMARY KEY,
21
+ app TEXT NOT NULL,
22
+ kind TEXT NOT NULL CHECK (kind IN ('create', 'update', 'revoke')),
23
+ principal_id TEXT NOT NULL,
24
+ grant_id TEXT,
25
+ role_key TEXT,
26
+ permissions TEXT,
27
+ scope_type TEXT,
28
+ scope_value TEXT,
29
+ grant_expires_at INTEGER,
30
+ requested_by TEXT NOT NULL,
31
+ requested_at INTEGER NOT NULL,
32
+ expires_at INTEGER NOT NULL,
33
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'failed')),
34
+ decision_id TEXT,
35
+ decided_by TEXT,
36
+ decided_at INTEGER,
37
+ CHECK ((kind = 'create') = (grant_id IS NULL)),
38
+ CHECK ((role_key IS NULL) <> (permissions IS NULL)),
39
+ CHECK ((scope_type IS NULL) = (scope_value IS NULL))
40
+ );
41
+ CREATE INDEX idx_grant_requests_open ON grant_requests (app, status);
@@ -0,0 +1,14 @@
1
+ -- A grant holds a set of values of one dimension, one row per value (ADR-0085). SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0036_grant_scope_sets.sql` states the same outcome.
3
+ --
4
+ -- The rows of a grant with more than one value share `scope_set`, the grant's id. NULL is a grant of one value, which
5
+ -- is every grant written before this file, so each of them stays the grant it was and resolves as before.
6
+ ALTER TABLE grants ADD COLUMN scope_set TEXT;
7
+ CREATE INDEX idx_grants_scope_set ON grants(scope_set);
8
+
9
+ -- The values a dimension lists for the console, a JSON array of { value, label? }; NULL lists none.
10
+ ALTER TABLE app_scopes ADD COLUMN value_list TEXT;
11
+
12
+ -- Every value a waiting grant change asks for (ADR-0083), a JSON array, when it asks for more than one; `scope_value`
13
+ -- keeps the first. NULL is a request of one value or none, which is every request written before this file.
14
+ ALTER TABLE grant_requests ADD COLUMN scope_values TEXT;
@@ -0,0 +1,41 @@
1
+ -- A console grant that waits for a second administrator (ADR-0083). Postgres dialect;
2
+ -- `../migrations/0035_grant_requests.sql` states the same outcome.
3
+ --
4
+ -- `app_grant_approvals` holds whether grant changes at an application id (`<app>@<env>`) wait (`required`). Only Control
5
+ -- writes it, with the provisioning key, when an environment chooses or drops the `grants` approval category; `revision`
6
+ -- is the environment's protection revision in Control, and an older one never overwrites a newer. No row, as for every
7
+ -- application before this file, means a grant change applies at once.
8
+ CREATE TABLE app_grant_approvals (
9
+ app TEXT PRIMARY KEY,
10
+ required INTEGER NOT NULL CHECK (required IN (0, 1)),
11
+ revision INTEGER NOT NULL,
12
+ updated_at INTEGER NOT NULL
13
+ );
14
+
15
+ -- One requested grant change. Nothing that resolves permissions reads this table: a request has no effect until an
16
+ -- approval writes the change itself, in the transaction that claims the request (`decision_id`). The grant fields are
17
+ -- the new grant for `create` and `update`, the revoked one for `revoke`; `grant_id` names the grant an `update` or a
18
+ -- `revoke` acts on. An open request is `pending` before `expires_at`.
19
+ CREATE TABLE grant_requests (
20
+ id TEXT PRIMARY KEY,
21
+ app TEXT NOT NULL,
22
+ kind TEXT NOT NULL CHECK (kind IN ('create', 'update', 'revoke')),
23
+ principal_id TEXT NOT NULL,
24
+ grant_id TEXT,
25
+ role_key TEXT,
26
+ permissions TEXT,
27
+ scope_type TEXT,
28
+ scope_value TEXT,
29
+ grant_expires_at INTEGER,
30
+ requested_by TEXT NOT NULL,
31
+ requested_at INTEGER NOT NULL,
32
+ expires_at INTEGER NOT NULL,
33
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'failed')),
34
+ decision_id TEXT,
35
+ decided_by TEXT,
36
+ decided_at INTEGER,
37
+ CHECK ((kind = 'create') = (grant_id IS NULL)),
38
+ CHECK ((role_key IS NULL) <> (permissions IS NULL)),
39
+ CHECK ((scope_type IS NULL) = (scope_value IS NULL))
40
+ );
41
+ CREATE INDEX idx_grant_requests_open ON grant_requests (app, status);
@@ -0,0 +1,14 @@
1
+ -- A grant holds a set of values of one dimension, one row per value (ADR-0085). Postgres dialect;
2
+ -- `../migrations/0036_grant_scope_sets.sql` states the same outcome.
3
+ --
4
+ -- The rows of a grant with more than one value share `scope_set`, the grant's id. NULL is a grant of one value, which
5
+ -- is every grant written before this file, so each of them stays the grant it was and resolves as before.
6
+ ALTER TABLE grants ADD COLUMN scope_set TEXT;
7
+ CREATE INDEX idx_grants_scope_set ON grants(scope_set);
8
+
9
+ -- The values a dimension lists for the console, a JSON array of { value, label? }; NULL lists none.
10
+ ALTER TABLE app_scopes ADD COLUMN value_list TEXT;
11
+
12
+ -- Every value a waiting grant change asks for (ADR-0083), a JSON array, when it asks for more than one; `scope_value`
13
+ -- keeps the first. NULL is a request of one value or none, which is every request written before this file.
14
+ ALTER TABLE grant_requests ADD COLUMN scope_values TEXT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/iam",
3
- "version": "0.9.0-dev.35",
3
+ "version": "0.9.0-dev.37",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -56,16 +56,16 @@
56
56
  "prune:auth-log": "bun src/node/prune.ts"
57
57
  },
58
58
  "dependencies": {
59
- "@fabrika/app": "0.9.0-dev.35",
60
- "@fabrika/auth": "0.9.0-dev.35",
61
- "@fabrika/auth-core": "0.9.0-dev.35",
62
- "@fabrika/control-contract": "0.9.0-dev.35",
63
- "@fabrika/email": "0.9.0-dev.35",
64
- "@fabrika/iam-contract": "0.9.0-dev.35",
65
- "@fabrika/platform": "0.9.0-dev.35",
66
- "@fabrika/platform-node": "0.9.0-dev.35",
67
- "@fabrika/provider-cloudflare": "0.9.0-dev.35",
68
- "@fabrika/proxy-core": "0.9.0-dev.35",
59
+ "@fabrika/app": "0.9.0-dev.37",
60
+ "@fabrika/auth": "0.9.0-dev.37",
61
+ "@fabrika/auth-core": "0.9.0-dev.37",
62
+ "@fabrika/control-contract": "0.9.0-dev.37",
63
+ "@fabrika/email": "0.9.0-dev.37",
64
+ "@fabrika/iam-contract": "0.9.0-dev.37",
65
+ "@fabrika/platform": "0.9.0-dev.37",
66
+ "@fabrika/platform-node": "0.9.0-dev.37",
67
+ "@fabrika/provider-cloudflare": "0.9.0-dev.37",
68
+ "@fabrika/proxy-core": "0.9.0-dev.37",
69
69
  "jose": "^5.9.0",
70
70
  "uqr": "^0.1.3",
71
71
  "zod": "^3.25.76"
@@ -119,7 +119,7 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
119
119
  }
120
120
  const scope = parseScope(input)
121
121
  if (!scope.ok) {
122
- return fail(400, 'scopeType and scopeValue must be both set or both omitted')
122
+ return fail(400, scope.message)
123
123
  }
124
124
  const contractProblem = await contractGrantProblem(c.services.repositories.appSchema, app, { ...roleOrInline, scopeType: scope.scopeType }, false)
125
125
  if (contractProblem !== null) {
@@ -139,13 +139,13 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
139
139
  const { principals, grants, credentials, audit } = c.services.repositories
140
140
  await audit.commit([
141
141
  principals.createServiceStatement(principalId, label),
142
- grants.grantStatement(grantId, {
142
+ ...grants.grantSetStatements(grantId, {
143
143
  principalId,
144
144
  app,
145
145
  roleKey: roleOrInline.roleKey,
146
146
  permissions: roleOrInline.permissions,
147
147
  scopeType: scope.scopeType,
148
- scopeValue: scope.scopeValue,
148
+ scopeValues: scope.scopeValues,
149
149
  grantedBy: c.admin.id,
150
150
  expiresAt,
151
151
  }),
@@ -176,7 +176,8 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
176
176
  roleKey: roleOrInline.roleKey,
177
177
  permissions: roleOrInline.permissions,
178
178
  scopeType: scope.scopeType,
179
- scopeValue: scope.scopeValue,
179
+ scopeValue: scope.scopeValues?.[0] ?? null,
180
+ ...(scope.scopeValues !== null && scope.scopeValues.length > 1 ? { scopeValues: scope.scopeValues } : {}),
180
181
  app,
181
182
  },
182
183
  })),
@@ -268,9 +269,10 @@ const provisionApiKeyRequestSchema = z.object({
268
269
  permissions: z.array(z.string()).optional().catch(undefined),
269
270
  scopeType: z.string().nullable().optional().catch(undefined),
270
271
  scopeValue: z.string().nullable().optional().catch(undefined),
272
+ scopeValues: z.array(z.string()).optional().catch(undefined),
271
273
  app: z.string().nullable().optional().catch(undefined),
272
274
  expiresAt: z.number().finite().optional().catch(undefined),
273
- }).transform(({ label, type, roleKey, permissions, scopeType, scopeValue, app, expiresAt }) => {
275
+ }).transform(({ label, type, roleKey, permissions, scopeType, scopeValue, scopeValues, app, expiresAt }) => {
274
276
  return {
275
277
  label,
276
278
  type,
@@ -278,6 +280,7 @@ const provisionApiKeyRequestSchema = z.object({
278
280
  ...(permissions !== undefined ? { permissions } : {}),
279
281
  ...(scopeType !== undefined ? { scopeType } : {}),
280
282
  ...(scopeValue !== undefined ? { scopeValue } : {}),
283
+ ...(scopeValues !== undefined ? { scopeValues } : {}),
281
284
  ...(app !== undefined ? { app } : {}),
282
285
  ...(expiresAt !== undefined ? { expiresAt } : {}),
283
286
  }
@@ -32,6 +32,7 @@ import { BUILTIN_ROLES } from '../roles'
32
32
  import type { Services } from '../services'
33
33
  import { delegatedActions, parseStoredPermissions } from '../stored-permissions'
34
34
  import { fail } from './context'
35
+ import { grantsWait, requestGrantChange } from './grant-requests'
35
36
  import { IAM_APP } from './router'
36
37
 
37
38
  /** The person administering, as the console's token names it. */
@@ -113,7 +114,11 @@ async function grantableRole(admin: PeopleAdministrator, administered: Administe
113
114
  }
114
115
 
115
116
  /** The record of a change the administrator made, filed under the application. A user's audit label is its id. */
116
- function peopleEvent(admin: PeopleAdministrator, app: string, event: { action: string; resourceId: string; metadata: unknown }): AuditEventInput {
117
+ function peopleEvent(
118
+ admin: PeopleAdministrator,
119
+ app: string,
120
+ event: { action: string; resourceId: string; metadata: unknown; resourceType?: string },
121
+ ): AuditEventInput {
117
122
  return {
118
123
  requestId: admin.requestId,
119
124
  principalId: admin.principal.id,
@@ -168,6 +173,33 @@ export async function grantAppRole(ctx: IamAppContext, input: GrantAppRoleReques
168
173
  (action): PermissionEntry => ({ action, scope: null, source: 'grant' }),
169
174
  )
170
175
  const expiresAt = authorityDeadline(administered, carried, unixNow())
176
+ if (await grantsWait(admin.services, administered.app)) {
177
+ const now = unixNow()
178
+ const holds = (await grants.listGrants(target.id)).some((grant) =>
179
+ grant.app === administered.app && grant.role_key === role.role_key && grant.scope_value === null
180
+ && (grant.expires_at === null || grant.expires_at > now)
181
+ )
182
+ if (holds) return { principalId: target.id, role: role.role_key, granted: false }
183
+ const pending = await requestGrantChange(admin.services, {
184
+ app: administered.app,
185
+ kind: 'create',
186
+ principalId: target.id,
187
+ grantId: null,
188
+ roleKey: role.role_key,
189
+ permissions: null,
190
+ scopeType: null,
191
+ scopeValues: null,
192
+ grantExpiresAt: expiresAt,
193
+ requestedBy: admin.principal.id,
194
+ }, (requestId, metadata) =>
195
+ peopleEvent(admin, administered.app, {
196
+ action: 'iam.grant.request',
197
+ resourceType: 'grant_request',
198
+ resourceId: requestId,
199
+ metadata: { ...metadata, delegated: true },
200
+ }))
201
+ return { principalId: target.id, role: role.role_key, granted: false, pending }
202
+ }
171
203
  const granted = await grants.createDelegatedRoleGrant(
172
204
  { principalId: target.id, roleKey: role.role_key, grantedBy: admin.principal.id, expiresAt },
173
205
  administered.authority,
@@ -195,6 +227,27 @@ export async function revokeAppRole(ctx: IamAppContext, input: RevokeAppRoleRequ
195
227
  grant.app === administered.app && grant.role_key === role.role_key && grant.scope_type === null && grant.scope_value === null
196
228
  )
197
229
  if (held === undefined) return { revoked: false }
230
+ if (await grantsWait(admin.services, administered.app)) {
231
+ const pending = await requestGrantChange(admin.services, {
232
+ app: administered.app,
233
+ kind: 'revoke',
234
+ principalId: input.principalId,
235
+ grantId: held.id,
236
+ roleKey: role.role_key,
237
+ permissions: null,
238
+ scopeType: null,
239
+ scopeValues: null,
240
+ grantExpiresAt: held.expires_at,
241
+ requestedBy: admin.principal.id,
242
+ }, (requestId, metadata) =>
243
+ peopleEvent(admin, administered.app, {
244
+ action: 'iam.grant.request',
245
+ resourceType: 'grant_request',
246
+ resourceId: requestId,
247
+ metadata: { ...metadata, delegated: true },
248
+ }))
249
+ return { revoked: false, pending }
250
+ }
198
251
  const revoked = await grants.deleteDelegatedGrant(
199
252
  held,
200
253
  administered.authority,
@@ -1,5 +1,5 @@
1
1
  import { appSchemaSchema } from '@fabrika/auth'
2
- import { type AppDelegationDef, type AppLinkMountDef, LOCALES, type RoleDef } from '@fabrika/auth-core'
2
+ import { type AppDelegationDef, type AppLinkMountDef, type DimensionValue, LOCALES, type RoleDef } from '@fabrika/auth-core'
3
3
 
4
4
  import {
5
5
  type AppDto,
@@ -14,7 +14,7 @@ import type { z } from 'zod'
14
14
  import { parsePresentation } from '../app-presentation'
15
15
  import { normalizeOrigin } from '../handoff'
16
16
  import { BUILTIN_ROLES } from '../roles'
17
- import { parseStoredPermissions } from '../stored-permissions'
17
+ import { parseStoredPermissions, parseStoredValueList } from '../stored-permissions'
18
18
  import { type AdminContext, adminEvent, fail } from './context'
19
19
  import { dbRoleToDef, knownApps } from './grant-support'
20
20
  import { error, json, readJson } from './http'
@@ -176,6 +176,7 @@ export async function putAppSchema(c: AdminContext, app: string): Promise<Respon
176
176
  members: s.members ?? null,
177
177
  directory: s.directory ?? null,
178
178
  lookups: s.lookups ?? null,
179
+ values: s.values ?? null,
179
180
  })),
180
181
  actions: schema.actions.map((a) => ({ action: a.action, description: a.description ?? null })),
181
182
  roles: Object.entries(schema.roles).map(([roleKey, def]) => ({
@@ -252,6 +253,7 @@ async function readAppSchemaDto(c: AdminContext, app: string): Promise<AppSchema
252
253
  ...(r.members_manage !== null && r.members_list !== null ? { members: { manage: r.members_manage, list: r.members_list } } : {}),
253
254
  ...(r.members_directory === 'labels' ? { directory: 'labels' } : {}),
254
255
  ...(r.members_lookup === null ? {} : { lookups: parseStoredPermissions(r.members_lookup) }),
256
+ ...valueListOf(r.value_list),
255
257
  })),
256
258
  actions: actionRows.map((r) => ({ action: r.action, ...(r.description !== null ? { description: r.description } : {}) })),
257
259
  roles,
@@ -306,3 +308,9 @@ export async function getAppSchemaUseCase(c: AdminContext, input: AppInput): Pro
306
308
  }
307
309
  return readAppSchemaDto(c, app)
308
310
  }
311
+
312
+ /** A scope's listed values as the schema answers them: present only when the stored list parses. */
313
+ function valueListOf(stored: string | null): { values?: DimensionValue[] } {
314
+ const values = parseStoredValueList(stored)
315
+ return values === null ? {} : { values }
316
+ }
@@ -0,0 +1,276 @@
1
+ // A console grant that waits for a second administrator (ADR-0083 §4). At an application whose grants wait, a grant
2
+ // change runs every check it runs today and then records a request instead of the change; nothing that resolves
3
+ // permissions reads a request. An administrator of the application, a person in a signed-in session other than the
4
+ // requester, approves it, and approving makes the change with the approver's own checks, in the transaction that claims
5
+ // the request. This is authorization, never an enforcement decision (ADR-0022).
6
+
7
+ import { parseAppEnvironmentId } from '@fabrika/auth-core'
8
+ import {
9
+ type DecideGrantRequestInput,
10
+ GRANT_REQUEST_TTL_SECONDS,
11
+ type GrantRequestDto,
12
+ type ListGrantRequestsInput,
13
+ type SetGrantApprovalRequest,
14
+ } from '@fabrika/iam-contract'
15
+ import { uuidv7 } from '@fabrika/platform'
16
+ import { PROVISIONING_ADMIN_ID } from '../auth'
17
+ import { contractGrantProblem, externalGrantProblem } from '../contract-rules'
18
+ import { type AuditEventInput, auditLabelOf, type CreateGrantRequestInput, ExternalGrantError, type GrantRequestRow, type GrantSetRead } from '../db'
19
+ import { requestScopeValues } from '../repositories/grants'
20
+ import { unixNow } from '../repositories/sql'
21
+ import type { Services } from '../services'
22
+ import { parseStoredPermissions } from '../stored-permissions'
23
+ import { type AdminContext, adminEvent, fail } from './context'
24
+ import { appField, grantIdOf, parseRoleOrInline } from './grant-support'
25
+ import type { ResolvedAdmin } from './router'
26
+ import { managesApp, requireGrantablePrincipal } from './user-admin'
27
+
28
+ /** Whether a grant change at `app` waits; a cross-app grant reaches no application and never does. */
29
+ export async function grantsWait(services: Services, app: string | null): Promise<boolean> {
30
+ return app !== null && await services.repositories.grantRequests.grantsWait(app)
31
+ }
32
+
33
+ /** What a grant change asks for, before IAM records it; the request's timestamps are IAM's. */
34
+ export type GrantChangeRequest = Omit<CreateGrantRequestInput, 'requestedAt' | 'expiresAt'>
35
+
36
+ /** Record the change as a request, with its `iam.grant.request` record built by `event`, and answer it. */
37
+ export async function requestGrantChange(
38
+ services: Services,
39
+ change: GrantChangeRequest,
40
+ event: (requestId: string, metadata: Record<string, unknown>) => AuditEventInput,
41
+ ): Promise<GrantRequestDto> {
42
+ const now = unixNow()
43
+ const row = await services.repositories.grantRequests.create(
44
+ { ...change, requestedAt: now, expiresAt: now + GRANT_REQUEST_TTL_SECONDS },
45
+ (requestId) =>
46
+ event(requestId, {
47
+ kind: change.kind,
48
+ app: change.app,
49
+ principalId: change.principalId,
50
+ grantId: change.grantId,
51
+ roleKey: change.roleKey,
52
+ permissions: change.permissions,
53
+ scopeType: change.scopeType,
54
+ scopeValue: change.scopeValues?.[0] ?? null,
55
+ ...(change.scopeValues !== null && change.scopeValues.length > 1 ? { scopeValues: change.scopeValues } : {}),
56
+ }),
57
+ )
58
+ return toGrantRequestDto(services, row, now)
59
+ }
60
+
61
+ /** The open requests at the applications the caller administers, the oldest first. */
62
+ export async function listGrantRequestsUseCase(c: AdminContext, input: ListGrantRequestsInput): Promise<{ items: GrantRequestDto[] }> {
63
+ const now = unixNow()
64
+ const rows = (await c.services.repositories.grantRequests.listOpen(now)).filter((row) =>
65
+ (input.app === undefined || row.app === input.app) && managesApp(c.services, c.administration, row.app)
66
+ )
67
+ return { items: await Promise.all(rows.map((row) => toGrantRequestDto(c.services, row, now))) }
68
+ }
69
+
70
+ /**
71
+ * Approve or reject one open request. Only a person in a signed-in session decides (`person`), never a `px_` key; an
72
+ * application the caller does not administer and an unknown request are one 404. The requester may reject (withdraw)
73
+ * their own request, never approve it.
74
+ */
75
+ export async function decideGrantRequestUseCase(c: AdminContext, person: boolean, input: DecideGrantRequestInput): Promise<GrantRequestDto> {
76
+ const requests = c.services.repositories.grantRequests
77
+ const request = await requests.get(input.id)
78
+ if (request === null || !managesApp(c.services, c.administration, request.app)) return fail(404, 'grant request not found')
79
+ if (!person) return fail(403, 'only a person signed in to the console decides a grant request, never a key')
80
+ const now = unixNow()
81
+ if (request.status !== 'pending' || request.expires_at <= now) return fail(409, 'the grant request is no longer open')
82
+ if (input.decision === 'reject') {
83
+ const rejected = await requests.reject(
84
+ request.id,
85
+ c.admin.id,
86
+ now,
87
+ adminEvent(c, {
88
+ action: 'iam.grant.request.reject',
89
+ resourceType: 'grant_request',
90
+ resourceId: request.id,
91
+ metadata: { app: request.app, kind: request.kind, principalId: request.principal_id, requestedBy: request.requested_by },
92
+ }),
93
+ )
94
+ return rejected === null ? fail(409, 'the grant request is no longer open') : toGrantRequestDto(c.services, rejected, now)
95
+ }
96
+ if (request.requested_by === c.admin.id) {
97
+ return fail(403, 'another administrator of the application approves a grant request; you may reject your own')
98
+ }
99
+ const current = await approvable(c, request)
100
+ const decision = { id: uuidv7(), by: c.admin.id, at: now }
101
+ const action = request.kind === 'create' ? 'iam.grant.create' : request.kind === 'update' ? 'iam.grant.update' : 'iam.grant.revoke'
102
+ const scopeValues = requestScopeValues(request)
103
+ let applied: Awaited<ReturnType<typeof c.services.repositories.grants.applyRequest>>
104
+ try {
105
+ applied = await c.services.repositories.grants.applyRequest(request, current, decision, (grantId) =>
106
+ adminEvent(c, {
107
+ action,
108
+ resourceType: 'grant',
109
+ resourceId: grantId,
110
+ metadata: {
111
+ principalId: request.principal_id,
112
+ app: request.app,
113
+ roleKey: request.role_key,
114
+ permissions: request.permissions === null ? null : parseStoredPermissions(request.permissions),
115
+ scopeType: request.scope_type,
116
+ scopeValue: scopeValues?.[0] ?? null,
117
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
118
+ grantRequestId: request.id,
119
+ requestedBy: request.requested_by,
120
+ },
121
+ }))
122
+ } catch (cause) {
123
+ // Both roll the whole batch back, the claim included: the request stays open for a later decision or a rejection.
124
+ if (cause instanceof ExternalGrantError) return fail(409, `${cause.message}; reject the request`)
125
+ if (await heldElsewhere(c, request)) return fail(409, 'the principal already holds this grant; reject the request')
126
+ throw cause
127
+ }
128
+ if (!applied.claimed) return fail(409, 'the grant request is no longer open')
129
+ if (applied.changed === null) {
130
+ return fail(409, 'the change no longer applies: the access changed since the checks; the request is closed as failed')
131
+ }
132
+ const decided = await requests.get(request.id)
133
+ return decided === null ? fail(404, 'grant request not found') : toGrantRequestDto(c.services, decided, now)
134
+ }
135
+
136
+ /** The caller of a grant request procedure who administers no IAM application: an application's own administrator. */
137
+ export interface GrantRequester {
138
+ readonly services: Services
139
+ readonly requestId: string
140
+ readonly admin: ResolvedAdmin
141
+ }
142
+
143
+ /** A requester without IAM administration sees only the requests they made (an application administrator's own). */
144
+ export async function listOwnGrantRequestsUseCase(c: GrantRequester, input: ListGrantRequestsInput): Promise<{ items: GrantRequestDto[] }> {
145
+ const now = unixNow()
146
+ const rows = (await c.services.repositories.grantRequests.listOpen(now)).filter((row) =>
147
+ (input.app === undefined || row.app === input.app) && row.requested_by === c.admin.id
148
+ )
149
+ return { items: await Promise.all(rows.map((row) => toGrantRequestDto(c.services, row, now))) }
150
+ }
151
+
152
+ /**
153
+ * A requester without IAM administration withdraws a request they made, as a person in a signed-in session; any other
154
+ * request, and approving, is the 404 of an unknown one. The record is filed under the request's application.
155
+ */
156
+ export async function withdrawOwnGrantRequestUseCase(c: GrantRequester, input: DecideGrantRequestInput): Promise<GrantRequestDto> {
157
+ const requests = c.services.repositories.grantRequests
158
+ const request = await requests.get(input.id)
159
+ if (request === null || request.requested_by !== c.admin.id || input.decision !== 'reject') return fail(404, 'grant request not found')
160
+ if (c.admin.type !== 'user' || !c.admin.session) return fail(403, 'only a person signed in to the console decides a grant request, never a key')
161
+ const now = unixNow()
162
+ const rejected = await requests.reject(request.id, c.admin.id, now, {
163
+ requestId: c.requestId,
164
+ principalId: c.admin.id,
165
+ principalLabel: auditLabelOf(c.admin),
166
+ app: request.app,
167
+ action: 'iam.grant.request.reject',
168
+ resourceType: 'grant_request',
169
+ resourceId: request.id,
170
+ metadata: { app: request.app, kind: request.kind, principalId: request.principal_id, requestedBy: request.requested_by },
171
+ })
172
+ return rejected === null ? fail(409, 'the grant request is no longer open') : toGrantRequestDto(c.services, rejected, now)
173
+ }
174
+
175
+ /**
176
+ * The checks the original change ran, again, with the approver as the administrator: the approver must be able to make
177
+ * the change now. Answers the grant an `update` or a `revoke` acts on.
178
+ */
179
+ async function approvable(c: AdminContext, request: GrantRequestRow): Promise<GrantSetRead | null> {
180
+ const { grants, principals, appSchema } = c.services.repositories
181
+ const principal = await principals.getPrincipalById(request.principal_id)
182
+ if (principal === null) return fail(409, 'the principal no longer exists; reject the request')
183
+ if (await grants.isWorkloadPrincipal(principal.id)) return fail(409, 'a job, a webhook or a connector holds no grant')
184
+ requireGrantablePrincipal(c, principal)
185
+ const current = request.grant_id === null ? null : await grants.getGrantSet(request.grant_id)
186
+ const [held] = current?.rows ?? []
187
+ if (request.kind !== 'create' && (held === undefined || held.app !== request.app || held.principal_id !== principal.id)) {
188
+ return fail(409, 'the grant is gone; reject the request')
189
+ }
190
+ if (request.kind === 'revoke') return current
191
+ if (!(await appField(c, { app: request.app })).ok) return fail(409, 'the application is no longer registered; reject the request')
192
+ const parsed = await parseRoleOrInline(
193
+ c,
194
+ request.role_key === null ? { permissions: parseStoredPermissions(request.permissions ?? '[]') } : { roleKey: request.role_key },
195
+ request.app,
196
+ )
197
+ if (!parsed.ok) return fail(409, `${parsed.message}; reject the request`)
198
+ const authorization = {
199
+ roleKey: request.role_key,
200
+ permissions: request.permissions === null ? null : parseStoredPermissions(request.permissions),
201
+ scopeType: request.scope_type,
202
+ }
203
+ const problem = await contractGrantProblem(appSchema, request.app, authorization, principal.type === 'user')
204
+ ?? await externalGrantProblem(appSchema, principal, request.app, authorization)
205
+ if (problem !== null) return fail(409, problem)
206
+ if (await heldElsewhere(c, request)) return fail(409, 'the principal already holds this grant; reject the request')
207
+ return current
208
+ }
209
+
210
+ /**
211
+ * Whether another grant of the principal already holds the requested role in one of the requested values. A scoped one
212
+ * counts expired too: the unique index refuses the value either way; only an expired app-wide grant is renewed in place.
213
+ */
214
+ async function heldElsewhere(c: AdminContext, request: GrantRequestRow): Promise<boolean> {
215
+ if (request.role_key === null) return false
216
+ const values = requestScopeValues(request)
217
+ return (await c.services.repositories.grants.listGrants(request.principal_id)).some((grant) =>
218
+ grantIdOf(grant) !== request.grant_id && grant.app === request.app && grant.role_key === request.role_key
219
+ && grant.scope_type === request.scope_type
220
+ && (values === null
221
+ ? grant.scope_value === null && (grant.expires_at === null || grant.expires_at > unixNow())
222
+ : grant.scope_value !== null && values.includes(grant.scope_value))
223
+ )
224
+ }
225
+
226
+ /**
227
+ * Make grant changes at `app` wait, or apply at once again (ADR-0083 §4). Only Control sets it, with the provisioning
228
+ * key, when an environment chooses or drops the `grants` category: an installation administrator who could switch it
229
+ * off could grant past it. Only an application environment id qualifies.
230
+ */
231
+ export async function setGrantApprovalUseCase(c: AdminContext, input: SetGrantApprovalRequest): Promise<SetGrantApprovalRequest> {
232
+ if (c.admin.id !== PROVISIONING_ADMIN_ID) {
233
+ return fail(403, 'only Control sets whether grants wait, with the provisioning key')
234
+ }
235
+ if (parseAppEnvironmentId(input.app) === null || c.services.config.platformAudiences.has(input.app)) {
236
+ return fail(400, 'grant approval applies to an application environment id `<app>@<env>`')
237
+ }
238
+ const stored = await c.services.repositories.grantRequests.setGrantsWait(
239
+ input.app,
240
+ input.required,
241
+ input.revision,
242
+ unixNow(),
243
+ adminEvent(c, {
244
+ action: 'iam.grant_approval.set',
245
+ resourceType: 'app',
246
+ resourceId: input.app,
247
+ metadata: { required: input.required, revision: input.revision },
248
+ }),
249
+ )
250
+ return { app: input.app, ...stored }
251
+ }
252
+
253
+ async function toGrantRequestDto(services: Services, row: GrantRequestRow, now: number): Promise<GrantRequestDto> {
254
+ const { principals } = services.repositories
255
+ return {
256
+ id: row.id,
257
+ app: row.app,
258
+ kind: row.kind,
259
+ principalId: row.principal_id,
260
+ principalLabel: (await principals.getPrincipalById(row.principal_id))?.label ?? null,
261
+ grantId: row.grant_id,
262
+ roleKey: row.role_key,
263
+ permissions: row.permissions === null ? null : parseStoredPermissions(row.permissions),
264
+ scopeType: row.scope_type,
265
+ scopeValue: row.scope_value,
266
+ scopeValues: requestScopeValues(row),
267
+ grantExpiresAt: row.grant_expires_at,
268
+ requestedBy: row.requested_by,
269
+ requestedByLabel: (await principals.getPrincipalById(row.requested_by))?.label ?? null,
270
+ requestedAt: row.requested_at,
271
+ expiresAt: row.expires_at,
272
+ status: row.status === 'pending' && row.expires_at <= now ? 'expired' : row.status,
273
+ decidedBy: row.decided_by,
274
+ decidedAt: row.decided_at,
275
+ }
276
+ }