@crombolo/server 0.43.1 → 0.45.0

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,334 @@
1
+ /**
2
+ * Signing in to a remote from CI (story 160): a GitHub Actions or GitLab job's
3
+ * OIDC identity token, exchanged (RFC 8693) for a short-lived token that acts
4
+ * as the trust rule it matched. No secret is stored anywhere: the provider signs
5
+ * the identity token, and a rule an administrator made on this site says which
6
+ * repository and branch, tag or environment it must come from, and what it may
7
+ * do. docs/remote-protocol.md, "Signing in from CI".
8
+ */
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import { RemotePermissions } from '@crombolo/core'
11
+ import {
12
+ type CiToken,
13
+ type Db,
14
+ RemoteTrustRepository,
15
+ type TrustRefKind,
16
+ type TrustRule,
17
+ type TrustRuleInput,
18
+ } from '@crombolo/data'
19
+ import { createRemoteJWKSet, type JWTPayload, jwtVerify } from 'jose'
20
+ import { AttemptLimiter } from './setup.ts'
21
+
22
+ export const GITHUB_ISSUER = 'https://token.actions.githubusercontent.com'
23
+ export const GITLAB_ISSUER = 'https://gitlab.com'
24
+ export const TOKEN_EXCHANGE_GRANT = 'urn:ietf:params:oauth:grant-type:token-exchange'
25
+ export const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt'
26
+ export const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'
27
+
28
+ /** How long a CI token lasts. There is no refresh: the job exchanges again. */
29
+ export const CI_TOKEN_SECONDS = 15 * 60
30
+ /** An identity token valid for longer than this is refused. */
31
+ const MAX_IDENTITY_SECONDS = 60 * 60
32
+
33
+ /** The issuers a site trusts tokens from: GitHub's, gitlab.com's, and any it names. */
34
+ export function trustedIssuers(extra: readonly string[] = []): string[] {
35
+ return [...new Set([GITHUB_ISSUER, GITLAB_ISSUER, ...extra.map((i) => i.replace(/\/+$/, ''))])]
36
+ }
37
+
38
+ const isLocal = (host: string) => host === 'localhost' || host === '127.0.0.1' || host === '[::1]'
39
+
40
+ /** An issuer is fetched over HTTPS; a local one only for a test or a developer's own GitLab. */
41
+ export function usableIssuer(issuer: string): boolean {
42
+ try {
43
+ const url = new URL(issuer)
44
+ return url.protocol === 'https:' || (url.protocol === 'http:' && isLocal(url.hostname))
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
50
+ /** Where a CI run was, from its identity token, in the same words for either provider. */
51
+ export interface RunClaims {
52
+ repository: string
53
+ refType: 'branch' | 'tag' | undefined
54
+ ref: string | undefined
55
+ environment: string | undefined
56
+ /** The run, for the audit log: GitHub's run id and attempt, GitLab's pipeline and job. */
57
+ run: string | undefined
58
+ }
59
+
60
+ const text = (value: unknown) => (typeof value === 'string' && value !== '' ? value : undefined)
61
+
62
+ /** A verified identity token's claims, as GitHub or GitLab put them. Pure. */
63
+ export function runClaims(issuer: string, payload: JWTPayload): RunClaims | undefined {
64
+ const refType = text(payload.ref_type)
65
+ const kind = refType === 'branch' || refType === 'tag' ? refType : undefined
66
+ if (issuer === GITHUB_ISSUER) {
67
+ const repository = text(payload.repository)
68
+ if (!repository) return undefined
69
+ const ref = text(payload.ref)
70
+ const prefix = kind === 'tag' ? 'refs/tags/' : 'refs/heads/'
71
+ const runId = text(payload.run_id)
72
+ return {
73
+ repository,
74
+ refType: kind,
75
+ ref: ref?.startsWith(prefix) ? ref.slice(prefix.length) : ref,
76
+ environment: text(payload.environment),
77
+ run: runId ? `${runId}/${text(payload.run_attempt) ?? '1'}` : undefined,
78
+ }
79
+ }
80
+ // GitLab, whether gitlab.com or a self-managed instance a site names.
81
+ const repository = text(payload.project_path)
82
+ if (!repository) return undefined
83
+ const pipeline = text(payload.pipeline_id)
84
+ const job = text(payload.job_id)
85
+ return {
86
+ repository,
87
+ refType: kind,
88
+ ref: text(payload.ref),
89
+ environment: text(payload.environment),
90
+ run: pipeline ? `${pipeline}${job ? `/${job}` : ''}` : undefined,
91
+ }
92
+ }
93
+
94
+ /** Whether a rule admits a run: its issuer, repository and ref exactly, no wildcards. Pure. */
95
+ export function ruleMatches(rule: TrustRule, issuer: string, claims: RunClaims): boolean {
96
+ if (rule.disabled || rule.issuer !== issuer) return false
97
+ // Owners and repositories are case-insensitive on both providers.
98
+ if (rule.repository.toLowerCase() !== claims.repository.toLowerCase()) return false
99
+ if (rule.refKind === 'environment') return claims.environment === rule.refValue
100
+ return claims.refType === rule.refKind && claims.ref === rule.refValue
101
+ }
102
+
103
+ /** The remote verbs a rule may hold. */
104
+ export const TRUSTABLE_PERMISSIONS: readonly string[] = Object.values(RemotePermissions)
105
+
106
+ const REF_KINDS: readonly TrustRefKind[] = ['branch', 'tag', 'environment']
107
+
108
+ /** A rule as posted, checked: undefined and the reasons when it cannot be one. Pure. */
109
+ export function readRuleInput(
110
+ body: unknown,
111
+ issuers: readonly string[],
112
+ ): { input?: TrustRuleInput; problems: string[] } {
113
+ const b = (body ?? {}) as Record<string, unknown>
114
+ const problems: string[] = []
115
+ const name = typeof b.name === 'string' ? b.name.trim() : ''
116
+ if (!name || name.length > 255) problems.push('Give it a name of up to 255 characters.')
117
+ const issuer = typeof b.issuer === 'string' ? b.issuer.trim().replace(/\/+$/, '') : ''
118
+ if (!issuers.includes(issuer))
119
+ problems.push(`The provider must be one of: ${issuers.join(', ')}.`)
120
+ const repository = typeof b.repository === 'string' ? b.repository.trim() : ''
121
+ if (!/^[\w.-]+(\/[\w.-]+)+$/.test(repository))
122
+ problems.push(
123
+ 'The repository is owner/name (GitHub) or group/project (GitLab), with no wildcards.',
124
+ )
125
+ const refKind = REF_KINDS.find((k) => k === b.refKind)
126
+ if (!refKind) problems.push('Say whether it matches a branch, a tag or an environment.')
127
+ const refValue = typeof b.refValue === 'string' ? b.refValue.trim() : ''
128
+ if (!refValue || /[*?[\]]/.test(refValue))
129
+ problems.push('Name the branch, tag or environment exactly, with no wildcards.')
130
+ const permissions = Array.isArray(b.permissions)
131
+ ? [...new Set(b.permissions.filter((p): p is string => typeof p === 'string'))]
132
+ : []
133
+ if (permissions.length === 0) problems.push('Choose what it may do.')
134
+ const unknown = permissions.filter((p) => !TRUSTABLE_PERMISSIONS.includes(p))
135
+ if (unknown.length > 0) problems.push(`Not remote permissions: ${unknown.join(', ')}.`)
136
+ if (problems.length > 0) return { problems }
137
+ return {
138
+ input: { name, issuer, repository, refKind: refKind as TrustRefKind, refValue, permissions },
139
+ problems,
140
+ }
141
+ }
142
+
143
+ /** The principal a CI token acts as: the rule, holding its remote permissions and nothing else. */
144
+ export function ciPrincipal(token: CiToken): Principal {
145
+ const none = { root: false, keys: [] }
146
+ return {
147
+ id: token.rule.key,
148
+ userName: token.rule.name,
149
+ name: `CI: ${token.rule.name}`,
150
+ email: '',
151
+ isAdmin: false,
152
+ languageIsoCode: undefined,
153
+ avatarUrls: [],
154
+ allowedSections: [],
155
+ permissions: token.rule.permissions.filter((p) => TRUSTABLE_PERMISSIONS.includes(p)),
156
+ groupKeys: [],
157
+ hasAccessToAllLanguages: false,
158
+ languages: [],
159
+ startNodes: { document: none, media: none, element: none },
160
+ groups: [],
161
+ ci: { rule: token.rule.key, claims: token.claims },
162
+ }
163
+ }
164
+
165
+ /** Whether a request came over HTTPS: directly, or through a proxy that says so. */
166
+ export function overHttps(request: Request, url: URL): boolean {
167
+ if (url.protocol === 'https:') return true
168
+ if (request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() === 'https') return true
169
+ return isLocal(url.hostname)
170
+ }
171
+
172
+ export interface CiSignIn {
173
+ /** What the discovery document says about signing in from CI. */
174
+ discovery(origin: string, api: string): Record<string, unknown>
175
+ /** The exchange: an identity token in, a CI token out, or a refusal that says nothing more. */
176
+ exchange(request: Request, url: URL, ip: string | undefined): Promise<Response>
177
+ /** The principal a bearer token is, when it is a CI token. */
178
+ principalOf(request: Request): Promise<Principal | undefined>
179
+ readonly issuers: readonly string[]
180
+ }
181
+
182
+ type Refusal = { reason: string; issuer?: string; repository?: string }
183
+
184
+ export function createCiSignIn(options: {
185
+ db: Db
186
+ issuers: readonly string[]
187
+ /** Told of each exchange, accepted or refused, for the audit log. */
188
+ onExchange(
189
+ outcome: { ok: true; rule: TrustRule; claims: RunClaims } | ({ ok: false } & Refusal),
190
+ request: Request,
191
+ ): Promise<void>
192
+ }): CiSignIn {
193
+ const rules = new RemoteTrustRepository(options.db)
194
+ const issuers = options.issuers.filter(usableIssuer)
195
+ const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
196
+ const keySets = new Map<string, ReturnType<typeof createRemoteJWKSet>>()
197
+
198
+ /** The issuer's signing keys, from its OIDC discovery; cached, and failing closed. */
199
+ const keysOf = async (issuer: string) => {
200
+ const known = keySets.get(issuer)
201
+ if (known) return known
202
+ const response = await fetch(`${issuer}/.well-known/openid-configuration`)
203
+ if (!response.ok) throw new Error(`the issuer's discovery answered ${response.status}`)
204
+ const { jwks_uri: jwksUri } = (await response.json()) as { jwks_uri?: string }
205
+ if (!jwksUri || !usableIssuer(new URL(jwksUri).origin))
206
+ throw new Error('the issuer names no usable key set')
207
+ const set = createRemoteJWKSet(new URL(jwksUri))
208
+ keySets.set(issuer, set)
209
+ return set
210
+ }
211
+
212
+ const refuse = async (request: Request, refusal: Refusal, ip: string | undefined) => {
213
+ limiter.fail(`ip:${ip ?? 'unknown'}`)
214
+ if (refusal.issuer) limiter.fail(`issuer:${refusal.issuer}`)
215
+ await options.onExchange({ ok: false, ...refusal }, request)
216
+ // The same answer whatever went wrong: the audit log has the reason, the caller does not.
217
+ return Response.json(
218
+ { error: 'invalid_grant', error_description: 'The identity token was not accepted.' },
219
+ { status: 400, headers: { 'cache-control': 'no-store' } },
220
+ )
221
+ }
222
+
223
+ const unverifiedIssuer = (token: string): string | undefined => {
224
+ try {
225
+ const body = token.split('.')[1]
226
+ if (!body) return undefined
227
+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as JWTPayload
228
+ return typeof payload.iss === 'string' ? payload.iss.replace(/\/+$/, '') : undefined
229
+ } catch {
230
+ return undefined
231
+ }
232
+ }
233
+
234
+ return {
235
+ issuers,
236
+
237
+ discovery(origin, api) {
238
+ return {
239
+ tokenExchange: `${api}/token`,
240
+ grantType: TOKEN_EXCHANGE_GRANT,
241
+ subjectTokenType: JWT_TOKEN_TYPE,
242
+ audience: origin,
243
+ issuers,
244
+ }
245
+ },
246
+
247
+ async exchange(request, url, ip) {
248
+ const json = (body: unknown, status: number) =>
249
+ Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
250
+ if (!overHttps(request, url))
251
+ return json(
252
+ { error: 'invalid_request', error_description: 'Signing in from CI needs HTTPS.' },
253
+ 400,
254
+ )
255
+ if (limiter.blocked(`ip:${ip ?? 'unknown'}`))
256
+ return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
257
+ const form = new URLSearchParams(await request.text())
258
+ if (form.get('grant_type') !== TOKEN_EXCHANGE_GRANT)
259
+ return json({ error: 'unsupported_grant_type' }, 400)
260
+ if (form.get('subject_token_type') !== JWT_TOKEN_TYPE)
261
+ return json({ error: 'invalid_request', error_description: 'A JWT is expected.' }, 400)
262
+ const token = form.get('subject_token') ?? ''
263
+
264
+ const issuer = unverifiedIssuer(token)
265
+ if (!issuer || !issuers.includes(issuer))
266
+ return refuse(request, { reason: 'an issuer this site does not trust' }, ip)
267
+ if (limiter.blocked(`issuer:${issuer}`))
268
+ return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
269
+
270
+ let payload: JWTPayload
271
+ try {
272
+ const verified = await jwtVerify(token, await keysOf(issuer), {
273
+ issuer,
274
+ audience: url.origin,
275
+ requiredClaims: ['exp', 'iat', 'jti'],
276
+ })
277
+ payload = verified.payload
278
+ } catch (error) {
279
+ return refuse(
280
+ request,
281
+ {
282
+ reason: `the token did not verify: ${error instanceof Error ? error.message : String(error)}`,
283
+ issuer,
284
+ },
285
+ ip,
286
+ )
287
+ }
288
+ if ((payload.exp as number) - (payload.iat as number) > MAX_IDENTITY_SECONDS)
289
+ return refuse(request, { reason: 'the token is valid for too long', issuer }, ip)
290
+
291
+ const claims = runClaims(issuer, payload)
292
+ if (!claims) return refuse(request, { reason: 'the token names no repository', issuer }, ip)
293
+ const rule = (await rules.liveFor(issuer)).find((candidate) =>
294
+ ruleMatches(candidate, issuer, claims),
295
+ )
296
+ if (!rule)
297
+ return refuse(
298
+ request,
299
+ { reason: 'no trust rule matches', issuer, repository: claims.repository },
300
+ ip,
301
+ )
302
+
303
+ const recorded: Record<string, string> = { repository: claims.repository }
304
+ if (claims.refType) recorded.refType = claims.refType
305
+ if (claims.ref) recorded.ref = claims.ref
306
+ if (claims.environment) recorded.environment = claims.environment
307
+ if (claims.run) recorded.run = claims.run
308
+ const issued = await rules.issue(
309
+ rule,
310
+ { issuer, jti: payload.jti as string, claims: recorded },
311
+ CI_TOKEN_SECONDS,
312
+ )
313
+ if (!issued) return refuse(request, { reason: 'the token was already used', issuer }, ip)
314
+ await options.onExchange({ ok: true, rule, claims }, request)
315
+ return json(
316
+ {
317
+ access_token: issued.token,
318
+ issued_token_type: ACCESS_TOKEN_TYPE,
319
+ token_type: 'Bearer',
320
+ expires_in: CI_TOKEN_SECONDS,
321
+ },
322
+ 200,
323
+ )
324
+ },
325
+
326
+ async principalOf(request) {
327
+ const header = request.headers.get('authorization') ?? ''
328
+ const match = /^Bearer\s+(crci_\S+)$/i.exec(header)
329
+ if (!match) return undefined
330
+ const token = await rules.resolve(match[1] as string)
331
+ return token ? ciPrincipal(token) : undefined
332
+ },
333
+ }
334
+ }