@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.
@@ -22,6 +22,7 @@ import { parseOAuthConfig } from '../oauth-config'
22
22
  import { parseOidcSessionSeconds } from '../oidc-session'
23
23
  import { BUN_PBKDF2_COST } from '../password-crypto'
24
24
  import { parseRetention } from '../retention'
25
+ import { parseAdminAudiences, platformAudiencesFor } from '../services'
25
26
 
26
27
  /** Config that exists ONLY off Workers — the process's own knobs, not part of the service's `Env`. */
27
28
  export interface ProcessConfig {
@@ -102,7 +103,7 @@ export async function createRuntime(source: Record<string, string | undefined> =
102
103
  const controlUrl = httpOrigin(source, 'FABRIKA_CONTROL_URL')
103
104
 
104
105
  // Parsed here as well as per request in `buildServices`, for the same readiness-probe reason as above.
105
- parseOAuthConfig(source['FABRIKA_IAM_OAUTH_CONFIG'])
106
+ parseOAuthConfig(source['FABRIKA_IAM_OAUTH_CONFIG'], platformAudiencesFor(parseAdminAudiences(source['FABRIKA_IAM_ADMIN_AUDIENCES'])))
106
107
  const authLogRetentionDays = source['FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS']
107
108
  const auditRetentionDays = source['FABRIKA_IAM_AUDIT_RETENTION_DAYS']
108
109
  parseRetention(
@@ -15,15 +15,16 @@ export interface OAuthConfig {
15
15
  const MAX_CLIENTS = 16
16
16
  const MAX_RESOURCES = 32
17
17
  const CONFIG_KEYS = ['clients', 'resources']
18
- const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl']
18
+ const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl', 'identity']
19
19
  const RESOURCE_KEYS = ['app', 'resource', 'defaultScopes', 'scopeGrants', 'client']
20
20
 
21
21
  /**
22
22
  * Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the boot instead of
23
23
  * quietly serving fewer clients or scopes than the operator wrote. Unknown keys are refused for the same reason.
24
- * `clients` may be empty: the command-line client is IAM's own and never listed.
24
+ * `clients` may be empty: the command-line client is IAM's own and never listed. A client's identity resource names
25
+ * neither a registered resource nor a `platformAudiences` app, so its token is never one an installation service accepts.
25
26
  */
26
- export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
27
+ export function parseOAuthConfig(raw: string | undefined, platformAudiences: ReadonlySet<string>): OAuthConfig | null {
27
28
  if (raw === undefined || raw.trim() === '') return null
28
29
  const value = parseJsonOrNull(raw)
29
30
  const rawClients = prop(value, 'clients')
@@ -55,6 +56,14 @@ export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
55
56
  }
56
57
  resources.push(resource)
57
58
  }
59
+ for (const [index, { identity }] of clients.entries()) {
60
+ if (
61
+ identity !== undefined
62
+ && (platformAudiences.has(identity.app) || resources.some((entry) => entry.resource === identity.resource || entry.app === identity.app))
63
+ ) {
64
+ throw new Error(`OAUTH_CONFIG.clients[${index}].identity names an installation service's app or resource`)
65
+ }
66
+ }
58
67
  return { clients, resources }
59
68
  }
60
69
 
@@ -1,4 +1,5 @@
1
1
  import { DEFAULT_LOCALE, narrowPermissions, type PermissionEntry } from '@fabrika/auth-core'
2
+ import { CONTROL_APP_ID, CONTROL_CLI_RESOURCES } from '@fabrika/control-contract'
2
3
  import { isOAuthDeviceGrantLifetime, OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS, type OAuthResourceDto } from '@fabrika/iam-contract'
3
4
  import { sessionEndsAt } from './auth'
4
5
  import { readForm, redirectHeaders, sameOrigin } from './auth/http'
@@ -115,7 +116,7 @@ async function consentPage(
115
116
  const authority = await resolveAuthorityAt(services, principal, attempt.app)
116
117
  const sections = resources.map((resource) => {
117
118
  const permissions = narrowPermissions(authority.permissions, scopeCeiling(resource, request.scopes) ?? [])
118
- return `<h2><code>${escapeHtml(resource.resource)}</code></h2>${permissionList(permissions)}`
119
+ return `<h2>${escapeHtml(resourceLabel(resource))}</h2><p class="uri">${escapeHtml(resource.resource)}</p>${permissionList(permissions)}`
119
120
  })
120
121
  const unbounded = request.scopes.filter((token) => resources.some((resource) => isUnbounded(resource, token)))
121
122
  const warning = unbounded.length === 0
@@ -124,7 +125,7 @@ async function consentPage(
124
125
  unbounded.map((token) => `<code>${escapeHtml(token)}</code>`).join(', ')
125
126
  } is not limited to one scope value: it holds its actions everywhere you hold them.</p>`
126
127
  const lifetimes = OAUTH_DEVICE_GRANT_LIFETIMES_SECONDS.map((seconds, index) =>
127
- `<label><input type="radio" name="lifetime" value="${seconds}"${index === 0 ? ' checked' : ''}> ${LIFETIME_LABELS[seconds]}</label>`
128
+ `<label class="choice"><input type="radio" name="lifetime" value="${seconds}"${index === 0 ? ' checked' : ''}> ${LIFETIME_LABELS[seconds]}</label>`
128
129
  )
129
130
  return page(
130
131
  services,
@@ -134,7 +135,7 @@ async function consentPage(
134
135
  <p>A device asks to act as you in <strong>${escapeHtml(attempt.app)}</strong>. It started this request at
135
136
  <strong>${new Date(attempt.created_at * 1000).toISOString()}</strong> with the code <code>${escapeHtml(formatUserCode(userCode))}</code>.
136
137
  Allow it only if you started it yourself.</p>
137
- <p>Scopes: <code>${escapeHtml(request.scopes.join(' '))}</code></p>
138
+ <p>Scopes: ${request.scopes.map((token) => `<code>${escapeHtml(token)}</code>`).join(' ')}</p>
138
139
  ${warning}
139
140
  <p>At most these permissions, and only while you hold them yourself:</p>
140
141
  ${sections.join('')}
@@ -142,11 +143,21 @@ async function consentPage(
142
143
  <input type="hidden" name="user_code" value="${escapeHtml(formatUserCode(userCode))}">
143
144
  <fieldset><legend>Access lasts</legend>${lifetimes.join('')}</fieldset>
144
145
  <p>Access also ends when this sign-in ends or when it is revoked.</p>
145
- <button name="decision" value="approve">Allow</button>
146
- <button name="decision" value="deny">Deny</button></form>`,
146
+ <div class="actions"><button name="decision" value="approve">Allow</button>
147
+ <button name="decision" value="deny">Deny</button></div></form>`,
147
148
  )
148
149
  }
149
150
 
151
+ /**
152
+ * What a person reads a resource as: the name the console gives its command-line resource (the device grant serves
153
+ * only those), else the resource's path, which tells two resources of one app apart. The full URI stays under it.
154
+ */
155
+ function resourceLabel(resource: OAuthResourceDto): string {
156
+ const path = new URL(resource.resource).pathname
157
+ const known = resource.app === CONTROL_APP_ID ? CONTROL_CLI_RESOURCES.find((entry) => entry.path === path) : undefined
158
+ return known?.label ?? path
159
+ }
160
+
150
161
  /** A scope whose actions no parameter narrows and at least one of which names no scope of its own. */
151
162
  function isUnbounded(resource: OAuthResourceDto, token: string): boolean {
152
163
  const grant = resource.scopeGrants.find((entry) => entry.scope === token)
@@ -157,9 +168,9 @@ function permissionList(permissions: readonly PermissionEntry[]): string {
157
168
  if (permissions.length === 0) return '<p>None: you hold none of these permissions yourself.</p>'
158
169
  const items = permissions.map((permission) => {
159
170
  const scope = permission.scope == null ? 'everywhere' : `${permission.scope.type} ${permission.scope.value}`
160
- return `<li><code>${escapeHtml(permission.action)}</code> — ${escapeHtml(scope)}</li>`
171
+ return `<li><code>${escapeHtml(permission.action)}</code> <span>${escapeHtml(scope)}</span></li>`
161
172
  })
162
- return `<ul>${items.join('')}</ul>`
173
+ return `<ul class="rows">${items.join('')}</ul>`
163
174
  }
164
175
 
165
176
  async function page(services: Services, title: string, content: string, status = 200): Promise<Response> {
package/src/oauth-http.ts CHANGED
@@ -1,26 +1,37 @@
1
- import { DEFAULT_LOCALE } from '@fabrika/auth-core'
1
+ import { DEFAULT_LOCALE, type KeyGrant } from '@fabrika/auth-core'
2
2
  import {
3
3
  OAUTH_CLIENT_ASSERTION_ALGORITHMS,
4
4
  OAUTH_DEVICE_CODE_GRANT_TYPE,
5
5
  type OAuthAuthorizationRequest,
6
6
  type OAuthAuthorizationServerMetadata,
7
7
  type OAuthClientCredential,
8
- type OAuthResourceDto,
8
+ type OAuthIdentityResource,
9
9
  parseOAuthAuthorizationAttempt,
10
10
  parseOAuthClientCredential,
11
11
  parseOAuthDeviceAuthorizationRequest,
12
12
  parseOAuthRevocationRequest,
13
13
  parseOAuthTokenRequest,
14
14
  resolveOAuthAuthorizationScopes,
15
+ resolveOAuthIdentityScopes,
15
16
  } from '@fabrika/iam-contract'
16
17
  import { decodeJwt } from 'jose'
17
18
  import { readForm, redirectHeaders, sameOrigin } from './auth/http'
18
19
  import { currentSession } from './auth/sessions'
19
- import { principalStatus } from './db'
20
+ import { type PrincipalRow, principalStatus } from './db'
20
21
  import type { Env } from './env'
21
22
  import { escapeHtml } from './html'
22
23
  import { installationBrand } from './installation-brand'
23
- import { establishClient, exchangeOAuthToken, grantAuthorization, type ManagedClient, revokeOAuthToken, scopeCeiling, servesClient } from './oauth'
24
+ import {
25
+ type AuthorizationTarget,
26
+ establishClient,
27
+ exchangeOAuthToken,
28
+ grantAuthorization,
29
+ heldIdentityRoles,
30
+ type ManagedClient,
31
+ revokeOAuthToken,
32
+ scopeCeiling,
33
+ servesClient,
34
+ } from './oauth'
24
35
  import { authenticateOAuthClient, authenticateRevokingClient } from './oauth-client-auth'
25
36
  import type { OAuthConfig } from './oauth-config'
26
37
  import { OAUTH_DEVICE_PATH, redeemDeviceCode, startDeviceAuthorization } from './oauth-device'
@@ -95,7 +106,7 @@ function authorizationServerMetadata(issuer: string): Response {
95
106
  type AuthorizationCheck =
96
107
  | { kind: 'refused'; message: string }
97
108
  | { kind: 'redirect'; response: Response }
98
- | { kind: 'valid'; request: OAuthAuthorizationRequest; client: ManagedClient; resource: OAuthResourceDto; scopes: string[] }
109
+ | { kind: 'valid'; request: OAuthAuthorizationRequest; client: ManagedClient; resource: AuthorizationTarget; scopes: string[]; ceiling: KeyGrant[] }
99
110
 
100
111
  /**
101
112
  * Validate an authorization request in the order RFC 6749 §4.1.2.1 requires: until the client and its
@@ -108,12 +119,38 @@ async function checkAuthorization(issuer: string, config: OAuthConfig, input: Re
108
119
  const client = await establishClient(config, coordinates.client_id, coordinates.redirect_uri)
109
120
  if (client === null) return { kind: 'refused', message: 'The client or its redirect URI is not registered.' }
110
121
  if (attempt.kind === 'invalid_scope') return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
122
+ const identity = client.registration.identity
123
+ if (identity !== undefined) return checkIdentityAuthorization(issuer, attempt.request, client, identity)
111
124
  // The command-line client's resources are served through the device grant only, never to a managed client.
112
125
  const resource = config.resources.find((entry) => entry.resource === coordinates.resource && servesClient(entry, false))
113
126
  if (resource === undefined) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_target' }) }
114
127
  const scopes = resolveOAuthAuthorizationScopes(attempt.request.scope, resource)
115
- if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
116
- return { kind: 'valid', request: attempt.request, client, resource, scopes }
128
+ const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
129
+ if (scopes === null || ceiling === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
130
+ return { kind: 'valid', request: attempt.request, client, resource, scopes, ceiling }
131
+ }
132
+
133
+ /** An identity-only client is served its own resource alone, with the `identity` scope and no permission. */
134
+ function checkIdentityAuthorization(
135
+ issuer: string,
136
+ request: OAuthAuthorizationRequest,
137
+ client: ManagedClient,
138
+ identity: OAuthIdentityResource,
139
+ ): AuthorizationCheck {
140
+ if (request.resource !== identity.resource) return { kind: 'redirect', response: clientRedirect(issuer, request, { error: 'invalid_target' }) }
141
+ const scopes = resolveOAuthIdentityScopes(request.scope)
142
+ if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, request, { error: 'invalid_scope' }) }
143
+ return { kind: 'valid', request, client, resource: identity, scopes, ceiling: [] }
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
117
154
  }
118
155
 
119
156
  async function showConsent(request: Request, services: Services, config: OAuthConfig): Promise<Response> {
@@ -130,6 +167,9 @@ async function showConsent(request: Request, services: Services, config: OAuthCo
130
167
  if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') {
131
168
  return errorPage(services, 'This account cannot authorize applications.', 403)
132
169
  }
170
+ if (await refusedByIdentityRoles(services, check, principal)) {
171
+ return clientRedirect(services.config.issuer, check.request, { error: 'access_denied' })
172
+ }
133
173
  return consentPage(services, check, principal.label)
134
174
  }
135
175
 
@@ -146,6 +186,10 @@ async function decideConsent(request: Request, services: Services, config: OAuth
146
186
  if (decision !== 'approve') return errorPage(services, 'The consent decision is missing.', 400)
147
187
  const session = await currentSession(request, services)
148
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
+ }
149
193
  const code = await grantAuthorization(services, { request: check.request, resource: check.resource, scopes: check.scopes, session, requestId })
150
194
  return clientRedirect(issuer, check.request, { code })
151
195
  }
@@ -228,12 +272,21 @@ function withAssertedClientId(fields: Record<string, string> | null, credential:
228
272
  }
229
273
 
230
274
  async function consentPage(services: Services, check: Extract<AuthorizationCheck, { kind: 'valid' }>, signedInAs: string): Promise<Response> {
231
- const { request, client, resource, scopes } = check
275
+ const { request, client, resource, scopes, ceiling } = check
232
276
  const clientName = client.metadata.client_name ?? client.registration.clientId
233
- const permissions = (scopeCeiling(resource, scopes) ?? []).map((permission) => {
277
+ const permissions = ceiling.map((permission) => {
234
278
  const scope = permission.scope == null ? 'everywhere' : `${permission.scope.type} ${permission.scope.value}`
235
279
  return `<li><code>${escapeHtml(permission.action)}</code> — ${escapeHtml(scope)}</li>`
236
280
  })
281
+ const asks = client.registration.identity === undefined
282
+ ? `<p><strong>${escapeHtml(clientName)}</strong> asks to act as you in <strong>${escapeHtml(resource.app)}</strong>.</p>`
283
+ : `<p><strong>${escapeHtml(clientName)}</strong> asks to know who you are. It receives who you are${
284
+ client.registration.identity.roles === undefined ? '' : ` and the roles you hold in <strong>${escapeHtml(resource.app)}</strong>`
285
+ }, and no permission.</p>`
286
+ const grants = client.registration.identity === undefined
287
+ ? `<p>At most these permissions, and only those you hold yourself:</p>
288
+ <ul>${permissions.join('')}</ul>`
289
+ : ''
237
290
  const fields: [string, string | undefined][] = [
238
291
  ['response_type', request.response_type],
239
292
  ['client_id', request.client_id],
@@ -251,12 +304,11 @@ async function consentPage(services: Services, check: Extract<AuthorizationCheck
251
304
  title: 'Authorize application',
252
305
  content: `<h1>Authorize ${escapeHtml(clientName)}</h1>
253
306
  <p>Signed in as <strong>${escapeHtml(signedInAs)}</strong>.</p>
254
- <p><strong>${escapeHtml(clientName)}</strong> asks to act as you in <strong>${escapeHtml(resource.app)}</strong>.</p>
307
+ ${asks}
255
308
  <p>Client: <code>${escapeHtml(client.registration.clientId)}</code></p>
256
309
  <p>Resource: <code>${escapeHtml(resource.resource)}</code></p>
257
310
  <p>Scopes: <code>${escapeHtml(scopes.join(' '))}</code></p>
258
- <p>At most these permissions, and only those you hold yourself:</p>
259
- <ul>${permissions.join('')}</ul>
311
+ ${grants}
260
312
  <p>Access ends when this sign-in ends or when it is revoked.</p>
261
313
  <form method="post" action="${AUTHORIZE_PATH}">${hidden.join('')}
262
314
  <button name="decision" value="approve">Allow</button>
package/src/oauth.ts CHANGED
@@ -9,8 +9,10 @@ import {
9
9
  } from '@fabrika/auth-core'
10
10
  import {
11
11
  OAUTH_DEVICE_CODE_GRANT_TYPE,
12
+ OAUTH_IDENTITY_SCOPE,
12
13
  type OAuthAuthorizationRequest,
13
14
  type OAuthClientMetadataDocument,
15
+ type OAuthIdentityRole,
14
16
  type OAuthResourceDto,
15
17
  type OAuthRevocationRequest,
16
18
  type OAuthTokenRequest,
@@ -30,7 +32,7 @@ import { authorityDeadline, resolveAuthorityAt } from './resolve'
30
32
  import { generateToken, hashToken, timingSafeEqualHex } from './secret'
31
33
  import type { Services } from './services'
32
34
  import { getSigner, verifyResourceAccessToken } from './signing'
33
- import { boundedToken } from './tokens'
35
+ import { boundedToken, mailboxClaim } from './tokens'
34
36
 
35
37
  /** An authorization code is redeemed by the client's back end within seconds of the redirect. */
36
38
  export const OAUTH_CODE_TTL_SECONDS = 60
@@ -82,10 +84,13 @@ export async function establishClient(config: OAuthConfig, clientId: string, red
82
84
  return { kind: 'managed', registration, metadata }
83
85
  }
84
86
 
87
+ /** What a consent grants: a registered resource, or an identity-only client's own resource. */
88
+ export type AuthorizationTarget = Pick<OAuthResourceDto, 'app' | 'resource'>
89
+
85
90
  /** Record the consent and return the plaintext authorization code — the only time it exists. */
86
91
  export async function grantAuthorization(
87
92
  services: Services,
88
- input: { request: OAuthAuthorizationRequest; resource: OAuthResourceDto; scopes: string[]; session: SessionRow; requestId: string },
93
+ input: { request: OAuthAuthorizationRequest; resource: AuthorizationTarget; scopes: string[]; session: SessionRow; requestId: string },
89
94
  ): Promise<string> {
90
95
  const now = unixNow()
91
96
  const code = generateToken()
@@ -270,6 +275,7 @@ export async function mintForGrant(
270
275
  scopes: authority.scopes,
271
276
  grantId: grant.id,
272
277
  tokenId: uuidv7(),
278
+ ...(authority.identity === undefined ? {} : { ...mailboxClaim(authority.principal), ...authority.identity }),
273
279
  })
274
280
  const token = await boundedToken((await getSigner(env)).signResourceToken(claims), { app: grant.app, subject: authority.principal.id })
275
281
  if (token === null) return null
@@ -281,6 +287,15 @@ export async function mintForGrant(
281
287
  }
282
288
  }
283
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
+
284
299
  /**
285
300
  * Everything a grant needs to still mean something, checked at every code exchange and refresh: the
286
301
  * grant live, its client and resource still configured, the IAM session it was given under live and
@@ -291,16 +306,11 @@ export async function grantAuthority(
291
306
  grant: OAuthGrantRow,
292
307
  now: number,
293
308
  resourceUri: string = grant.resource,
294
- ): Promise<{ principal: PrincipalRow; scopes: string[]; permissions: PermissionEntry[]; expiresAt: number | null } | null> {
309
+ ): Promise<GrantAuthority | null> {
295
310
  const config = services.config.oauth
296
311
  if (config === null || grant.revoked_at !== null || grant.expires_at <= now || !grantResources(grant).includes(resourceUri)) return null
297
- const resource = config.resources.find((entry) =>
298
- entry.resource === resourceUri && entry.app === grant.app && servesClient(entry, grant.client_id === OAUTH_CLI_CLIENT_ID)
299
- )
300
- const clientKnown = grant.client_id === OAUTH_CLI_CLIENT_ID || config.clients.some((client) => client.clientId === grant.client_id)
301
- if (resource === undefined || !clientKnown) return null
302
312
  const scopes = parseOAuthScopes(parseJsonOrNull(grant.scopes))
303
- const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
313
+ const ceiling = scopes === null ? null : grantCeiling(config, grant, resourceUri, scopes)
304
314
  if (scopes === null || ceiling === null) return null
305
315
  const session = await services.repositories.sessions.getActiveSessionById(grant.session_id)
306
316
  if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config, now)) {
@@ -308,13 +318,78 @@ export async function grantAuthority(
308
318
  }
309
319
  const principal = await services.repositories.principals.getPrincipalById(grant.principal_id)
310
320
  if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return null
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
+ }
311
331
  const live = await resolveAuthorityAt(services, principal, grant.app)
312
- const permissions = narrowPermissions(live.permissions, ceiling)
332
+ const permissions = narrowPermissions(live.permissions, ceiling.permissions)
313
333
  // A refreshed token ends with its login too: an OIDC login issued before the cap stores a later expiry than its end.
314
334
  const expiresAt = Math.min(authorityDeadline(live, permissions, now) ?? Number.POSITIVE_INFINITY, sessionEndsAt(session, services.config))
315
335
  return { principal, scopes, permissions, expiresAt }
316
336
  }
317
337
 
338
+ /**
339
+ * What a grant's token may carry at `resourceUri` under the current configuration, or null when its client or resource
340
+ * is no longer configured for it. An identity-only client is served its own resource alone, so a grant it holds for
341
+ * any other one (given before it was bound) mints nothing, and a grant for an identity resource carries no permission.
342
+ */
343
+ function grantCeiling(
344
+ config: OAuthConfig,
345
+ grant: OAuthGrantRow,
346
+ resourceUri: string,
347
+ scopes: readonly string[],
348
+ ): { kind: 'identity'; roles: readonly OAuthIdentityRole[] | undefined } | { kind: 'scoped'; permissions: KeyGrant[] } | null {
349
+ const cli = grant.client_id === OAUTH_CLI_CLIENT_ID
350
+ const client = config.clients.find((entry) => entry.clientId === grant.client_id)
351
+ if (!cli && client === undefined) return null
352
+ const identity = client?.identity
353
+ if (identity !== undefined) {
354
+ const matches = identity.resource === resourceUri && identity.app === grant.app && sameScopes(scopes, [OAUTH_IDENTITY_SCOPE])
355
+ return matches ? { kind: 'identity', roles: identity.roles } : null
356
+ }
357
+ const resource = config.resources.find((entry) => entry.resource === resourceUri && entry.app === grant.app && servesClient(entry, cli))
358
+ const permissions = resource === undefined ? null : scopeCeiling(resource, scopes)
359
+ return permissions === null ? null : { kind: 'scoped', permissions }
360
+ }
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
+
389
+ function sameScopes(scopes: readonly string[], expected: readonly string[]): boolean {
390
+ return scopes.length === expected.length && scopes.every((scope, index) => scope === expected[index])
391
+ }
392
+
318
393
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
319
394
  export function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null {
320
395
  const ceiling: KeyGrant[] = []
@@ -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
+ }