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

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,265 @@
1
+ import { OAUTH_CLI_CLIENT_ID, parseOAuthScopes } from '@fabrika/auth-core'
2
+ import {
3
+ OAUTH_DEVICE_CODE_GRANT_TYPE,
4
+ type OAuthDeviceAuthorizationRequest,
5
+ type OAuthDeviceAuthorizationResponse,
6
+ type OAuthResourceDto,
7
+ type OAuthTokenRequest,
8
+ resolveOAuthScopeToken,
9
+ } from '@fabrika/iam-contract'
10
+ import { uuidv7 } from '@fabrika/platform'
11
+ import type { Env } from './env'
12
+ import { parseJsonOrNull } from './json'
13
+ import {
14
+ type EstablishedClient,
15
+ grantAuthority,
16
+ grantRevocation,
17
+ mintForGrant,
18
+ type OAuthTokenOutcome,
19
+ servesClient,
20
+ storedResourceList,
21
+ } from './oauth'
22
+ import type { OAuthConfig } from './oauth-config'
23
+ import type { OAuthDeviceAuthorizationRow, OAuthGrantRow } from './repositories/oauth'
24
+ import { unixNow } from './repositories/sql'
25
+ import { generateToken, hashToken } from './secret'
26
+ import type { Services } from './services'
27
+
28
+ type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
29
+
30
+ export const OAUTH_DEVICE_PATH = '/oauth/device'
31
+ /** RFC 8628 §3.2 `expires_in`: a person has five minutes to enter the code and decide. */
32
+ export const OAUTH_DEVICE_ATTEMPT_TTL_SECONDS = 300
33
+ export const OAUTH_DEVICE_POLL_INTERVAL_SECONDS = 5
34
+
35
+ /** RFC 8628 §6.1: twenty consonants, eight of them (about 34 bits), typed without ambiguity. */
36
+ const USER_CODE_ALPHABET = 'BCDFGHJKLMNPQRSTVWXZ'
37
+ const USER_CODE_LENGTH = 8
38
+
39
+ const START_WINDOW_SECONDS = 600
40
+ /** Starts per client address in a window, only where the composition names one (`client-address.ts`). */
41
+ const STARTS_PER_ADDRESS = 30
42
+ /**
43
+ * Starts per client in a window. With one device client it is installation-wide, and on a composition that names no
44
+ * client address it is the only bound, so it bounds the attempt rows a flood writes (each expires in five minutes)
45
+ * rather than a person: keeping it full takes a sustained flood, and a full bucket refuses for one minute only.
46
+ */
47
+ const STARTS_PER_CLIENT = 10_000
48
+ const CLIENT_BLOCK_SECONDS = 60
49
+
50
+ /**
51
+ * RFC 8628 §5.1: code entries a signed-in person may make in a window, right or wrong, counted before the lookup so a
52
+ * burst cannot test more codes than this. Looking a code up and deciding it are two entries.
53
+ */
54
+ const CODE_ENTRY_WINDOW_SECONDS = 600
55
+ const CODE_ENTRIES_PER_PRINCIPAL = 20
56
+
57
+ export type DeviceStartOutcome =
58
+ | { ok: true; body: OAuthDeviceAuthorizationResponse }
59
+ | { ok: false; error: 'unauthorized_client' | 'invalid_target' | 'invalid_scope' | 'temporarily_unavailable' }
60
+
61
+ /** The user code as a person types it: upper case, without the separator or spaces. Null when it cannot be one. */
62
+ export function normalizeUserCode(raw: string): string | null {
63
+ if (raw.length > 32) return null
64
+ const code = raw.toUpperCase().replaceAll(/[\s-]/g, '')
65
+ return code.length === USER_CODE_LENGTH && [...code].every((letter) => USER_CODE_ALPHABET.includes(letter)) ? code : null
66
+ }
67
+
68
+ export function formatUserCode(code: string): string {
69
+ return `${code.slice(0, 4)}-${code.slice(4)}`
70
+ }
71
+
72
+ function generateUserCode(): string {
73
+ let code = ''
74
+ while (code.length < USER_CODE_LENGTH) {
75
+ for (const byte of crypto.getRandomValues(new Uint8Array(USER_CODE_LENGTH))) {
76
+ // 240 is the largest multiple of 20 below 256, so every letter is equally likely.
77
+ if (byte < 240 && code.length < USER_CODE_LENGTH) code += USER_CODE_ALPHABET.charAt(byte % USER_CODE_ALPHABET.length)
78
+ }
79
+ }
80
+ return code
81
+ }
82
+
83
+ export function userCodeHash(code: string): Promise<string> {
84
+ return hashToken(`oauth-device-user-code:${code}`)
85
+ }
86
+
87
+ /**
88
+ * Count one use of the bucket `key`, which admits `allowed` uses per window, and answer whether it is spent. Decided from
89
+ * the counting statement's own `RETURNING`, so a concurrent burst cannot pass it.
90
+ */
91
+ async function spentBucket(services: Services, key: string, allowed: number, blockSeconds: number): Promise<boolean> {
92
+ const throttle = await services.repositories.passwords.recordLoginFailure({
93
+ loginKeyHash: await hashToken(key),
94
+ windowSeconds: START_WINDOW_SECONDS,
95
+ // The row blocks on the use that reaches `maxAttempts`, so the allowed uses are one fewer.
96
+ maxAttempts: allowed + 1,
97
+ blockSeconds,
98
+ })
99
+ return throttle.blocked_until !== null && throttle.blocked_until > unixNow()
100
+ }
101
+
102
+ /** The resources a device request names, when the server serves every one of them for one app. */
103
+ function requestedResources(config: OAuthConfig, uris: readonly string[]): OAuthResourceDto[] | null {
104
+ const resources: OAuthResourceDto[] = []
105
+ for (const uri of uris) {
106
+ const resource = config.resources.find((entry) => entry.resource === uri && servesClient(entry, true))
107
+ const first = resources[0]
108
+ if (resource === undefined || (first !== undefined && resource.app !== first.app)) return null
109
+ resources.push(resource)
110
+ }
111
+ return resources
112
+ }
113
+
114
+ /** RFC 8628 §3.1–3.2: record an attempt for the CLI client and answer its codes. */
115
+ export async function startDeviceAuthorization(
116
+ services: Services,
117
+ config: OAuthConfig,
118
+ request: OAuthDeviceAuthorizationRequest,
119
+ clientAddress: string | null,
120
+ ): Promise<DeviceStartOutcome> {
121
+ if (request.client_id !== OAUTH_CLI_CLIENT_ID) return { ok: false, error: 'unauthorized_client' }
122
+ const resources = requestedResources(config, request.resources)
123
+ const app = resources?.[0]?.app
124
+ if (resources === null || app === undefined) return { ok: false, error: 'invalid_target' }
125
+ if (!resources.every((resource) => request.scope.every((token) => resolveOAuthScopeToken(token, resource) !== null))) {
126
+ return { ok: false, error: 'invalid_scope' }
127
+ }
128
+ // The address bucket first: a start it refuses must not count against the bucket every other client shares.
129
+ if (clientAddress !== null && await spentBucket(services, `oauth-device-start:address:${clientAddress}`, STARTS_PER_ADDRESS, START_WINDOW_SECONDS)) {
130
+ return { ok: false, error: 'temporarily_unavailable' }
131
+ }
132
+ if (await spentBucket(services, `oauth-device-start:client:${request.client_id}`, STARTS_PER_CLIENT, CLIENT_BLOCK_SECONDS)) {
133
+ return { ok: false, error: 'temporarily_unavailable' }
134
+ }
135
+ const now = unixNow()
136
+ // A collision of either code with a live attempt is improbable; drawing again settles it.
137
+ for (let attempt = 0; attempt < 3; attempt++) {
138
+ const deviceCode = generateToken()
139
+ const userCode = generateUserCode()
140
+ const started = await services.repositories.oauth.startDeviceAuthorization({
141
+ device_code_hash: await hashToken(deviceCode),
142
+ user_code_hash: await userCodeHash(userCode),
143
+ client_id: request.client_id,
144
+ app,
145
+ resources: JSON.stringify(request.resources),
146
+ scopes: JSON.stringify(request.scope),
147
+ interval_seconds: OAUTH_DEVICE_POLL_INTERVAL_SECONDS,
148
+ created_at: now,
149
+ expires_at: now + OAUTH_DEVICE_ATTEMPT_TTL_SECONDS,
150
+ })
151
+ if (!started) continue
152
+ const verificationUri = `${services.config.issuer}${OAUTH_DEVICE_PATH}`
153
+ return {
154
+ ok: true,
155
+ body: {
156
+ device_code: deviceCode,
157
+ user_code: formatUserCode(userCode),
158
+ verification_uri: verificationUri,
159
+ verification_uri_complete: `${verificationUri}?${new URLSearchParams({ user_code: formatUserCode(userCode) })}`,
160
+ expires_in: OAUTH_DEVICE_ATTEMPT_TTL_SECONDS,
161
+ interval: OAUTH_DEVICE_POLL_INTERVAL_SECONDS,
162
+ },
163
+ }
164
+ }
165
+ throw new Error('could not draw unused device codes')
166
+ }
167
+
168
+ export type CodeEntry =
169
+ | { kind: 'found'; attempt: OAuthDeviceAuthorizationRow; userCode: string }
170
+ | { kind: 'unknown' }
171
+ | { kind: 'throttled' }
172
+
173
+ /**
174
+ * The pending attempt a signed-in person's code names. Every entry counts against that person before the lookup, and
175
+ * once the budget is spent even a right code is refused until the block ends (RFC 8628 §5.1).
176
+ */
177
+ export async function enterUserCode(services: Services, principalId: string, raw: string): Promise<CodeEntry> {
178
+ const throttle = await services.repositories.passwords.recordLoginFailure({
179
+ loginKeyHash: await hashToken(`oauth-device-code:principal:${principalId}`),
180
+ windowSeconds: CODE_ENTRY_WINDOW_SECONDS,
181
+ maxAttempts: CODE_ENTRIES_PER_PRINCIPAL + 1,
182
+ blockSeconds: CODE_ENTRY_WINDOW_SECONDS,
183
+ })
184
+ const now = unixNow()
185
+ if (throttle.blocked_until !== null && throttle.blocked_until > now) return { kind: 'throttled' }
186
+ const userCode = normalizeUserCode(raw)
187
+ const attempt = userCode === null ? null : await services.repositories.oauth.pendingDeviceAuthorization(await userCodeHash(userCode), now)
188
+ return attempt !== null && userCode !== null ? { kind: 'found', attempt, userCode } : { kind: 'unknown' }
189
+ }
190
+
191
+ /** The attempt's stored scope tokens and resources, or null when either does not parse. */
192
+ export function attemptRequest(attempt: OAuthDeviceAuthorizationRow): { scopes: string[]; resources: string[] } | null {
193
+ const scopes = parseOAuthScopes(parseJsonOrNull(attempt.scopes))
194
+ const resources = storedResourceList(attempt.resources)
195
+ return scopes === null || resources === null ? null : { scopes, resources }
196
+ }
197
+
198
+ /**
199
+ * RFC 8628 §3.4–3.5: one poll of the token endpoint. An approved attempt is spent for a new grant, bound to the IAM
200
+ * session it was approved under, and answers a token for the requested resource and the grant's first refresh token.
201
+ */
202
+ export async function redeemDeviceCode(
203
+ services: Services,
204
+ env: SigningEnv,
205
+ client: EstablishedClient,
206
+ input: Extract<OAuthTokenRequest, { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE }>,
207
+ requestId: string,
208
+ ): Promise<OAuthTokenOutcome> {
209
+ if (client.kind !== 'cli') return { ok: false, error: 'unauthorized_client' }
210
+ const repository = services.repositories.oauth
211
+ const now = unixNow()
212
+ const hash = await hashToken(input.device_code)
213
+ const attempt = await repository.deviceAuthorization(hash)
214
+ if (attempt === null || attempt.client_id !== input.client_id) return { ok: false, error: 'invalid_grant' }
215
+ if (attempt.status === 'redeemed') {
216
+ // A spent device code presented again may have leaked: revoke what it gave, as for a replayed authorization code.
217
+ if (attempt.grant_id !== null) {
218
+ await repository.revokeGrant(attempt.grant_id, now, grantRevocation(requestId, attempt.grant_id, input.client_id, 'device_code_replay'))
219
+ }
220
+ return { ok: false, error: 'invalid_grant' }
221
+ }
222
+ if (attempt.expires_at <= now) return { ok: false, error: 'expired_token' }
223
+ if (!await repository.admitDevicePoll(hash, now)) return { ok: false, error: 'slow_down' }
224
+ if (attempt.status === 'denied') return { ok: false, error: 'access_denied' }
225
+ if (attempt.status === 'pending') return { ok: false, error: 'authorization_pending' }
226
+ const request = attemptRequest(attempt)
227
+ const [first] = request?.resources ?? []
228
+ // Checked before the attempt is spent, so a wrong resource does not cost the approval.
229
+ if (
230
+ request === null || first === undefined || !request.resources.includes(input.resource) || attempt.principal_id === null
231
+ || attempt.session_id === null || attempt.grant_expires_at === null
232
+ ) {
233
+ return { ok: false, error: 'invalid_grant' }
234
+ }
235
+ const grant: OAuthGrantRow = {
236
+ id: uuidv7(),
237
+ principal_id: attempt.principal_id,
238
+ session_id: attempt.session_id,
239
+ client_id: attempt.client_id,
240
+ app: attempt.app,
241
+ resource: first,
242
+ resources: JSON.stringify(request.resources),
243
+ scopes: JSON.stringify(request.scopes),
244
+ created_at: now,
245
+ expires_at: attempt.grant_expires_at,
246
+ revoked_at: null,
247
+ }
248
+ // The grant's whole authority (session, principal, configuration) is checked before anything is written.
249
+ if (await grantAuthority(services, grant, now, input.resource) === null) return { ok: false, error: 'invalid_grant' }
250
+ const refreshToken = generateToken()
251
+ const claimed = await repository.redeemDeviceAuthorization(hash, grant, await hashToken(refreshToken), {
252
+ requestId,
253
+ principalId: grant.principal_id,
254
+ principalLabel: grant.principal_id,
255
+ app: 'propustka',
256
+ action: 'iam.oauth.grant.create',
257
+ resourceType: 'oauth_grant',
258
+ resourceId: grant.id,
259
+ metadata: { clientId: grant.client_id, app: grant.app, resources: request.resources, scopes: request.scopes, flow: 'device' },
260
+ }, now)
261
+ if (claimed === null) return { ok: false, error: 'invalid_grant' }
262
+ const access = await mintForGrant(services, env, grant, input.resource, now)
263
+ if (access === null) return { ok: false, error: 'invalid_grant' }
264
+ return { ok: true, body: { ...access, refresh_token: refreshToken } }
265
+ }
package/src/oauth-http.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { DEFAULT_LOCALE } from '@fabrika/auth-core'
2
2
  import {
3
3
  OAUTH_CLIENT_ASSERTION_ALGORITHMS,
4
+ OAUTH_DEVICE_CODE_GRANT_TYPE,
4
5
  type OAuthAuthorizationRequest,
5
6
  type OAuthAuthorizationServerMetadata,
6
7
  type OAuthClientCredential,
7
8
  type OAuthResourceDto,
8
9
  parseOAuthAuthorizationAttempt,
9
10
  parseOAuthClientCredential,
11
+ parseOAuthDeviceAuthorizationRequest,
10
12
  parseOAuthRevocationRequest,
11
13
  parseOAuthTokenRequest,
12
14
  resolveOAuthAuthorizationScopes,
@@ -18,9 +20,11 @@ import { principalStatus } from './db'
18
20
  import type { Env } from './env'
19
21
  import { escapeHtml } from './html'
20
22
  import { installationBrand } from './installation-brand'
21
- import { establishClient, type EstablishedClient, exchangeOAuthToken, grantAuthorization, revokeOAuthToken, scopeCeiling } from './oauth'
23
+ import { establishClient, exchangeOAuthToken, grantAuthorization, type ManagedClient, revokeOAuthToken, scopeCeiling, servesClient } from './oauth'
22
24
  import { authenticateOAuthClient, authenticateRevokingClient } from './oauth-client-auth'
23
25
  import type { OAuthConfig } from './oauth-config'
26
+ import { OAUTH_DEVICE_PATH, redeemDeviceCode, startDeviceAuthorization } from './oauth-device'
27
+ import { handleDevicePage } from './oauth-device-page'
24
28
  import { normalizeOrigin } from './origin'
25
29
  import { htmlPage } from './password-pages'
26
30
  import type { Services } from './services'
@@ -29,11 +33,21 @@ export const OAUTH_METADATA_PATH = '/.well-known/oauth-authorization-server'
29
33
  const AUTHORIZE_PATH = '/oauth/authorize'
30
34
  const TOKEN_PATH = '/oauth/token'
31
35
  const REVOKE_PATH = '/oauth/revoke'
36
+ const DEVICE_AUTHORIZATION_PATH = '/oauth/device_authorization'
32
37
 
33
38
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
34
39
 
35
- /** The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. */
36
- export async function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string): Promise<Response> {
40
+ /**
41
+ * The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. `clientAddress` is the
42
+ * composition's client coordinate (`client-address.ts`), null where it names none.
43
+ */
44
+ export async function handleOAuth(
45
+ request: Request,
46
+ services: Services,
47
+ env: SigningEnv,
48
+ requestId: string,
49
+ clientAddress: string | null,
50
+ ): Promise<Response> {
37
51
  const config = services.config.oauth
38
52
  if (config === null) return new Response('not found', { status: 404 })
39
53
  const pathname = new URL(request.url).pathname
@@ -48,6 +62,10 @@ export async function handleOAuth(request: Request, services: Services, env: Sig
48
62
  return request.method === 'POST' ? token(request, services, env, config, requestId) : methodNotAllowed('POST')
49
63
  case REVOKE_PATH:
50
64
  return request.method === 'POST' ? revoke(request, services, env, config, requestId) : methodNotAllowed('POST')
65
+ case DEVICE_AUTHORIZATION_PATH:
66
+ return request.method === 'POST' ? deviceAuthorization(request, services, config, clientAddress) : methodNotAllowed('POST')
67
+ case OAUTH_DEVICE_PATH:
68
+ return handleDevicePage(request, services, config)
51
69
  default:
52
70
  return new Response('not found', { status: 404 })
53
71
  }
@@ -59,9 +77,10 @@ function authorizationServerMetadata(issuer: string): Response {
59
77
  authorization_endpoint: `${issuer}${AUTHORIZE_PATH}`,
60
78
  token_endpoint: `${issuer}${TOKEN_PATH}`,
61
79
  revocation_endpoint: `${issuer}${REVOKE_PATH}`,
80
+ device_authorization_endpoint: `${issuer}${DEVICE_AUTHORIZATION_PATH}`,
62
81
  jwks_uri: `${issuer}/.well-known/jwks.json`,
63
82
  response_types_supported: ['code'],
64
- grant_types_supported: ['authorization_code', 'refresh_token'],
83
+ grant_types_supported: ['authorization_code', 'refresh_token', OAUTH_DEVICE_CODE_GRANT_TYPE],
65
84
  code_challenge_methods_supported: ['S256'],
66
85
  token_endpoint_auth_methods_supported: ['none', 'private_key_jwt'],
67
86
  token_endpoint_auth_signing_alg_values_supported: [...OAUTH_CLIENT_ASSERTION_ALGORITHMS],
@@ -76,7 +95,7 @@ function authorizationServerMetadata(issuer: string): Response {
76
95
  type AuthorizationCheck =
77
96
  | { kind: 'refused'; message: string }
78
97
  | { kind: 'redirect'; response: Response }
79
- | { kind: 'valid'; request: OAuthAuthorizationRequest; client: EstablishedClient; resource: OAuthResourceDto; scopes: string[] }
98
+ | { kind: 'valid'; request: OAuthAuthorizationRequest; client: ManagedClient; resource: OAuthResourceDto; scopes: string[] }
80
99
 
81
100
  /**
82
101
  * Validate an authorization request in the order RFC 6749 §4.1.2.1 requires: until the client and its
@@ -89,7 +108,8 @@ async function checkAuthorization(issuer: string, config: OAuthConfig, input: Re
89
108
  const client = await establishClient(config, coordinates.client_id, coordinates.redirect_uri)
90
109
  if (client === null) return { kind: 'refused', message: 'The client or its redirect URI is not registered.' }
91
110
  if (attempt.kind === 'invalid_scope') return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
92
- const resource = config.resources.find((entry) => entry.resource === coordinates.resource)
111
+ // The command-line client's resources are served through the device grant only, never to a managed client.
112
+ const resource = config.resources.find((entry) => entry.resource === coordinates.resource && servesClient(entry, false))
93
113
  if (resource === undefined) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_target' }) }
94
114
  const scopes = resolveOAuthAuthorizationScopes(attempt.request.scope, resource)
95
115
  if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
@@ -144,7 +164,9 @@ async function token(request: Request, services: Services, env: SigningEnv, conf
144
164
  audiences: [`${issuer}${TOKEN_PATH}`, issuer],
145
165
  })
146
166
  if (client === null) return protocolError('invalid_client', 401)
147
- const outcome = await exchangeOAuthToken(services, env, client, input, requestId)
167
+ const outcome = input.grant_type === OAUTH_DEVICE_CODE_GRANT_TYPE
168
+ ? await redeemDeviceCode(services, env, client, input, requestId)
169
+ : await exchangeOAuthToken(services, env, client, input, requestId)
148
170
  if (!outcome.ok) return protocolError(outcome.error, 400)
149
171
  return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
150
172
  }
@@ -167,6 +189,30 @@ async function revoke(request: Request, services: Services, env: SigningEnv, con
167
189
  return new Response(null, { status: 200, headers: { 'cache-control': 'no-store' } })
168
190
  }
169
191
 
192
+ /** RFC 8628 §3.1: a public client starts a device authorization; a client that sends an assertion is refused. */
193
+ async function deviceAuthorization(request: Request, services: Services, config: OAuthConfig, clientAddress: string | null): Promise<Response> {
194
+ const form = await readForm(request)
195
+ const fields = form === null ? null : withRepeatedResource(form)
196
+ if (fields === null) return protocolError('invalid_request', 400)
197
+ if (parseOAuthClientCredential(fields.fields)?.method !== 'none') return protocolError('invalid_client', 401)
198
+ const input = parseOAuthDeviceAuthorizationRequest(fields)
199
+ if (input === null) return protocolError('invalid_request', 400)
200
+ const outcome = await startDeviceAuthorization(services, config, input, clientAddress)
201
+ if (!outcome.ok && outcome.error === 'temporarily_unavailable') {
202
+ return Response.json({ error: outcome.error }, { status: 429, headers: { 'retry-after': '60', 'cache-control': 'no-store', pragma: 'no-cache' } })
203
+ }
204
+ if (!outcome.ok) return protocolError(outcome.error, 400)
205
+ return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
206
+ }
207
+
208
+ /** RFC 8707 §2: `resource` may repeat to name several resources; every other parameter still must not. */
209
+ function withRepeatedResource(params: URLSearchParams): { fields: Record<string, string>; resources: string[] } | null {
210
+ const resources = params.getAll('resource')
211
+ const rest = new URLSearchParams([...params].filter(([name]) => name !== 'resource'))
212
+ const fields = singleValued(rest)
213
+ return fields === null ? null : { fields, resources }
214
+ }
215
+
170
216
  /**
171
217
  * RFC 7521 §4.2 lets a client that authenticates with an assertion omit `client_id`; the assertion's
172
218
  * `sub` then names it. Nothing is trusted from it here: verification requires `iss` = `sub` = that id.
package/src/oauth.ts CHANGED
@@ -3,16 +3,19 @@ import {
3
3
  DEFAULT_TOKEN_TTL_SECONDS,
4
4
  type KeyGrant,
5
5
  narrowPermissions,
6
+ OAUTH_CLI_CLIENT_ID,
6
7
  parseOAuthScopes,
7
8
  type PermissionEntry,
8
9
  } from '@fabrika/auth-core'
9
- import type {
10
- OAuthAuthorizationRequest,
11
- OAuthClientMetadataDocument,
12
- OAuthResourceDto,
13
- OAuthRevocationRequest,
14
- OAuthTokenRequest,
15
- OAuthTokenResponse,
10
+ import {
11
+ OAUTH_DEVICE_CODE_GRANT_TYPE,
12
+ type OAuthAuthorizationRequest,
13
+ type OAuthClientMetadataDocument,
14
+ type OAuthResourceDto,
15
+ type OAuthRevocationRequest,
16
+ type OAuthTokenRequest,
17
+ type OAuthTokenResponse,
18
+ resolveOAuthScopeToken,
16
19
  } from '@fabrika/iam-contract'
17
20
  import { uuidv7 } from '@fabrika/platform'
18
21
  import { sessionEndsAt, sessionUsable } from './auth'
@@ -34,21 +37,49 @@ export const OAUTH_CODE_TTL_SECONDS = 60
34
37
 
35
38
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
36
39
 
37
- export interface EstablishedClient {
38
- registration: ManagedOAuthClient
39
- metadata: OAuthClientMetadataDocument
40
+ /**
41
+ * A client an authorization or token request comes from: an operator-registered CIMD client, or the installation's own
42
+ * command-line client, a public client IAM knows without a document. The CLI client has no redirect URI, so it never
43
+ * completes an authorization request; it redeems the grants IAM gives it otherwise and refreshes them.
44
+ */
45
+ export type EstablishedClient =
46
+ | { kind: 'managed'; registration: ManagedOAuthClient; metadata: OAuthClientMetadataDocument }
47
+ | { kind: 'cli'; clientId: string }
48
+
49
+ export type ManagedClient = Extract<EstablishedClient, { kind: 'managed' }>
50
+
51
+ /** The grant types a client may use at the token endpoint: its document's, or the CLI client's fixed set. */
52
+ function clientGrantTypes(client: EstablishedClient): readonly string[] {
53
+ return client.kind === 'cli' ? ['refresh_token'] : client.metadata.grant_types
54
+ }
55
+
56
+ /** Whether `resource` is served to the command-line client (`cli`) or to the managed clients; never to both. */
57
+ export function servesClient(resource: OAuthResourceDto, cli: boolean): boolean {
58
+ return (resource.client === 'cli') === cli
59
+ }
60
+
61
+ /** The resources a grant was given for: every token it mints names one of them. */
62
+ export function grantResources(grant: Pick<OAuthGrantRow, 'resource' | 'resources'>): string[] {
63
+ const stored = grant.resources === null ? null : storedResourceList(grant.resources)
64
+ return stored ?? [grant.resource]
65
+ }
66
+
67
+ /** A stored JSON list of resources, or null when it is not one. */
68
+ export function storedResourceList(text: string): string[] | null {
69
+ const value = parseJsonOrNull(text)
70
+ return Array.isArray(value) && value.length > 0 && value.every((entry): entry is string => typeof entry === 'string') ? value : null
40
71
  }
41
72
 
42
73
  /**
43
74
  * Resolve a client and its redirect URI. Until this succeeds nothing may be redirected to
44
75
  * `redirect_uri`. An unregistered client id is refused before any metadata fetch.
45
76
  */
46
- export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<EstablishedClient | null> {
77
+ export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<ManagedClient | null> {
47
78
  const registration = config.clients.find((client) => client.clientId === clientId)
48
79
  if (registration === undefined || !registration.redirectUris.includes(redirectUri)) return null
49
80
  const metadata = await clientMetadata(registration)
50
81
  if (metadata === null || !metadata.redirect_uris.includes(redirectUri)) return null
51
- return { registration, metadata }
82
+ return { kind: 'managed', registration, metadata }
52
83
  }
53
84
 
54
85
  /** Record the consent and return the plaintext authorization code — the only time it exists. */
@@ -67,6 +98,7 @@ export async function grantAuthorization(
67
98
  client_id: input.request.client_id,
68
99
  app: input.resource.app,
69
100
  resource: input.resource.resource,
101
+ resources: null,
70
102
  scopes: JSON.stringify(input.scopes),
71
103
  created_at: now,
72
104
  expires_at: input.session.expires_at,
@@ -92,19 +124,32 @@ export async function grantAuthorization(
92
124
  return code
93
125
  }
94
126
 
95
- export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: 'invalid_grant' }
127
+ /** RFC 6749 §5.2 and RFC 8628 §3.5: what a refused token request answers. */
128
+ export type OAuthTokenError =
129
+ | 'invalid_grant'
130
+ | 'invalid_target'
131
+ | 'unauthorized_client'
132
+ | 'authorization_pending'
133
+ | 'slow_down'
134
+ | 'access_denied'
135
+ | 'expired_token'
136
+
137
+ export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: OAuthTokenError }
96
138
 
97
139
  /** Redeem a code or rotate a refresh token for a client `authenticateOAuthClient` established. */
98
140
  export async function exchangeOAuthToken(
99
141
  services: Services,
100
142
  env: SigningEnv,
101
143
  client: EstablishedClient,
102
- input: OAuthTokenRequest,
144
+ input: Exclude<OAuthTokenRequest, { grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE }>,
103
145
  requestId: string,
104
146
  ): Promise<OAuthTokenOutcome> {
105
- return input.grant_type === 'authorization_code'
106
- ? redeemCode(services, env, client.metadata, input, requestId)
107
- : rotateRefreshToken(services, env, client.metadata, input, requestId)
147
+ const grantTypes = clientGrantTypes(client)
148
+ if (input.grant_type === 'authorization_code') {
149
+ // RFC 6749 §5.2: the CLI client may not use this grant type; refused before the code is spent.
150
+ return client.kind === 'managed' ? redeemCode(services, env, client.metadata, input, requestId) : { ok: false, error: 'unauthorized_client' }
151
+ }
152
+ return rotateRefreshToken(services, env, grantTypes, input, requestId)
108
153
  }
109
154
 
110
155
  async function redeemCode(
@@ -128,12 +173,12 @@ async function redeemCode(
128
173
  const grant = await repository.grant(code.grant_id)
129
174
  const proof = timingSafeEqualHex(await hashToken(await pkceChallenge(input.code_verifier)), await hashToken(code.challenge))
130
175
  if (
131
- !proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource
176
+ !proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || !grantResources(grant).includes(input.resource)
132
177
  || code.redirect_uri !== input.redirect_uri
133
178
  ) {
134
179
  return { ok: false, error: 'invalid_grant' }
135
180
  }
136
- const access = await mintForGrant(services, env, grant, now)
181
+ const access = await mintForGrant(services, env, grant, input.resource, now)
137
182
  if (access === null) return { ok: false, error: 'invalid_grant' }
138
183
  if (!metadata.grant_types.includes('refresh_token')) return { ok: true, body: access }
139
184
  const refreshToken = generateToken()
@@ -144,14 +189,22 @@ async function redeemCode(
144
189
  async function rotateRefreshToken(
145
190
  services: Services,
146
191
  env: SigningEnv,
147
- metadata: OAuthClientMetadataDocument,
192
+ grantTypes: readonly string[],
148
193
  input: Extract<OAuthTokenRequest, { grant_type: 'refresh_token' }>,
149
194
  requestId: string,
150
195
  ): Promise<OAuthTokenOutcome> {
151
- if (!metadata.grant_types.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
196
+ if (!grantTypes.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
152
197
  const repository = services.repositories.oauth
153
198
  const now = unixNow()
154
199
  const hash = await hashToken(input.refresh_token)
200
+ // RFC 8707: a live token asking for a resource its grant does not cover is refused unspent, so the client keeps it.
201
+ const unspent = await repository.refreshToken(hash)
202
+ if (unspent !== null && unspent.used_at === null) {
203
+ const covering = await repository.grant(unspent.grant_id)
204
+ if (covering !== null && covering.client_id === input.client_id && !grantResources(covering).includes(input.resource)) {
205
+ return { ok: false, error: 'invalid_target' }
206
+ }
207
+ }
155
208
  const presented = await repository.consumeRefreshToken(hash, now)
156
209
  if (presented === null) {
157
210
  const spent = await repository.refreshToken(hash)
@@ -160,10 +213,10 @@ async function rotateRefreshToken(
160
213
  return { ok: false, error: 'invalid_grant' }
161
214
  }
162
215
  const grant = await repository.grant(presented.grant_id)
163
- if (presented.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource) {
216
+ if (presented.expires_at <= now || grant === null || grant.client_id !== input.client_id || !grantResources(grant).includes(input.resource)) {
164
217
  return { ok: false, error: 'invalid_grant' }
165
218
  }
166
- const access = await mintForGrant(services, env, grant, now)
219
+ const access = await mintForGrant(services, env, grant, input.resource, now)
167
220
  if (access === null) return { ok: false, error: 'invalid_grant' }
168
221
  const next = generateToken()
169
222
  await repository.insertRefreshToken({ token_hash: await hashToken(next), grant_id: grant.id, expires_at: grant.expires_at })
@@ -190,8 +243,15 @@ export async function revokeOAuthToken(services: Services, env: SigningEnv, inpu
190
243
  }
191
244
  }
192
245
 
193
- async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, now: number): Promise<OAuthTokenResponse | null> {
194
- const authority = await grantAuthority(services, grant, now)
246
+ /** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
247
+ export async function mintForGrant(
248
+ services: Services,
249
+ env: SigningEnv,
250
+ grant: OAuthGrantRow,
251
+ resource: string,
252
+ now: number,
253
+ ): Promise<OAuthTokenResponse | null> {
254
+ const authority = await grantAuthority(services, grant, now, resource)
195
255
  if (authority === null) return null
196
256
  // A replay or a revocation may have landed while authority was resolved; read the grant once more.
197
257
  const current = await services.repositories.oauth.grant(grant.id)
@@ -200,7 +260,7 @@ async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGra
200
260
  const claims = buildResourceAccessClaims({
201
261
  iss: services.config.issuer,
202
262
  app: grant.app,
203
- resource: grant.resource,
263
+ resource,
204
264
  subject: authority.principal.id,
205
265
  label: authority.principal.label,
206
266
  permissions: authority.permissions,
@@ -230,11 +290,15 @@ export async function grantAuthority(
230
290
  services: Services,
231
291
  grant: OAuthGrantRow,
232
292
  now: number,
293
+ resourceUri: string = grant.resource,
233
294
  ): Promise<{ principal: PrincipalRow; scopes: string[]; permissions: PermissionEntry[]; expiresAt: number | null } | null> {
234
295
  const config = services.config.oauth
235
- if (config === null || grant.revoked_at !== null || grant.expires_at <= now) return null
236
- const resource = config.resources.find((entry) => entry.resource === grant.resource && entry.app === grant.app)
237
- if (resource === undefined || !config.clients.some((client) => client.clientId === grant.client_id)) return null
296
+ 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
238
302
  const scopes = parseOAuthScopes(parseJsonOrNull(grant.scopes))
239
303
  const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
240
304
  if (scopes === null || ceiling === null) return null
@@ -255,19 +319,19 @@ export async function grantAuthority(
255
319
  export function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null {
256
320
  const ceiling: KeyGrant[] = []
257
321
  for (const scope of scopes) {
258
- const grant = resource.scopeGrants.find((entry) => entry.scope === scope)
259
- if (grant === undefined) return null
260
- ceiling.push(...grant.permissions)
322
+ const permissions = resolveOAuthScopeToken(scope, resource)
323
+ if (permissions === null) return null
324
+ ceiling.push(...permissions)
261
325
  }
262
326
  return ceiling
263
327
  }
264
328
 
265
329
  /** The record of a grant's revocation: by its client, or by IAM on a replayed code or refresh token. */
266
- function grantRevocation(
330
+ export function grantRevocation(
267
331
  requestId: string,
268
332
  grantId: string,
269
333
  clientId: string,
270
- reason: 'code_replay' | 'refresh_replay' | 'client_revocation',
334
+ reason: 'code_replay' | 'refresh_replay' | 'device_code_replay' | 'client_revocation',
271
335
  ): AuditEventInput {
272
336
  return {
273
337
  requestId,
@@ -124,8 +124,10 @@ const AUDIT_PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?'
124
124
  * The INSERT of one audit row, for the batch of an unconditional change it records: the row and the change commit
125
125
  * together, and a failed insert rolls the change back. Diff and metadata are stored JSON-encoded.
126
126
  */
127
- export function auditEventStatement(db: SqlDatabase, event: AuditEventInput): SqlStatement {
128
- return db.prepare(`INSERT INTO audit_events ${AUDIT_COLUMNS} VALUES (${AUDIT_PLACEHOLDERS})`).bind(...auditValues(uuidv7(), event))
127
+ /** The INSERT of one audit row; with `guard`, written only when the guard finds its row (see `SqlGuard`). */
128
+ export function auditEventStatement(db: SqlDatabase, event: AuditEventInput, guard?: SqlGuard): SqlStatement {
129
+ const insert = guardedInsert(`audit_events ${AUDIT_COLUMNS}`, AUDIT_PLACEHOLDERS, auditValues(uuidv7(), event), guard)
130
+ return db.prepare(insert.sql).bind(...insert.binds)
129
131
  }
130
132
 
131
133
  /**