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

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,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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/iam",
3
- "version": "0.9.0-dev.34",
3
+ "version": "0.9.0-dev.36",
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.34",
60
- "@fabrika/auth": "0.9.0-dev.34",
61
- "@fabrika/auth-core": "0.9.0-dev.34",
62
- "@fabrika/control-contract": "0.9.0-dev.34",
63
- "@fabrika/email": "0.9.0-dev.34",
64
- "@fabrika/iam-contract": "0.9.0-dev.34",
65
- "@fabrika/platform": "0.9.0-dev.34",
66
- "@fabrika/platform-node": "0.9.0-dev.34",
67
- "@fabrika/provider-cloudflare": "0.9.0-dev.34",
68
- "@fabrika/proxy-core": "0.9.0-dev.34",
59
+ "@fabrika/app": "0.9.0-dev.36",
60
+ "@fabrika/auth": "0.9.0-dev.36",
61
+ "@fabrika/auth-core": "0.9.0-dev.36",
62
+ "@fabrika/control-contract": "0.9.0-dev.36",
63
+ "@fabrika/email": "0.9.0-dev.36",
64
+ "@fabrika/iam-contract": "0.9.0-dev.36",
65
+ "@fabrika/platform": "0.9.0-dev.36",
66
+ "@fabrika/platform-node": "0.9.0-dev.36",
67
+ "@fabrika/provider-cloudflare": "0.9.0-dev.36",
68
+ "@fabrika/proxy-core": "0.9.0-dev.36",
69
69
  "jose": "^5.9.0",
70
70
  "uqr": "^0.1.3",
71
71
  "zod": "^3.25.76"
@@ -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
+ scopeValue: 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
+ scopeValue: 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,
@@ -0,0 +1,253 @@
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, type GrantRequestRow, type GrantRow } from '../db'
19
+ import { unixNow } from '../repositories/sql'
20
+ import type { Services } from '../services'
21
+ import { parseStoredPermissions } from '../stored-permissions'
22
+ import { type AdminContext, adminEvent, fail } from './context'
23
+ import { appField, parseRoleOrInline } from './grant-support'
24
+ import type { ResolvedAdmin } from './router'
25
+ import { managesApp, requireGrantablePrincipal } from './user-admin'
26
+
27
+ /** Whether a grant change at `app` waits; a cross-app grant reaches no application and never does. */
28
+ export async function grantsWait(services: Services, app: string | null): Promise<boolean> {
29
+ return app !== null && await services.repositories.grantRequests.grantsWait(app)
30
+ }
31
+
32
+ /** What a grant change asks for, before IAM records it; the request's timestamps are IAM's. */
33
+ export type GrantChangeRequest = Omit<CreateGrantRequestInput, 'requestedAt' | 'expiresAt'>
34
+
35
+ /** Record the change as a request, with its `iam.grant.request` record built by `event`, and answer it. */
36
+ export async function requestGrantChange(
37
+ services: Services,
38
+ change: GrantChangeRequest,
39
+ event: (requestId: string, metadata: Record<string, unknown>) => AuditEventInput,
40
+ ): Promise<GrantRequestDto> {
41
+ const now = unixNow()
42
+ const row = await services.repositories.grantRequests.create(
43
+ { ...change, requestedAt: now, expiresAt: now + GRANT_REQUEST_TTL_SECONDS },
44
+ (requestId) =>
45
+ event(requestId, {
46
+ kind: change.kind,
47
+ app: change.app,
48
+ principalId: change.principalId,
49
+ grantId: change.grantId,
50
+ roleKey: change.roleKey,
51
+ permissions: change.permissions,
52
+ scopeType: change.scopeType,
53
+ scopeValue: change.scopeValue,
54
+ }),
55
+ )
56
+ return toGrantRequestDto(services, row, now)
57
+ }
58
+
59
+ /** The open requests at the applications the caller administers, the oldest first. */
60
+ export async function listGrantRequestsUseCase(c: AdminContext, input: ListGrantRequestsInput): Promise<{ items: GrantRequestDto[] }> {
61
+ const now = unixNow()
62
+ const rows = (await c.services.repositories.grantRequests.listOpen(now)).filter((row) =>
63
+ (input.app === undefined || row.app === input.app) && managesApp(c.services, c.administration, row.app)
64
+ )
65
+ return { items: await Promise.all(rows.map((row) => toGrantRequestDto(c.services, row, now))) }
66
+ }
67
+
68
+ /**
69
+ * Approve or reject one open request. Only a person in a signed-in session decides (`person`), never a `px_` key; an
70
+ * application the caller does not administer and an unknown request are one 404. The requester may reject (withdraw)
71
+ * their own request, never approve it.
72
+ */
73
+ export async function decideGrantRequestUseCase(c: AdminContext, person: boolean, input: DecideGrantRequestInput): Promise<GrantRequestDto> {
74
+ const requests = c.services.repositories.grantRequests
75
+ const request = await requests.get(input.id)
76
+ if (request === null || !managesApp(c.services, c.administration, request.app)) return fail(404, 'grant request not found')
77
+ if (!person) return fail(403, 'only a person signed in to the console decides a grant request, never a key')
78
+ const now = unixNow()
79
+ if (request.status !== 'pending' || request.expires_at <= now) return fail(409, 'the grant request is no longer open')
80
+ if (input.decision === 'reject') {
81
+ const rejected = await requests.reject(
82
+ request.id,
83
+ c.admin.id,
84
+ now,
85
+ adminEvent(c, {
86
+ action: 'iam.grant.request.reject',
87
+ resourceType: 'grant_request',
88
+ resourceId: request.id,
89
+ metadata: { app: request.app, kind: request.kind, principalId: request.principal_id, requestedBy: request.requested_by },
90
+ }),
91
+ )
92
+ return rejected === null ? fail(409, 'the grant request is no longer open') : toGrantRequestDto(c.services, rejected, now)
93
+ }
94
+ if (request.requested_by === c.admin.id) {
95
+ return fail(403, 'another administrator of the application approves a grant request; you may reject your own')
96
+ }
97
+ const current = await approvable(c, request)
98
+ const decision = { id: uuidv7(), by: c.admin.id, at: now }
99
+ const action = request.kind === 'create' ? 'iam.grant.create' : request.kind === 'update' ? 'iam.grant.update' : 'iam.grant.revoke'
100
+ const applied = await c.services.repositories.grants.applyRequest(request, current, decision, (grantId) =>
101
+ adminEvent(c, {
102
+ action,
103
+ resourceType: 'grant',
104
+ resourceId: grantId,
105
+ metadata: {
106
+ principalId: request.principal_id,
107
+ app: request.app,
108
+ roleKey: request.role_key,
109
+ permissions: request.permissions === null ? null : parseStoredPermissions(request.permissions),
110
+ scopeType: request.scope_type,
111
+ scopeValue: request.scope_value,
112
+ grantRequestId: request.id,
113
+ requestedBy: request.requested_by,
114
+ },
115
+ }))
116
+ if (!applied.claimed) return fail(409, 'the grant request is no longer open')
117
+ if (applied.changed === null) {
118
+ return fail(409, 'the change no longer applies: the access changed since the checks; the request is closed as failed')
119
+ }
120
+ const decided = await requests.get(request.id)
121
+ return decided === null ? fail(404, 'grant request not found') : toGrantRequestDto(c.services, decided, now)
122
+ }
123
+
124
+ /** The caller of a grant request procedure who administers no IAM application: an application's own administrator. */
125
+ export interface GrantRequester {
126
+ readonly services: Services
127
+ readonly requestId: string
128
+ readonly admin: ResolvedAdmin
129
+ }
130
+
131
+ /** A requester without IAM administration sees only the requests they made (an application administrator's own). */
132
+ export async function listOwnGrantRequestsUseCase(c: GrantRequester, input: ListGrantRequestsInput): Promise<{ items: GrantRequestDto[] }> {
133
+ const now = unixNow()
134
+ const rows = (await c.services.repositories.grantRequests.listOpen(now)).filter((row) =>
135
+ (input.app === undefined || row.app === input.app) && row.requested_by === c.admin.id
136
+ )
137
+ return { items: await Promise.all(rows.map((row) => toGrantRequestDto(c.services, row, now))) }
138
+ }
139
+
140
+ /**
141
+ * A requester without IAM administration withdraws a request they made, as a person in a signed-in session; any other
142
+ * request, and approving, is the 404 of an unknown one. The record is filed under the request's application.
143
+ */
144
+ export async function withdrawOwnGrantRequestUseCase(c: GrantRequester, input: DecideGrantRequestInput): Promise<GrantRequestDto> {
145
+ const requests = c.services.repositories.grantRequests
146
+ const request = await requests.get(input.id)
147
+ if (request === null || request.requested_by !== c.admin.id || input.decision !== 'reject') return fail(404, 'grant request not found')
148
+ 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')
149
+ const now = unixNow()
150
+ const rejected = await requests.reject(request.id, c.admin.id, now, {
151
+ requestId: c.requestId,
152
+ principalId: c.admin.id,
153
+ principalLabel: auditLabelOf(c.admin),
154
+ app: request.app,
155
+ action: 'iam.grant.request.reject',
156
+ resourceType: 'grant_request',
157
+ resourceId: request.id,
158
+ metadata: { app: request.app, kind: request.kind, principalId: request.principal_id, requestedBy: request.requested_by },
159
+ })
160
+ return rejected === null ? fail(409, 'the grant request is no longer open') : toGrantRequestDto(c.services, rejected, now)
161
+ }
162
+
163
+ /**
164
+ * The checks the original change ran, again, with the approver as the administrator: the approver must be able to make
165
+ * the change now. Answers the grant an `update` or a `revoke` acts on.
166
+ */
167
+ async function approvable(c: AdminContext, request: GrantRequestRow): Promise<GrantRow | null> {
168
+ const { grants, principals, appSchema } = c.services.repositories
169
+ const principal = await principals.getPrincipalById(request.principal_id)
170
+ if (principal === null) return fail(409, 'the principal no longer exists; reject the request')
171
+ if (await grants.isWorkloadPrincipal(principal.id)) return fail(409, 'a job, a webhook or a connector holds no grant')
172
+ requireGrantablePrincipal(c, principal)
173
+ const current = request.grant_id === null ? null : await grants.getGrantById(request.grant_id)
174
+ if (request.kind !== 'create' && (current === null || current.app !== request.app || current.principal_id !== principal.id)) {
175
+ return fail(409, 'the grant is gone; reject the request')
176
+ }
177
+ if (request.kind === 'revoke') return current
178
+ if (!(await appField(c, { app: request.app })).ok) return fail(409, 'the application is no longer registered; reject the request')
179
+ const parsed = await parseRoleOrInline(
180
+ c,
181
+ request.role_key === null ? { permissions: parseStoredPermissions(request.permissions ?? '[]') } : { roleKey: request.role_key },
182
+ request.app,
183
+ )
184
+ if (!parsed.ok) return fail(409, `${parsed.message}; reject the request`)
185
+ const authorization = {
186
+ roleKey: request.role_key,
187
+ permissions: request.permissions === null ? null : parseStoredPermissions(request.permissions),
188
+ scopeType: request.scope_type,
189
+ }
190
+ const problem = await contractGrantProblem(appSchema, request.app, authorization, principal.type === 'user')
191
+ ?? await externalGrantProblem(appSchema, principal, request.app, authorization)
192
+ if (problem !== null) return fail(409, problem)
193
+ if (request.role_key !== null) {
194
+ const held = (await grants.listGrants(principal.id)).some((grant) =>
195
+ grant.id !== request.grant_id && grant.app === request.app && grant.role_key === request.role_key
196
+ && grant.scope_type === request.scope_type && grant.scope_value === request.scope_value
197
+ && (grant.expires_at === null || grant.expires_at > unixNow())
198
+ )
199
+ if (held) return fail(409, 'the principal already holds this grant; reject the request')
200
+ }
201
+ return current
202
+ }
203
+
204
+ /**
205
+ * Make grant changes at `app` wait, or apply at once again (ADR-0083 §4). Only Control sets it, with the provisioning
206
+ * key, when an environment chooses or drops the `grants` category: an installation administrator who could switch it
207
+ * off could grant past it. Only an application environment id qualifies.
208
+ */
209
+ export async function setGrantApprovalUseCase(c: AdminContext, input: SetGrantApprovalRequest): Promise<SetGrantApprovalRequest> {
210
+ if (c.admin.id !== PROVISIONING_ADMIN_ID) {
211
+ return fail(403, 'only Control sets whether grants wait, with the provisioning key')
212
+ }
213
+ if (parseAppEnvironmentId(input.app) === null || c.services.config.platformAudiences.has(input.app)) {
214
+ return fail(400, 'grant approval applies to an application environment id `<app>@<env>`')
215
+ }
216
+ const stored = await c.services.repositories.grantRequests.setGrantsWait(
217
+ input.app,
218
+ input.required,
219
+ input.revision,
220
+ unixNow(),
221
+ adminEvent(c, {
222
+ action: 'iam.grant_approval.set',
223
+ resourceType: 'app',
224
+ resourceId: input.app,
225
+ metadata: { required: input.required, revision: input.revision },
226
+ }),
227
+ )
228
+ return { app: input.app, ...stored }
229
+ }
230
+
231
+ async function toGrantRequestDto(services: Services, row: GrantRequestRow, now: number): Promise<GrantRequestDto> {
232
+ const { principals } = services.repositories
233
+ return {
234
+ id: row.id,
235
+ app: row.app,
236
+ kind: row.kind,
237
+ principalId: row.principal_id,
238
+ principalLabel: (await principals.getPrincipalById(row.principal_id))?.label ?? null,
239
+ grantId: row.grant_id,
240
+ roleKey: row.role_key,
241
+ permissions: row.permissions === null ? null : parseStoredPermissions(row.permissions),
242
+ scopeType: row.scope_type,
243
+ scopeValue: row.scope_value,
244
+ grantExpiresAt: row.grant_expires_at,
245
+ requestedBy: row.requested_by,
246
+ requestedByLabel: (await principals.getPrincipalById(row.requested_by))?.label ?? null,
247
+ requestedAt: row.requested_at,
248
+ expiresAt: row.expires_at,
249
+ status: row.status === 'pending' && row.expires_at <= now ? 'expired' : row.status,
250
+ decidedBy: row.decided_by,
251
+ decidedAt: row.decided_at,
252
+ }
253
+ }
@@ -1,11 +1,19 @@
1
- import { type CreateGrantRequest, type GrantDto, type OkResponse, type UpdateGrantInput } from '@fabrika/iam-contract'
1
+ import {
2
+ type CreateGrantRequest,
3
+ type GrantChangeResponse,
4
+ type OkResponse,
5
+ type PendingGrantChange,
6
+ type UpdateGrantInput,
7
+ } from '@fabrika/iam-contract'
2
8
  import { contractGrantProblem, externalGrantProblem } from '../contract-rules'
3
9
  import { ExternalGrantError, type GrantRow } from '../db'
10
+ import { parseStoredPermissions } from '../stored-permissions'
4
11
  import { type AdminContext, adminEvent, fail } from './context'
12
+ import { type GrantChangeRequest, grantsWait, requestGrantChange } from './grant-requests'
5
13
  import { appField, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDto } from './grant-support'
6
14
  import { requireGrantablePrincipal, requireManagedApp } from './user-admin'
7
15
 
8
- export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantDto> {
16
+ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantChangeResponse> {
9
17
  const principalId = input.principalId
10
18
  if (principalId.trim() === '') return fail(400, 'principalId required')
11
19
  if (await c.services.repositories.grants.isWorkloadPrincipal(principalId)) {
@@ -46,6 +54,26 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
46
54
  }
47
55
  const values = { principalId, app, scopeType: scope.scopeType, scopeValue: scope.scopeValue, grantedBy: c.admin.id, expiresAt }
48
56
  const roleKey = roleOrInline.roleKey
57
+ if (app !== null && await grantsWait(c.services, app)) {
58
+ 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}`)
62
+ }
63
+ }
64
+ return await pendingChange(c, {
65
+ app,
66
+ kind: 'create',
67
+ principalId,
68
+ grantId: null,
69
+ roleKey,
70
+ permissions: roleOrInline.permissions,
71
+ scopeType: scope.scopeType,
72
+ scopeValue: scope.scopeValue,
73
+ grantExpiresAt: expiresAt,
74
+ requestedBy: c.admin.id,
75
+ })
76
+ }
49
77
  const record = (grantId: string) =>
50
78
  adminEvent(c, {
51
79
  action: 'iam.grant.create',
@@ -82,7 +110,7 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
82
110
  return toGrantDto(grant, cache)
83
111
  }
84
112
 
85
- export async function deleteGrantUseCase(c: AdminContext, input: { id: string }): Promise<OkResponse> {
113
+ export async function deleteGrantUseCase(c: AdminContext, input: { id: string }): Promise<OkResponse & Partial<PendingGrantChange>> {
86
114
  const id = input.id
87
115
  const grant = await c.services.repositories.grants.getGrantById(id)
88
116
  if (!grant) {
@@ -94,6 +122,23 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
94
122
  return fail(404, 'grant not found')
95
123
  }
96
124
  requireGrantablePrincipal(c, principal)
125
+ if (grant.app !== null && await grantsWait(c.services, grant.app)) {
126
+ return {
127
+ ok: true,
128
+ ...await pendingChange(c, {
129
+ app: grant.app,
130
+ kind: 'revoke',
131
+ principalId: grant.principal_id,
132
+ grantId: grant.id,
133
+ roleKey: grant.role_key,
134
+ permissions: grant.permissions === null ? null : parseStoredPermissions(grant.permissions),
135
+ scopeType: grant.scope_type,
136
+ scopeValue: grant.scope_value,
137
+ grantExpiresAt: grant.expires_at,
138
+ requestedBy: c.admin.id,
139
+ }),
140
+ }
141
+ }
97
142
  await c.services.repositories.grants.deleteGrant(
98
143
  id,
99
144
  adminEvent(c, {
@@ -112,7 +157,7 @@ export async function deleteGrantUseCase(c: AdminContext, input: { id: string })
112
157
  }
113
158
 
114
159
  /** 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> {
160
+ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantChangeResponse> {
116
161
  const grant = await c.services.repositories.grants.getGrantById(input.id)
117
162
  if (grant === null) return fail(404, 'grant not found')
118
163
  requireManagedApp(c, grant.app)
@@ -151,6 +196,20 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
151
196
  ? 'This user already has that role in this scope. Edit the existing access instead.'
152
197
  : 'This key already has that role in this scope. Edit the existing grant instead.'
153
198
  if (await duplicate()) return fail(409, held)
199
+ if (grant.app !== null && await grantsWait(c.services, grant.app)) {
200
+ return await pendingChange(c, {
201
+ app: grant.app,
202
+ kind: 'update',
203
+ principalId: principal.id,
204
+ grantId: grant.id,
205
+ roleKey: authorization.roleKey,
206
+ permissions: authorization.permissions,
207
+ scopeType: scope.scopeType,
208
+ scopeValue: scope.scopeValue,
209
+ grantExpiresAt: expiresAt,
210
+ requestedBy: c.admin.id,
211
+ })
212
+ }
154
213
  let updated: GrantRow | null
155
214
  try {
156
215
  updated = await c.services.repositories.grants.updateGrant(
@@ -200,3 +259,13 @@ async function findHeldRoleGrant(
200
259
  && row.scope_value === candidate.scopeValue
201
260
  )
202
261
  }
262
+
263
+ /** Record a grant change at an application whose grants wait (ADR-0083): nothing changes until another administrator approves. */
264
+ async function pendingChange(c: AdminContext, change: GrantChangeRequest): Promise<PendingGrantChange> {
265
+ const pending = await requestGrantChange(
266
+ c.services,
267
+ change,
268
+ (requestId, metadata) => adminEvent(c, { action: 'iam.grant.request', resourceType: 'grant_request', resourceId: requestId, metadata }),
269
+ )
270
+ return { pending }
271
+ }
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'
@@ -97,6 +105,28 @@ export const adminRpcRouter: RpcRouterFor<IamAppContext, IamAdminRpcContract> =
97
105
  .mutation(({ ctx, input }) => adminUseCases.updateGrant(context(ctx), input)),
98
106
  delete: t.procedure.input(z.object({ id: nonEmpty })).mutation(({ ctx, input }) => adminUseCases.deleteGrant(context(ctx), input)),
99
107
  }),
108
+ // No `iam.admin` here: an administrator of each request's application decides it (ADR-0083), a person in a session.
109
+ grantRequests: t.router({
110
+ list: t.procedure.input(z.object({ app: nonEmpty.optional() }).default({})).query(({ ctx, input }) => {
111
+ const requester = ownRequester(ctx)
112
+ return requester === null ? listGrantRequestsUseCase(context(ctx), input) : listOwnGrantRequestsUseCase(requester, input)
113
+ }),
114
+ decide: t.procedure
115
+ .input(z.object({ id: nonEmpty, decision: z.enum(['approve', 'reject']) }))
116
+ .mutation(({ ctx, input }) => {
117
+ const requester = ownRequester(ctx)
118
+ return requester === null
119
+ ? decideGrantRequestUseCase(context(ctx), ctx.admin?.type === 'user' && ctx.admin.session, input)
120
+ : withdrawOwnGrantRequestUseCase(requester, input)
121
+ }),
122
+ }),
123
+ // Control's, with the provisioning key: whether an application environment's grants wait (ADR-0083).
124
+ grantApproval: t.router({
125
+ set: t.procedure
126
+ .input(z.object({ app: nonEmpty, required: z.boolean(), revision: z.number().int().nonnegative() }).strict())
127
+ .require(ADMIN_ACTION)
128
+ .mutation(({ ctx, input }) => setGrantApprovalUseCase(context(ctx), input)),
129
+ }),
100
130
  apps: t.router({
101
131
  list: t.procedure.query(({ ctx }) => adminUseCases.listApps(context(ctx))),
102
132
  getSchema: t.procedure.input(appInput).query(({ ctx, input }) => adminUseCases.getAppSchema(context(ctx), input)),
@@ -369,6 +399,12 @@ function authContext(admin: NonNullable<IamAppContext['admin']>): AuthContext {
369
399
  }
370
400
 
371
401
  /** The context of a caller with an administration; anyone else is refused before the use case runs. */
402
+ /** A caller with no IAM administration reaches only the grant requests it made itself (ADR-0083); null otherwise. */
403
+ function ownRequester(ctx: IamAppContext): GrantRequester | null {
404
+ if (ctx.admin === null) throw new UnauthorizedError()
405
+ return administrationOf(ctx.admin) === null ? { services: ctx.services, requestId: ctx.requestId, admin: ctx.admin } : null
406
+ }
407
+
372
408
  function context(ctx: IamAppContext): AdminContext {
373
409
  if (ctx.admin === null) throw new UnauthorizedError()
374
410
  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,6 +45,7 @@ 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'
48
+ export { type CreateGrantRequestInput, GrantRequestRepository, type GrantRequestRow } from './repositories/grant-requests'
47
49
  export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow } from './repositories/grants'
48
50
  export { type AuthCodeRow, HandoffRepository } from './repositories/handoff'
49
51
  export {
@@ -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),