@fabrika/iam 0.9.0-dev.35 → 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.
- package/migrations/0035_grant_requests.sql +41 -0
- package/migrations-postgres/0035_grant_requests.sql +41 -0
- package/package.json +11 -11
- package/src/admin/app-people.ts +54 -1
- package/src/admin/grant-requests.ts +253 -0
- package/src/admin/grants.ts +73 -4
- package/src/admin/rpc.ts +36 -0
- package/src/db.ts +4 -0
- package/src/oauth-http.ts +22 -2
- package/src/oauth.ts +52 -6
- package/src/repositories/audit.ts +5 -2
- package/src/repositories/grant-requests.ts +134 -0
- package/src/repositories/grants.ts +105 -0
- package/src/tokens.ts +1 -1
- package/types/src/admin/grant-requests.d.ts +42 -0
- package/types/src/admin/grants.d.ts +4 -4
- package/types/src/db.d.ts +3 -0
- package/types/src/oauth.d.ts +20 -6
- package/types/src/repositories/audit.d.ts +2 -0
- package/types/src/repositories/grant-requests.d.ts +64 -0
- package/types/src/repositories/grants.d.ts +16 -0
- package/types/src/tokens.d.ts +7 -0
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
|
|
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>`
|
package/src/oauth.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
OAUTH_IDENTITY_SCOPE,
|
|
13
13
|
type OAuthAuthorizationRequest,
|
|
14
14
|
type OAuthClientMetadataDocument,
|
|
15
|
+
type OAuthIdentityRole,
|
|
15
16
|
type OAuthResourceDto,
|
|
16
17
|
type OAuthRevocationRequest,
|
|
17
18
|
type OAuthTokenRequest,
|
|
@@ -31,7 +32,7 @@ import { authorityDeadline, resolveAuthorityAt } from './resolve'
|
|
|
31
32
|
import { generateToken, hashToken, timingSafeEqualHex } from './secret'
|
|
32
33
|
import type { Services } from './services'
|
|
33
34
|
import { getSigner, verifyResourceAccessToken } from './signing'
|
|
34
|
-
import { boundedToken } from './tokens'
|
|
35
|
+
import { boundedToken, mailboxClaim } from './tokens'
|
|
35
36
|
|
|
36
37
|
/** An authorization code is redeemed by the client's back end within seconds of the redirect. */
|
|
37
38
|
export const OAUTH_CODE_TTL_SECONDS = 60
|
|
@@ -274,6 +275,7 @@ export async function mintForGrant(
|
|
|
274
275
|
scopes: authority.scopes,
|
|
275
276
|
grantId: grant.id,
|
|
276
277
|
tokenId: uuidv7(),
|
|
278
|
+
...(authority.identity === undefined ? {} : { ...mailboxClaim(authority.principal), ...authority.identity }),
|
|
277
279
|
})
|
|
278
280
|
const token = await boundedToken((await getSigner(env)).signResourceToken(claims), { app: grant.app, subject: authority.principal.id })
|
|
279
281
|
if (token === null) return null
|
|
@@ -285,6 +287,15 @@ export async function mintForGrant(
|
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
|
|
290
|
+
/** What a grant's next token carries. `identity` is present on an identity resource's: its roles, when it declares them. */
|
|
291
|
+
export interface GrantAuthority {
|
|
292
|
+
principal: PrincipalRow
|
|
293
|
+
scopes: string[]
|
|
294
|
+
permissions: PermissionEntry[]
|
|
295
|
+
expiresAt: number | null
|
|
296
|
+
identity?: { roles?: string[] }
|
|
297
|
+
}
|
|
298
|
+
|
|
288
299
|
/**
|
|
289
300
|
* Everything a grant needs to still mean something, checked at every code exchange and refresh: the
|
|
290
301
|
* grant live, its client and resource still configured, the IAM session it was given under live and
|
|
@@ -295,7 +306,7 @@ export async function grantAuthority(
|
|
|
295
306
|
grant: OAuthGrantRow,
|
|
296
307
|
now: number,
|
|
297
308
|
resourceUri: string = grant.resource,
|
|
298
|
-
): Promise<
|
|
309
|
+
): Promise<GrantAuthority | null> {
|
|
299
310
|
const config = services.config.oauth
|
|
300
311
|
if (config === null || grant.revoked_at !== null || grant.expires_at <= now || !grantResources(grant).includes(resourceUri)) return null
|
|
301
312
|
const scopes = parseOAuthScopes(parseJsonOrNull(grant.scopes))
|
|
@@ -307,8 +318,16 @@ export async function grantAuthority(
|
|
|
307
318
|
}
|
|
308
319
|
const principal = await services.repositories.principals.getPrincipalById(grant.principal_id)
|
|
309
320
|
if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return null
|
|
310
|
-
|
|
311
|
-
|
|
321
|
+
if (ceiling.kind === 'identity') {
|
|
322
|
+
// An identity resource's token names the person and carries no permission. With declared roles it names those
|
|
323
|
+
// the person holds, and a person holding none gets no token: the grant stops at the next refresh.
|
|
324
|
+
const sessionEnd = sessionEndsAt(session, services.config)
|
|
325
|
+
if (ceiling.roles === undefined) return { principal, scopes, permissions: [], expiresAt: sessionEnd, identity: {} }
|
|
326
|
+
const held = await heldIdentityRoles(services, principal, grant.app, ceiling.roles)
|
|
327
|
+
if (held === null) return null
|
|
328
|
+
const expiresAt = Math.min(held.until ?? Number.POSITIVE_INFINITY, sessionEnd)
|
|
329
|
+
return { principal, scopes, permissions: [], expiresAt, identity: { roles: held.keys } }
|
|
330
|
+
}
|
|
312
331
|
const live = await resolveAuthorityAt(services, principal, grant.app)
|
|
313
332
|
const permissions = narrowPermissions(live.permissions, ceiling.permissions)
|
|
314
333
|
// A refreshed token ends with its login too: an OIDC login issued before the cap stores a later expiry than its end.
|
|
@@ -326,20 +345,47 @@ function grantCeiling(
|
|
|
326
345
|
grant: OAuthGrantRow,
|
|
327
346
|
resourceUri: string,
|
|
328
347
|
scopes: readonly string[],
|
|
329
|
-
): { kind: 'identity' } | { kind: 'scoped'; permissions: KeyGrant[] } | null {
|
|
348
|
+
): { kind: 'identity'; roles: readonly OAuthIdentityRole[] | undefined } | { kind: 'scoped'; permissions: KeyGrant[] } | null {
|
|
330
349
|
const cli = grant.client_id === OAUTH_CLI_CLIENT_ID
|
|
331
350
|
const client = config.clients.find((entry) => entry.clientId === grant.client_id)
|
|
332
351
|
if (!cli && client === undefined) return null
|
|
333
352
|
const identity = client?.identity
|
|
334
353
|
if (identity !== undefined) {
|
|
335
354
|
const matches = identity.resource === resourceUri && identity.app === grant.app && sameScopes(scopes, [OAUTH_IDENTITY_SCOPE])
|
|
336
|
-
return matches ? { kind: 'identity' } : null
|
|
355
|
+
return matches ? { kind: 'identity', roles: identity.roles } : null
|
|
337
356
|
}
|
|
338
357
|
const resource = config.resources.find((entry) => entry.resource === resourceUri && entry.app === grant.app && servesClient(entry, cli))
|
|
339
358
|
const permissions = resource === undefined ? null : scopeCeiling(resource, scopes)
|
|
340
359
|
return permissions === null ? null : { kind: 'scoped', permissions }
|
|
341
360
|
}
|
|
342
361
|
|
|
362
|
+
/**
|
|
363
|
+
* The declared roles `principal` holds at an external application, in declared order, and when the earliest of them
|
|
364
|
+
* ends (null: none ends); null when it holds none. Only a global grant of a declared role counts, and only for an
|
|
365
|
+
* internal principal: an external one holds nothing but roles its application declares external (ADR-0051).
|
|
366
|
+
*/
|
|
367
|
+
export async function heldIdentityRoles(
|
|
368
|
+
services: Services,
|
|
369
|
+
principal: PrincipalRow,
|
|
370
|
+
app: string,
|
|
371
|
+
declared: readonly OAuthIdentityRole[],
|
|
372
|
+
): Promise<{ keys: string[]; until: number | null } | null> {
|
|
373
|
+
if (principal.affiliation !== 'internal') return null
|
|
374
|
+
const grants = await services.repositories.grants.getActiveGrantsForApp(principal.id, app, { includeCrossApp: false })
|
|
375
|
+
const held = new Map<string, number | null>()
|
|
376
|
+
for (const grant of grants) {
|
|
377
|
+
const key = grant.role_key
|
|
378
|
+
if (key === null || grant.app !== app || grant.scope_type !== null || !declared.some((role) => role.key === key)) continue
|
|
379
|
+
const known = held.get(key)
|
|
380
|
+
// A role holds until the last of its grants ends.
|
|
381
|
+
held.set(key, known === undefined ? grant.expires_at : known === null || grant.expires_at === null ? null : Math.max(known, grant.expires_at))
|
|
382
|
+
}
|
|
383
|
+
const keys = declared.map((role) => role.key).filter((key) => held.has(key))
|
|
384
|
+
if (keys.length === 0) return null
|
|
385
|
+
const ends = [...held.values()].filter((until): until is number => until !== null)
|
|
386
|
+
return { keys, until: ends.length === 0 ? null : Math.min(...ends) }
|
|
387
|
+
}
|
|
388
|
+
|
|
343
389
|
function sameScopes(scopes: readonly string[], expected: readonly string[]): boolean {
|
|
344
390
|
return scopes.length === expected.length && scopes.every((scope, index) => scope === expected[index])
|
|
345
391
|
}
|
|
@@ -148,6 +148,8 @@ export interface AuditedChange {
|
|
|
148
148
|
readonly statements: SqlStatement[]
|
|
149
149
|
/** The rows the LAST change returned, read from the results of a batch whose statements start at `offset`. */
|
|
150
150
|
rows<T>(results: SqlQueryResult<T>[], offset?: number): T[]
|
|
151
|
+
/** The id of the record, which exists after the batch exactly when the change changed a row; null without a record. */
|
|
152
|
+
readonly recordId: string | null
|
|
151
153
|
}
|
|
152
154
|
|
|
153
155
|
/**
|
|
@@ -176,6 +178,7 @@ export class AuditWriter {
|
|
|
176
178
|
return {
|
|
177
179
|
statements: changes.map((change) => this.db.prepare(change.sql).bind(...change.binds)),
|
|
178
180
|
rows: (results, offset = 0) => results[offset + last]?.results ?? [],
|
|
181
|
+
recordId: null,
|
|
179
182
|
}
|
|
180
183
|
}
|
|
181
184
|
const id = uuidv7()
|
|
@@ -188,7 +191,7 @@ export class AuditWriter {
|
|
|
188
191
|
INSERT INTO audit_events ${AUDIT_COLUMNS} SELECT ${AUDIT_PLACEHOLDERS} WHERE ${changed} RETURNING id
|
|
189
192
|
) SELECT * FROM c${changes.length - 1}`)
|
|
190
193
|
.bind(...changes.flatMap((change) => change.binds), ...values)
|
|
191
|
-
return { statements: [statement], rows: (results, offset = 0) => results[offset]?.results ?? [] }
|
|
194
|
+
return { statements: [statement], rows: (results, offset = 0) => results[offset]?.results ?? [], recordId: id }
|
|
192
195
|
}
|
|
193
196
|
const statements = changes.flatMap((change) => [
|
|
194
197
|
this.db.prepare(change.sql).bind(...change.binds),
|
|
@@ -198,7 +201,7 @@ export class AuditWriter {
|
|
|
198
201
|
.bind(...values, id),
|
|
199
202
|
])
|
|
200
203
|
const last = (changes.length - 1) * 2
|
|
201
|
-
return { statements, rows: (results, offset = 0) => results[offset + last]?.results ?? [] }
|
|
204
|
+
return { statements, rows: (results, offset = 0) => results[offset + last]?.results ?? [], recordId: id }
|
|
202
205
|
}
|
|
203
206
|
|
|
204
207
|
/** Run one audited group as its own batch and answer the rows its last change returned. */
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { type SqlDatabase, uuidv7 } from '@fabrika/platform'
|
|
2
|
+
import { type AuditEventInput, AuditWriter } from './audit'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One requested grant change at an application whose console grants wait for approval (ADR-0083). Nothing that resolves
|
|
6
|
+
* permissions reads it; `GrantRepository.applyRequest` writes the change when a person approves it.
|
|
7
|
+
*/
|
|
8
|
+
export interface GrantRequestRow {
|
|
9
|
+
id: string
|
|
10
|
+
app: string
|
|
11
|
+
kind: 'create' | 'update' | 'revoke'
|
|
12
|
+
principal_id: string
|
|
13
|
+
/** The grant an `update` edits or a `revoke` removes; null for `create`. */
|
|
14
|
+
grant_id: string | null
|
|
15
|
+
role_key: string | null
|
|
16
|
+
/** Inline action-pattern set (JSON array); XOR `role_key`. */
|
|
17
|
+
permissions: string | null
|
|
18
|
+
scope_type: string | null
|
|
19
|
+
scope_value: string | null
|
|
20
|
+
grant_expires_at: number | null
|
|
21
|
+
requested_by: string
|
|
22
|
+
requested_at: number
|
|
23
|
+
expires_at: number
|
|
24
|
+
status: 'pending' | 'approved' | 'rejected' | 'failed'
|
|
25
|
+
/** The approval that claimed it, which the change it wrote carries in its guard. */
|
|
26
|
+
decision_id: string | null
|
|
27
|
+
decided_by: string | null
|
|
28
|
+
decided_at: number | null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface CreateGrantRequestInput {
|
|
32
|
+
app: string
|
|
33
|
+
kind: GrantRequestRow['kind']
|
|
34
|
+
principalId: string
|
|
35
|
+
grantId: string | null
|
|
36
|
+
roleKey: string | null
|
|
37
|
+
permissions: string[] | null
|
|
38
|
+
scopeType: string | null
|
|
39
|
+
scopeValue: string | null
|
|
40
|
+
grantExpiresAt: number | null
|
|
41
|
+
requestedBy: string
|
|
42
|
+
requestedAt: number
|
|
43
|
+
expiresAt: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class GrantRequestRepository {
|
|
47
|
+
constructor(
|
|
48
|
+
private readonly db: SqlDatabase,
|
|
49
|
+
private readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
|
|
50
|
+
) {}
|
|
51
|
+
|
|
52
|
+
/** Whether a grant change at `app` waits for approval. */
|
|
53
|
+
async grantsWait(app: string): Promise<boolean> {
|
|
54
|
+
const row = await this.db.prepare('SELECT required FROM app_grant_approvals WHERE app = ?').bind(app).first<{ required: number }>()
|
|
55
|
+
return row?.required === 1
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Set whether grant changes at `app` wait, as of Control's protection `revision`. An older revision than the stored one
|
|
60
|
+
* changes nothing, so a caller that lost the environment's lease cannot undo its successor's gate. The record is written
|
|
61
|
+
* only when `required` changes.
|
|
62
|
+
*/
|
|
63
|
+
async setGrantsWait(
|
|
64
|
+
app: string,
|
|
65
|
+
required: boolean,
|
|
66
|
+
revision: number,
|
|
67
|
+
now: number,
|
|
68
|
+
audit: AuditEventInput,
|
|
69
|
+
): Promise<{ required: boolean; revision: number }> {
|
|
70
|
+
const current = this.db
|
|
71
|
+
.prepare(`INSERT INTO app_grant_approvals (app, required, revision, updated_at) VALUES (?, 0, ?, ?)
|
|
72
|
+
ON CONFLICT (app) DO UPDATE SET revision = excluded.revision, updated_at = excluded.updated_at
|
|
73
|
+
WHERE app_grant_approvals.revision <= excluded.revision`)
|
|
74
|
+
.bind(app, revision, now)
|
|
75
|
+
const change = this.writer.changed([{
|
|
76
|
+
sql: 'UPDATE app_grant_approvals SET required = ? WHERE app = ? AND revision = ? AND required <> ? RETURNING app',
|
|
77
|
+
binds: [required ? 1 : 0, app, revision, required ? 1 : 0],
|
|
78
|
+
}], audit)
|
|
79
|
+
const read = this.db.prepare('SELECT required, revision FROM app_grant_approvals WHERE app = ?').bind(app)
|
|
80
|
+
const results = await this.db.batch<{ required: number; revision: number }>([current, ...change.statements, read])
|
|
81
|
+
const [stored] = results[results.length - 1]?.results ?? []
|
|
82
|
+
if (stored === undefined) throw new Error('the grant gate row is missing after its upsert')
|
|
83
|
+
return { required: stored.required === 1, revision: stored.revision }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async create(input: CreateGrantRequestInput, audit: (requestId: string) => AuditEventInput): Promise<GrantRequestRow> {
|
|
87
|
+
const id = uuidv7()
|
|
88
|
+
const [created] = await this.writer.run<GrantRequestRow>([{
|
|
89
|
+
sql: `INSERT INTO grant_requests (id, app, kind, principal_id, grant_id, role_key, permissions, scope_type, scope_value,
|
|
90
|
+
grant_expires_at, requested_by, requested_at, expires_at)
|
|
91
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
|
|
92
|
+
binds: [
|
|
93
|
+
id,
|
|
94
|
+
input.app,
|
|
95
|
+
input.kind,
|
|
96
|
+
input.principalId,
|
|
97
|
+
input.grantId,
|
|
98
|
+
input.roleKey,
|
|
99
|
+
input.permissions === null ? null : JSON.stringify(input.permissions),
|
|
100
|
+
input.scopeType,
|
|
101
|
+
input.scopeValue,
|
|
102
|
+
input.grantExpiresAt,
|
|
103
|
+
input.requestedBy,
|
|
104
|
+
input.requestedAt,
|
|
105
|
+
input.expiresAt,
|
|
106
|
+
],
|
|
107
|
+
}], audit(id))
|
|
108
|
+
if (created === undefined) throw new Error('a grant request insert returned no row')
|
|
109
|
+
return created
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async get(id: string): Promise<GrantRequestRow | null> {
|
|
113
|
+
return await this.db.prepare('SELECT * FROM grant_requests WHERE id = ?').bind(id).first<GrantRequestRow>()
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Every request still open at `now`, the oldest first. */
|
|
117
|
+
async listOpen(now: number): Promise<GrantRequestRow[]> {
|
|
118
|
+
const { results } = await this.db
|
|
119
|
+
.prepare(`SELECT * FROM grant_requests WHERE status = 'pending' AND expires_at > ? ORDER BY requested_at, id`)
|
|
120
|
+
.bind(now)
|
|
121
|
+
.all<GrantRequestRow>()
|
|
122
|
+
return results
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Reject an open request; null when it was decided or lapsed meanwhile. */
|
|
126
|
+
async reject(id: string, decidedBy: string, now: number, audit: AuditEventInput): Promise<GrantRequestRow | null> {
|
|
127
|
+
const [rejected] = await this.writer.run<GrantRequestRow>([{
|
|
128
|
+
sql: `UPDATE grant_requests SET status = 'rejected', decision_id = ?, decided_by = ?, decided_at = ?
|
|
129
|
+
WHERE id = ? AND status = 'pending' AND expires_at > ? RETURNING *`,
|
|
130
|
+
binds: [uuidv7(), decidedBy, now, id, now],
|
|
131
|
+
}], audit)
|
|
132
|
+
return rejected ?? null
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
|
|
2
|
+
import { z } from 'zod'
|
|
2
3
|
import { type AuditEventInput, AuditWriter, type SqlChange, type SqlDialect } from './audit'
|
|
4
|
+
import type { GrantRequestRow } from './grant-requests'
|
|
3
5
|
import { unixNow } from './sql'
|
|
4
6
|
|
|
5
7
|
/** A grant written for a workload principal: its authority is its declared actions, never a grant. */
|
|
@@ -353,6 +355,102 @@ export class GrantRepository {
|
|
|
353
355
|
}
|
|
354
356
|
}
|
|
355
357
|
|
|
358
|
+
/**
|
|
359
|
+
* Write the change an approved grant request asks for (ADR-0083), in one transaction with the approval's claim: the
|
|
360
|
+
* request moves `pending` → `approved` under `decision.id`, and the change carries a guard on that claim, so of two
|
|
361
|
+
* approvals one claims and writes, the other writes nothing. `current` is the grant an `update` edits as the approver's
|
|
362
|
+
* checks read it; the edit applies only over it. `claimed` false: decided or lapsed meanwhile. `changed` null with
|
|
363
|
+
* `claimed`: the change wrote nothing (a role grant already held, an ineligible grant, a grant gone or edited since).
|
|
364
|
+
*/
|
|
365
|
+
async applyRequest(
|
|
366
|
+
request: GrantRequestRow,
|
|
367
|
+
current: GrantRow | null,
|
|
368
|
+
decision: { readonly id: string; readonly by: string; readonly at: number },
|
|
369
|
+
audit: (grantId: string) => AuditEventInput,
|
|
370
|
+
): Promise<{ claimed: boolean; changed: GrantRow | null }> {
|
|
371
|
+
const claim = this.db
|
|
372
|
+
.prepare(`UPDATE grant_requests SET status = 'approved', decision_id = ?, decided_by = ?, decided_at = ?
|
|
373
|
+
WHERE id = ? AND status = 'pending' AND expires_at > ? RETURNING id`)
|
|
374
|
+
.bind(decision.id, decision.by, decision.at, request.id, decision.at)
|
|
375
|
+
const guard = { sql: 'EXISTS (SELECT 1 FROM grant_requests WHERE id = ? AND decision_id = ?)', binds: [request.id, decision.id] }
|
|
376
|
+
const input: CreateGrantInput = {
|
|
377
|
+
principalId: request.principal_id,
|
|
378
|
+
app: request.app,
|
|
379
|
+
roleKey: request.role_key,
|
|
380
|
+
permissions: request.permissions === null ? null : storedActions(request.permissions),
|
|
381
|
+
scopeType: request.scope_type,
|
|
382
|
+
scopeValue: request.scope_value,
|
|
383
|
+
grantedBy: decision.by,
|
|
384
|
+
expiresAt: request.grant_expires_at,
|
|
385
|
+
}
|
|
386
|
+
let grantId = request.grant_id ?? uuidv7()
|
|
387
|
+
let change: SqlChange
|
|
388
|
+
const leading: SqlStatement[] = []
|
|
389
|
+
if (request.kind === 'create') {
|
|
390
|
+
let conflict = ''
|
|
391
|
+
const conflictBinds: number[] = []
|
|
392
|
+
if (input.roleKey !== null && input.scopeValue != null) {
|
|
393
|
+
conflict =
|
|
394
|
+
`ON CONFLICT (principal_id, role_key, scope_type, scope_value, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NOT NULL DO NOTHING`
|
|
395
|
+
} else if (input.roleKey !== null) {
|
|
396
|
+
// As `createDelegatedRoleGrant`: an expired grant of the role is renewed in place, keeping its id.
|
|
397
|
+
const expired = await this.db
|
|
398
|
+
.prepare(`SELECT id FROM grants WHERE principal_id = ? AND role_key = ? AND app = ? AND scope_value IS NULL
|
|
399
|
+
AND expires_at IS NOT NULL AND expires_at <= ?`)
|
|
400
|
+
.bind(request.principal_id, input.roleKey, request.app, decision.at)
|
|
401
|
+
.first<{ id: string }>()
|
|
402
|
+
grantId = expired?.id ?? grantId
|
|
403
|
+
conflict = `ON CONFLICT (principal_id, role_key, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NULL
|
|
404
|
+
DO UPDATE SET expires_at = excluded.expires_at, granted_by = excluded.granted_by, created_at = excluded.created_at
|
|
405
|
+
WHERE grants.expires_at IS NOT NULL AND grants.expires_at <= ?`
|
|
406
|
+
conflictBinds.push(decision.at)
|
|
407
|
+
}
|
|
408
|
+
const insert = this.grantChange(grantId, input, conflict, guard)
|
|
409
|
+
change = { sql: insert.sql, binds: [...insert.binds, ...conflictBinds] }
|
|
410
|
+
} else if (request.kind === 'update') {
|
|
411
|
+
if (current === null) return { claimed: false, changed: null }
|
|
412
|
+
leading.push(grantRemovalStatement(this.db, { principalId: request.principal_id }))
|
|
413
|
+
change = {
|
|
414
|
+
sql: `UPDATE grants SET role_key = ?, permissions = ?, scope_type = ?, scope_value = ?, expires_at = ?
|
|
415
|
+
WHERE id = ? AND app = ? AND role_key IS NOT DISTINCT FROM ? AND permissions IS NOT DISTINCT FROM ?
|
|
416
|
+
AND scope_type IS NOT DISTINCT FROM ? AND scope_value IS NOT DISTINCT FROM ? AND expires_at IS NOT DISTINCT FROM ?
|
|
417
|
+
AND ${eligibleGrantSql(this.writer.dialect)} AND ${guard.sql} RETURNING *`,
|
|
418
|
+
binds: [
|
|
419
|
+
input.roleKey ?? null,
|
|
420
|
+
request.permissions,
|
|
421
|
+
input.scopeType ?? null,
|
|
422
|
+
input.scopeValue ?? null,
|
|
423
|
+
input.expiresAt ?? null,
|
|
424
|
+
current.id,
|
|
425
|
+
request.app,
|
|
426
|
+
current.role_key,
|
|
427
|
+
current.permissions,
|
|
428
|
+
current.scope_type,
|
|
429
|
+
current.scope_value,
|
|
430
|
+
current.expires_at,
|
|
431
|
+
...eligibleGrantBinds(input),
|
|
432
|
+
...guard.binds,
|
|
433
|
+
],
|
|
434
|
+
}
|
|
435
|
+
} else {
|
|
436
|
+
leading.push(grantRemovalStatement(this.db, { principalId: request.principal_id }))
|
|
437
|
+
change = {
|
|
438
|
+
sql: `DELETE FROM grants WHERE id = ? AND app = ? AND principal_id = ? AND ${guard.sql} RETURNING *`,
|
|
439
|
+
binds: [grantId, request.app, request.principal_id, ...guard.binds],
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
leading.push(claim)
|
|
443
|
+
const audited = this.writer.changed([change], audit(grantId))
|
|
444
|
+
// A claim whose change wrote nothing (no record) closes the request `failed` in the same transaction.
|
|
445
|
+
const failed = this.db
|
|
446
|
+
.prepare(`UPDATE grant_requests SET status = 'failed' WHERE id = ? AND decision_id = ?
|
|
447
|
+
AND NOT EXISTS (SELECT 1 FROM audit_events WHERE id = ?)`)
|
|
448
|
+
.bind(request.id, decision.id, audited.recordId)
|
|
449
|
+
const results = await this.db.batch<GrantRow>([...leading, ...audited.statements, failed])
|
|
450
|
+
const claimed = (results[leading.length - 1]?.results.length ?? 0) > 0
|
|
451
|
+
return { claimed, changed: audited.rows(results, leading.length)[0] ?? null }
|
|
452
|
+
}
|
|
453
|
+
|
|
356
454
|
/** Keep the audit's before-value true if another administrator edited this grant after it was read. */
|
|
357
455
|
async updateGrant(grant: GrantRow, input: CreateGrantInput, audit: AuditEventInput): Promise<GrantRow | null> {
|
|
358
456
|
await this.refuseWorkload(grant.principal_id)
|
|
@@ -402,3 +500,10 @@ export class GrantRepository {
|
|
|
402
500
|
return { sql: 'DELETE FROM grants WHERE principal_id = ? RETURNING id', binds: [principalId] }
|
|
403
501
|
}
|
|
404
502
|
}
|
|
503
|
+
|
|
504
|
+
const storedActionsSchema = z.array(z.string())
|
|
505
|
+
|
|
506
|
+
/** A stored inline action set (a JSON array of patterns), read once where it leaves the row. */
|
|
507
|
+
function storedActions(json: string): string[] {
|
|
508
|
+
return storedActionsSchema.parse(JSON.parse(json))
|
|
509
|
+
}
|
package/src/tokens.ts
CHANGED
|
@@ -457,7 +457,7 @@ export async function resolveCredential(services: Services, cred: CredentialRow,
|
|
|
457
457
|
* A user's mailbox for its token: `principals.email`, normalized by `PrincipalRepository`, the address the person signs
|
|
458
458
|
* in with. An application mails it as `ctx.principal.email`, so it is never `label`, the spelling the person sees.
|
|
459
459
|
*/
|
|
460
|
-
function mailboxClaim(principal: PrincipalRow): { email?: string } {
|
|
460
|
+
export function mailboxClaim(principal: PrincipalRow): { email?: string } {
|
|
461
461
|
return principal.type === 'user' && principal.email !== null ? { email: principal.email } : {}
|
|
462
462
|
}
|
|
463
463
|
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type DecideGrantRequestInput, type GrantRequestDto, type ListGrantRequestsInput, type SetGrantApprovalRequest } from '@fabrika/iam-contract';
|
|
2
|
+
import { type AuditEventInput, type CreateGrantRequestInput } from '../db';
|
|
3
|
+
import type { Services } from '../services';
|
|
4
|
+
import { type AdminContext } from './context';
|
|
5
|
+
import type { ResolvedAdmin } from './router';
|
|
6
|
+
/** Whether a grant change at `app` waits; a cross-app grant reaches no application and never does. */
|
|
7
|
+
export declare function grantsWait(services: Services, app: string | null): Promise<boolean>;
|
|
8
|
+
/** What a grant change asks for, before IAM records it; the request's timestamps are IAM's. */
|
|
9
|
+
export type GrantChangeRequest = Omit<CreateGrantRequestInput, 'requestedAt' | 'expiresAt'>;
|
|
10
|
+
/** Record the change as a request, with its `iam.grant.request` record built by `event`, and answer it. */
|
|
11
|
+
export declare function requestGrantChange(services: Services, change: GrantChangeRequest, event: (requestId: string, metadata: Record<string, unknown>) => AuditEventInput): Promise<GrantRequestDto>;
|
|
12
|
+
/** The open requests at the applications the caller administers, the oldest first. */
|
|
13
|
+
export declare function listGrantRequestsUseCase(c: AdminContext, input: ListGrantRequestsInput): Promise<{
|
|
14
|
+
items: GrantRequestDto[];
|
|
15
|
+
}>;
|
|
16
|
+
/**
|
|
17
|
+
* Approve or reject one open request. Only a person in a signed-in session decides (`person`), never a `px_` key; an
|
|
18
|
+
* application the caller does not administer and an unknown request are one 404. The requester may reject (withdraw)
|
|
19
|
+
* their own request, never approve it.
|
|
20
|
+
*/
|
|
21
|
+
export declare function decideGrantRequestUseCase(c: AdminContext, person: boolean, input: DecideGrantRequestInput): Promise<GrantRequestDto>;
|
|
22
|
+
/** The caller of a grant request procedure who administers no IAM application: an application's own administrator. */
|
|
23
|
+
export interface GrantRequester {
|
|
24
|
+
readonly services: Services;
|
|
25
|
+
readonly requestId: string;
|
|
26
|
+
readonly admin: ResolvedAdmin;
|
|
27
|
+
}
|
|
28
|
+
/** A requester without IAM administration sees only the requests they made (an application administrator's own). */
|
|
29
|
+
export declare function listOwnGrantRequestsUseCase(c: GrantRequester, input: ListGrantRequestsInput): Promise<{
|
|
30
|
+
items: GrantRequestDto[];
|
|
31
|
+
}>;
|
|
32
|
+
/**
|
|
33
|
+
* A requester without IAM administration withdraws a request they made, as a person in a signed-in session; any other
|
|
34
|
+
* request, and approving, is the 404 of an unknown one. The record is filed under the request's application.
|
|
35
|
+
*/
|
|
36
|
+
export declare function withdrawOwnGrantRequestUseCase(c: GrantRequester, input: DecideGrantRequestInput): Promise<GrantRequestDto>;
|
|
37
|
+
/**
|
|
38
|
+
* Make grant changes at `app` wait, or apply at once again (ADR-0083 §4). Only Control sets it, with the provisioning
|
|
39
|
+
* key, when an environment chooses or drops the `grants` category: an installation administrator who could switch it
|
|
40
|
+
* off could grant past it. Only an application environment id qualifies.
|
|
41
|
+
*/
|
|
42
|
+
export declare function setGrantApprovalUseCase(c: AdminContext, input: SetGrantApprovalRequest): Promise<SetGrantApprovalRequest>;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { type CreateGrantRequest, type
|
|
1
|
+
import { type CreateGrantRequest, type GrantChangeResponse, type OkResponse, type PendingGrantChange, type UpdateGrantInput } from '@fabrika/iam-contract';
|
|
2
2
|
import { type AdminContext } from './context';
|
|
3
|
-
export declare function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<
|
|
3
|
+
export declare function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantChangeResponse>;
|
|
4
4
|
export declare function deleteGrantUseCase(c: AdminContext, input: {
|
|
5
5
|
id: string;
|
|
6
|
-
}): Promise<OkResponse
|
|
6
|
+
}): Promise<OkResponse & Partial<PendingGrantChange>>;
|
|
7
7
|
/** Edit a grant in place within its original application. Both paths use the same role, scope and external-person rules. */
|
|
8
|
-
export declare function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<
|
|
8
|
+
export declare function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantChangeResponse>;
|
package/types/src/db.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { AuditRepository, type SqlDialect } from './repositories/audit';
|
|
|
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';
|
|
@@ -21,6 +22,7 @@ export { type AuditedChange, type AuditEventInput, type AuditEventRow, auditEven
|
|
|
21
22
|
export { type InstallationBrandImages, InstallationBrandRepository, type InstallationBrandRow } from './repositories/brand';
|
|
22
23
|
export { type CredentialGrantRow, CredentialRepository, type CredentialRow } from './repositories/credentials';
|
|
23
24
|
export { DeviceAuthorizationRepository, type DeviceAuthorizationRow, type DeviceReceiptRow } from './repositories/device';
|
|
25
|
+
export { type CreateGrantRequestInput, GrantRequestRepository, type GrantRequestRow } from './repositories/grant-requests';
|
|
24
26
|
export { type DelegatedAuthority, ExternalGrantError, GrantRepository, type GrantRow } from './repositories/grants';
|
|
25
27
|
export { type AuthCodeRow, HandoffRepository } from './repositories/handoff';
|
|
26
28
|
export { type DelegationGrantRow, type InvitationAcceptance, type InvitationRow, type InviterCheck, type MemberGrantRow, MembershipRepository, type MembershipRepositoryOptions, type NewPrincipalAcceptance, type NewPrincipalEvents, } from './repositories/membership';
|
|
@@ -37,6 +39,7 @@ export interface IamRepositories {
|
|
|
37
39
|
device: DeviceAuthorizationRepository;
|
|
38
40
|
principals: PrincipalRepository;
|
|
39
41
|
grants: GrantRepository;
|
|
42
|
+
grantRequests: GrantRequestRepository;
|
|
40
43
|
appSchema: AppSchemaRepository;
|
|
41
44
|
credentials: CredentialRepository;
|
|
42
45
|
sessions: SessionRepository;
|
package/types/src/oauth.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type KeyGrant, type PermissionEntry } from '@fabrika/auth-core';
|
|
2
|
-
import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthAuthorizationRequest, type OAuthClientMetadataDocument, type OAuthResourceDto, type OAuthRevocationRequest, type OAuthTokenRequest, type OAuthTokenResponse } from '@fabrika/iam-contract';
|
|
2
|
+
import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthAuthorizationRequest, type OAuthClientMetadataDocument, type OAuthIdentityRole, type OAuthResourceDto, type OAuthRevocationRequest, type OAuthTokenRequest, type OAuthTokenResponse } from '@fabrika/iam-contract';
|
|
3
3
|
import { type AuditEventInput, type OAuthGrantRow, type PrincipalRow, type SessionRow } from './db';
|
|
4
4
|
import type { Env } from './env';
|
|
5
5
|
import type { ManagedOAuthClient, OAuthConfig } from './oauth-config';
|
|
@@ -61,16 +61,30 @@ export declare function exchangeOAuthToken(services: Services, env: SigningEnv,
|
|
|
61
61
|
export declare function revokeOAuthToken(services: Services, env: SigningEnv, input: OAuthRevocationRequest, requestId: string): Promise<void>;
|
|
62
62
|
/** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
|
|
63
63
|
export declare function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, resource: string, now: number): Promise<OAuthTokenResponse | null>;
|
|
64
|
+
/** What a grant's next token carries. `identity` is present on an identity resource's: its roles, when it declares them. */
|
|
65
|
+
export interface GrantAuthority {
|
|
66
|
+
principal: PrincipalRow;
|
|
67
|
+
scopes: string[];
|
|
68
|
+
permissions: PermissionEntry[];
|
|
69
|
+
expiresAt: number | null;
|
|
70
|
+
identity?: {
|
|
71
|
+
roles?: string[];
|
|
72
|
+
};
|
|
73
|
+
}
|
|
64
74
|
/**
|
|
65
75
|
* Everything a grant needs to still mean something, checked at every code exchange and refresh: the
|
|
66
76
|
* grant live, its client and resource still configured, the IAM session it was given under live and
|
|
67
77
|
* usable, the principal an active user. The permissions are resolved live, never from the consent.
|
|
68
78
|
*/
|
|
69
|
-
export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number, resourceUri?: string): Promise<
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
79
|
+
export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number, resourceUri?: string): Promise<GrantAuthority | null>;
|
|
80
|
+
/**
|
|
81
|
+
* The declared roles `principal` holds at an external application, in declared order, and when the earliest of them
|
|
82
|
+
* ends (null: none ends); null when it holds none. Only a global grant of a declared role counts, and only for an
|
|
83
|
+
* internal principal: an external one holds nothing but roles its application declares external (ADR-0051).
|
|
84
|
+
*/
|
|
85
|
+
export declare function heldIdentityRoles(services: Services, principal: PrincipalRow, app: string, declared: readonly OAuthIdentityRole[]): Promise<{
|
|
86
|
+
keys: string[];
|
|
87
|
+
until: number | null;
|
|
74
88
|
} | null>;
|
|
75
89
|
/** The union of the scopes' grants, or null when a scope is no longer configured. */
|
|
76
90
|
export declare function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null;
|
|
@@ -104,6 +104,8 @@ export interface AuditedChange {
|
|
|
104
104
|
readonly statements: SqlStatement[];
|
|
105
105
|
/** The rows the LAST change returned, read from the results of a batch whose statements start at `offset`. */
|
|
106
106
|
rows<T>(results: SqlQueryResult<T>[], offset?: number): T[];
|
|
107
|
+
/** The id of the record, which exists after the batch exactly when the change changed a row; null without a record. */
|
|
108
|
+
readonly recordId: string | null;
|
|
107
109
|
}
|
|
108
110
|
/**
|
|
109
111
|
* Writes the record of a guarded change exactly when the change changed a row, decided by the change itself and never
|