@crombolo/server 0.66.0 → 0.68.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.
- package/package.json +14 -14
- package/src/adapters/members.ts +16 -2
- package/src/approvals.ts +8 -2
- package/src/cli-tokens-api.ts +6 -0
- package/src/config.ts +18 -1
- package/src/external-sign-in.ts +8 -2
- package/src/identity-providers.ts +52 -1
- package/src/index.ts +1 -0
- package/src/principal.ts +1 -0
- package/src/remote-ci.ts +34 -26
- package/src/remote-people.ts +339 -0
- package/src/remote.ts +39 -10
- package/src/server.ts +106 -0
- package/src/settings.ts +7 -0
- package/src/telemetry.ts +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.68.0",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -32,19 +32,19 @@
|
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@crombolo/api-delivery": "0.
|
|
36
|
-
"@crombolo/api-management": "0.
|
|
37
|
-
"@crombolo/auth": "0.
|
|
38
|
-
"@crombolo/backoffice-host": "0.
|
|
39
|
-
"@crombolo/common": "0.
|
|
40
|
-
"@crombolo/content": "0.
|
|
41
|
-
"@crombolo/contracts": "0.
|
|
42
|
-
"@crombolo/core": "0.
|
|
43
|
-
"@crombolo/data": "0.
|
|
44
|
-
"@crombolo/extension": "0.
|
|
45
|
-
"@crombolo/render": "0.
|
|
46
|
-
"@crombolo/schema": "0.
|
|
47
|
-
"@crombolo/transfer": "0.
|
|
35
|
+
"@crombolo/api-delivery": "0.68.0",
|
|
36
|
+
"@crombolo/api-management": "0.68.0",
|
|
37
|
+
"@crombolo/auth": "0.68.0",
|
|
38
|
+
"@crombolo/backoffice-host": "0.68.0",
|
|
39
|
+
"@crombolo/common": "0.68.0",
|
|
40
|
+
"@crombolo/content": "0.68.0",
|
|
41
|
+
"@crombolo/contracts": "0.68.0",
|
|
42
|
+
"@crombolo/core": "0.68.0",
|
|
43
|
+
"@crombolo/data": "0.68.0",
|
|
44
|
+
"@crombolo/extension": "0.68.0",
|
|
45
|
+
"@crombolo/render": "0.68.0",
|
|
46
|
+
"@crombolo/schema": "0.68.0",
|
|
47
|
+
"@crombolo/transfer": "0.68.0",
|
|
48
48
|
"@logtape/logtape": "^2.3.8",
|
|
49
49
|
"@opentelemetry/api": "1.10.0",
|
|
50
50
|
"@opentelemetry/context-async-hooks": "3.0.0",
|
package/src/adapters/members.ts
CHANGED
|
@@ -217,6 +217,20 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
|
|
|
217
217
|
return undefined
|
|
218
218
|
}
|
|
219
219
|
|
|
220
|
+
/**
|
|
221
|
+
* A group that doesn't exist is refused rather than dropped, so a save never
|
|
222
|
+
* leaves a member out of a group it was asked to put them in.
|
|
223
|
+
*/
|
|
224
|
+
const unknownGroups = async (groupKeys: readonly string[] | undefined) => {
|
|
225
|
+
const missing = await members.notGroups(groupKeys ?? [])
|
|
226
|
+
if (missing.length === 0) return undefined
|
|
227
|
+
return {
|
|
228
|
+
ok: false as const,
|
|
229
|
+
reason: `No member group has ${missing.length === 1 ? 'the key' : 'the keys'} ${missing.map((k) => `"${k}"`).join(', ')}.`,
|
|
230
|
+
status: 400,
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
220
234
|
const failure = (error: unknown) => {
|
|
221
235
|
if (error instanceof WriteRejectedError)
|
|
222
236
|
return { ok: false as const, reason: error.message, status: 409 }
|
|
@@ -235,7 +249,7 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
|
|
|
235
249
|
const type = await memberTypes.byKey(input.memberTypeKey)
|
|
236
250
|
if (!type)
|
|
237
251
|
return { ok: false as const, reason: 'The member type could not be found.', status: 404 }
|
|
238
|
-
const clash = await duplicate(input)
|
|
252
|
+
const clash = (await duplicate(input)) ?? (await unknownGroups(input.groupKeys))
|
|
239
253
|
if (clash) return clash
|
|
240
254
|
try {
|
|
241
255
|
const created = await members.create(
|
|
@@ -259,7 +273,7 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
|
|
|
259
273
|
async update(key, input, principal) {
|
|
260
274
|
const existing = await members.byKey(key)
|
|
261
275
|
if (!existing) return notFound()
|
|
262
|
-
const clash = await duplicate(input, key)
|
|
276
|
+
const clash = (await duplicate(input, key)) ?? (await unknownGroups(input.groupKeys))
|
|
263
277
|
if (clash) return clash
|
|
264
278
|
// Umbraco requires the current password only when the editor supplies one;
|
|
265
279
|
// an administrator changing another member's password does not.
|
package/src/approvals.ts
CHANGED
|
@@ -269,8 +269,9 @@ export function scheduleRefusal(
|
|
|
269
269
|
}
|
|
270
270
|
|
|
271
271
|
/**
|
|
272
|
-
* CI
|
|
273
|
-
* deciding, signed in, is the point
|
|
272
|
+
* CI, a command-line token and a token exchanged through a provider never
|
|
273
|
+
* decide (stories 160, 351, 364): a person deciding, signed in, is the point
|
|
274
|
+
* of an approval.
|
|
274
275
|
*/
|
|
275
276
|
function refuseUnattended(principal: Principal): void {
|
|
276
277
|
if (principal.ci) throw new ApprovalRefused('CI cannot approve or send back a request.', 403)
|
|
@@ -279,6 +280,11 @@ function refuseUnattended(principal: Principal): void {
|
|
|
279
280
|
'A command-line token cannot approve or send back a request. Decide it signed in as yourself.',
|
|
280
281
|
403,
|
|
281
282
|
)
|
|
283
|
+
if (principal.viaExchange)
|
|
284
|
+
throw new ApprovalRefused(
|
|
285
|
+
'A sign-in through another service cannot approve or send back a request. Decide it signed in as yourself.',
|
|
286
|
+
403,
|
|
287
|
+
)
|
|
282
288
|
}
|
|
283
289
|
|
|
284
290
|
export function createApprovals(options: ApprovalsOptions): Approvals {
|
package/src/cli-tokens-api.ts
CHANGED
|
@@ -96,6 +96,12 @@ export function createCliTokensApi(db: Db, tokens: CliTokens) {
|
|
|
96
96
|
}
|
|
97
97
|
if (!enabled) return refused(CLI_TOKEN_REFUSALS.off)
|
|
98
98
|
if (request.method === 'POST' && rest === '') {
|
|
99
|
+
// Story 364: a sign-in through another service lasts minutes; a token it made would not.
|
|
100
|
+
if (principal.viaExchange)
|
|
101
|
+
return refused(
|
|
102
|
+
'A sign-in through another service cannot make command-line tokens. Make one signed in as yourself.',
|
|
103
|
+
403,
|
|
104
|
+
)
|
|
99
105
|
const body = (await request.json().catch(() => ({}))) as { name?: unknown; days?: unknown }
|
|
100
106
|
const issued = await tokens.issue(
|
|
101
107
|
me.id,
|
package/src/config.ts
CHANGED
|
@@ -27,6 +27,8 @@ import { type UnrestrictedFrom, unrestrictedFrom } from './grant-policy.ts'
|
|
|
27
27
|
import { checkHost, type HostConfig } from './host-token.ts'
|
|
28
28
|
import {
|
|
29
29
|
checkIdentityProviders,
|
|
30
|
+
exchangeAudienceClashes,
|
|
31
|
+
exchangingProviders,
|
|
30
32
|
type IdentityProvider,
|
|
31
33
|
type LockedIdentityProviders,
|
|
32
34
|
} from './identity-providers.ts'
|
|
@@ -238,6 +240,12 @@ export interface CromboloConfig {
|
|
|
238
240
|
* them without the site's code. A provider's own `locked: true` does too.
|
|
239
241
|
*/
|
|
240
242
|
lockedIdentityProviders: LockedIdentityProviders
|
|
243
|
+
/**
|
|
244
|
+
* Back-office identity providers whose tokens the remote exchanges for a
|
|
245
|
+
* sign-in as the person (story 364), by id, besides those the config opts
|
|
246
|
+
* in: `CROMBOLO_REMOTE_EXCHANGE_PROVIDERS`.
|
|
247
|
+
*/
|
|
248
|
+
remoteExchangeProviders: readonly string[]
|
|
241
249
|
/**
|
|
242
250
|
* Whether the cache-busted asset path may be cached immutably. Defaults to
|
|
243
251
|
* `!development`.
|
|
@@ -1064,6 +1072,10 @@ export function loadConfig(
|
|
|
1064
1072
|
liveReload: envFlag(setting('CROMBOLO_LIVE_RELOAD')) ?? false,
|
|
1065
1073
|
allowPrivateAddresses: envFlag(setting('CROMBOLO_ALLOW_PRIVATE_ADDRESSES')) ?? false,
|
|
1066
1074
|
lockedIdentityProviders: lockedProviders(setting('CROMBOLO_LOCKED_IDENTITY_PROVIDERS')),
|
|
1075
|
+
remoteExchangeProviders: (setting('CROMBOLO_REMOTE_EXCHANGE_PROVIDERS') ?? '')
|
|
1076
|
+
.split(',')
|
|
1077
|
+
.map((id) => id.trim())
|
|
1078
|
+
.filter(Boolean),
|
|
1067
1079
|
seo: stripUndefined({
|
|
1068
1080
|
sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
|
|
1069
1081
|
indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
|
|
@@ -1132,6 +1144,11 @@ export function loadConfig(
|
|
|
1132
1144
|
)
|
|
1133
1145
|
checkIdentityProviders(merged.memberIdentityProviders, 'member')
|
|
1134
1146
|
checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
|
|
1147
|
+
for (const clash of exchangeAudienceClashes(
|
|
1148
|
+
exchangingProviders(merged.backofficeIdentityProviders, merged.remoteExchangeProviders),
|
|
1149
|
+
merged.backofficeIdentityProviders,
|
|
1150
|
+
))
|
|
1151
|
+
throw new Error(clash)
|
|
1135
1152
|
// Field by field, so a site setting its title suffix keeps the environment's switches.
|
|
1136
1153
|
merged.seo = { ...fromEnv.seo, ...stripUndefined(overrides.seo ?? {}) }
|
|
1137
1154
|
merged.remote = { ...fromEnv.remote, ...stripUndefined(overrides.remote ?? {}) }
|
|
@@ -1273,7 +1290,7 @@ export function describeDatabase(
|
|
|
1273
1290
|
}
|
|
1274
1291
|
}
|
|
1275
1292
|
|
|
1276
|
-
export const VERSION = '0.
|
|
1293
|
+
export const VERSION = '0.68.0'
|
|
1277
1294
|
|
|
1278
1295
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
1279
1296
|
/** A positive number from a setting, else the default. */
|
package/src/external-sign-in.ts
CHANGED
|
@@ -226,21 +226,27 @@ export function createExternalSignIn(
|
|
|
226
226
|
identity,
|
|
227
227
|
provider: { ...provider, name: provider.oidc.name },
|
|
228
228
|
})
|
|
229
|
+
// Story 364: what the remote's exchange finds this person by, from this issuer.
|
|
230
|
+
const named = identity.identity
|
|
231
|
+
? { value: identity.identity, issuer: provider.oidc.issuer }
|
|
232
|
+
: undefined
|
|
229
233
|
let account: ExternalAccount
|
|
230
234
|
switch (decision.kind) {
|
|
231
235
|
case 'refuse':
|
|
232
236
|
return back(decision.reason)
|
|
233
237
|
case 'signIn':
|
|
234
238
|
account = linkedAccount as ExternalAccount
|
|
239
|
+
if (named?.value !== linked?.identity?.value || named?.issuer !== linked?.identity?.issuer)
|
|
240
|
+
await logins.recordIdentity(loginProvider, identity.subject, named)
|
|
235
241
|
break
|
|
236
242
|
case 'link':
|
|
237
243
|
account = sameEmail as ExternalAccount
|
|
238
|
-
await logins.link(account.key, loginProvider, identity.subject)
|
|
244
|
+
await logins.link(account.key, loginProvider, identity.subject, named)
|
|
239
245
|
break
|
|
240
246
|
case 'create': {
|
|
241
247
|
const groups = syncedGroups(provider.defaultGroups, identity.groups, provider.groupMap)
|
|
242
248
|
account = await audience.create(identity, provider, groups)
|
|
243
|
-
await logins.link(account.key, loginProvider, identity.subject)
|
|
249
|
+
await logins.link(account.key, loginProvider, identity.subject, named)
|
|
244
250
|
break
|
|
245
251
|
}
|
|
246
252
|
}
|
|
@@ -48,6 +48,21 @@ export interface IdentityProviderOptions {
|
|
|
48
48
|
* alone. `CROMBOLO_LOCKED_IDENTITY_PROVIDERS` locks it too.
|
|
49
49
|
*/
|
|
50
50
|
locked?: boolean
|
|
51
|
+
/**
|
|
52
|
+
* Back-office providers only (story 364): lets the remote exchange this
|
|
53
|
+
* provider's tokens for a sign-in as the person they name. The token's `aud`
|
|
54
|
+
* must be `audience`, the site's origin by default, and never a sign-in
|
|
55
|
+
* client id. `CROMBOLO_REMOTE_EXCHANGE_PROVIDERS` turns it on too.
|
|
56
|
+
* `actors` names the clients a token can be issued to, by client id, for the
|
|
57
|
+
* history (story 366).
|
|
58
|
+
*/
|
|
59
|
+
remoteExchange?: boolean | RemoteExchangeOptions
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** How a provider's tokens are exchanged at the remote (stories 364 and 366). */
|
|
63
|
+
export interface RemoteExchangeOptions {
|
|
64
|
+
audience?: string
|
|
65
|
+
actors?: Readonly<Record<string, string>>
|
|
51
66
|
}
|
|
52
67
|
|
|
53
68
|
/** Which preset made a provider: what the Entra bundle looks for. */
|
|
@@ -67,6 +82,8 @@ export interface IdentityProvider {
|
|
|
67
82
|
memberType: string | undefined
|
|
68
83
|
/** Declared `locked: true`. */
|
|
69
84
|
locked: boolean
|
|
85
|
+
/** Declared `remoteExchange`: the audience its exchanged tokens carry, and the actors it names. */
|
|
86
|
+
remoteExchange: RemoteExchangeOptions | undefined
|
|
70
87
|
/** Why it cannot sign anyone in as it stands, such as a new issuer with no secret of its own. */
|
|
71
88
|
unavailable?: string
|
|
72
89
|
}
|
|
@@ -125,6 +142,12 @@ function preset(
|
|
|
125
142
|
defaultGroups: options.defaultGroups ?? [],
|
|
126
143
|
memberType: options.memberType,
|
|
127
144
|
locked: options.locked === true,
|
|
145
|
+
remoteExchange:
|
|
146
|
+
options.remoteExchange === true
|
|
147
|
+
? {}
|
|
148
|
+
: typeof options.remoteExchange === 'object'
|
|
149
|
+
? { ...options.remoteExchange }
|
|
150
|
+
: undefined,
|
|
128
151
|
}
|
|
129
152
|
}
|
|
130
153
|
|
|
@@ -145,7 +168,8 @@ export function entra(
|
|
|
145
168
|
clientId: options.clientId,
|
|
146
169
|
clientSecret: options.clientSecret,
|
|
147
170
|
},
|
|
148
|
-
|
|
171
|
+
// Entra's `sub` differs for each app registration; `oid` is the person's in the tenant.
|
|
172
|
+
{ email: 'email', name: 'name', groups: 'groups', identity: 'oid' },
|
|
149
173
|
options,
|
|
150
174
|
)
|
|
151
175
|
return { ...provider, tenantId: options.tenantId }
|
|
@@ -206,3 +230,30 @@ export function checkIdentityProviders(
|
|
|
206
230
|
}
|
|
207
231
|
return list
|
|
208
232
|
}
|
|
233
|
+
|
|
234
|
+
/** The back-office providers that exchange: those the config opts in, and those the server names. */
|
|
235
|
+
export function exchangingProviders(
|
|
236
|
+
providers: readonly IdentityProvider[],
|
|
237
|
+
fromServer: readonly string[],
|
|
238
|
+
): IdentityProvider[] {
|
|
239
|
+
return providers.flatMap((provider) => {
|
|
240
|
+
if (provider.remoteExchange) return [provider]
|
|
241
|
+
return fromServer.includes(provider.oidc.id) ? [{ ...provider, remoteExchange: {} }] : []
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Exchanging providers whose audience is a client id a sign-in uses, which the boot refuses. Pure. */
|
|
246
|
+
export function exchangeAudienceClashes(
|
|
247
|
+
exchanging: readonly IdentityProvider[],
|
|
248
|
+
backoffice: readonly IdentityProvider[],
|
|
249
|
+
): string[] {
|
|
250
|
+
return exchanging.flatMap((provider) => {
|
|
251
|
+
const audience = provider.remoteExchange?.audience
|
|
252
|
+
const clash = audience ? backoffice.find((p) => p.oidc.clientId === audience) : undefined
|
|
253
|
+
return clash
|
|
254
|
+
? [
|
|
255
|
+
`The ${provider.oidc.name} identity provider's remoteExchange audience is the client id ${clash.oidc.name} signs in with. Name the audience of an app used only for the remote, so a sign-in token can never be exchanged.`,
|
|
256
|
+
]
|
|
257
|
+
: []
|
|
258
|
+
})
|
|
259
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -143,6 +143,7 @@ export * from './remote-ci.ts'
|
|
|
143
143
|
export * from './remote-credentials.ts'
|
|
144
144
|
export * from './remote-media.ts'
|
|
145
145
|
export { FILE_NAME_HEADER } from './remote-media-library.ts'
|
|
146
|
+
export { actorOf, type ExchangeActor } from './remote-people.ts'
|
|
146
147
|
export * from './restart-pending.ts'
|
|
147
148
|
export * from './routes.ts'
|
|
148
149
|
export * from './schema.ts'
|
package/src/principal.ts
CHANGED
package/src/remote-ci.ts
CHANGED
|
@@ -30,6 +30,18 @@ export const CI_TOKEN_SECONDS = 15 * 60
|
|
|
30
30
|
/** An identity token valid for longer than this is refused. */
|
|
31
31
|
const MAX_IDENTITY_SECONDS = 60 * 60
|
|
32
32
|
|
|
33
|
+
/** The `iss` a JWT claims, unverified: only to choose who checks it. */
|
|
34
|
+
export function unverifiedIssuer(token: string): string | undefined {
|
|
35
|
+
try {
|
|
36
|
+
const body = token.split('.')[1]
|
|
37
|
+
if (!body) return undefined
|
|
38
|
+
const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as JWTPayload
|
|
39
|
+
return typeof payload.iss === 'string' ? payload.iss.replace(/\/+$/, '') : undefined
|
|
40
|
+
} catch {
|
|
41
|
+
return undefined
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
33
45
|
/** The issuers a site trusts tokens from: GitHub's, gitlab.com's, and any it names. */
|
|
34
46
|
export function trustedIssuers(extra: readonly string[] = []): string[] {
|
|
35
47
|
return [...new Set([GITHUB_ISSUER, GITLAB_ISSUER, ...extra.map((i) => i.replace(/\/+$/, ''))])]
|
|
@@ -47,6 +59,27 @@ export function usableIssuer(issuer: string): boolean {
|
|
|
47
59
|
}
|
|
48
60
|
}
|
|
49
61
|
|
|
62
|
+
/**
|
|
63
|
+
* An issuer's signing keys, from its OIDC discovery: cached per issuer, and
|
|
64
|
+
* failing closed when the issuer or its key set is not one to fetch.
|
|
65
|
+
*/
|
|
66
|
+
export function issuerKeys(): (issuer: string) => Promise<ReturnType<typeof createRemoteJWKSet>> {
|
|
67
|
+
const keySets = new Map<string, ReturnType<typeof createRemoteJWKSet>>()
|
|
68
|
+
return async (issuer) => {
|
|
69
|
+
const known = keySets.get(issuer)
|
|
70
|
+
if (known) return known
|
|
71
|
+
if (!usableIssuer(issuer)) throw new Error('the issuer is not reached over HTTPS')
|
|
72
|
+
const response = await fetch(`${issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`)
|
|
73
|
+
if (!response.ok) throw new Error(`the issuer's discovery answered ${response.status}`)
|
|
74
|
+
const { jwks_uri: jwksUri } = (await response.json()) as { jwks_uri?: string }
|
|
75
|
+
if (!jwksUri || !usableIssuer(new URL(jwksUri).origin))
|
|
76
|
+
throw new Error('the issuer names no usable key set')
|
|
77
|
+
const set = createRemoteJWKSet(new URL(jwksUri))
|
|
78
|
+
keySets.set(issuer, set)
|
|
79
|
+
return set
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
50
83
|
/** Where a CI run was, from its identity token, in the same words for either provider. */
|
|
51
84
|
export interface RunClaims {
|
|
52
85
|
repository: string
|
|
@@ -193,21 +226,7 @@ export function createCiSignIn(options: {
|
|
|
193
226
|
const rules = new RemoteTrustRepository(options.db)
|
|
194
227
|
const issuers = options.issuers.filter(usableIssuer)
|
|
195
228
|
const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
|
|
196
|
-
const
|
|
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
|
-
}
|
|
229
|
+
const keysOf = issuerKeys()
|
|
211
230
|
|
|
212
231
|
const refuse = async (request: Request, refusal: Refusal, ip: string | undefined) => {
|
|
213
232
|
limiter.fail(`ip:${ip ?? 'unknown'}`)
|
|
@@ -220,17 +239,6 @@ export function createCiSignIn(options: {
|
|
|
220
239
|
)
|
|
221
240
|
}
|
|
222
241
|
|
|
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
242
|
return {
|
|
235
243
|
issuers,
|
|
236
244
|
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A person signed in through a provider reaches the remote (story 364): a token
|
|
3
|
+
* one of the site's own back-office providers issued for the remote, exchanged
|
|
4
|
+
* (RFC 8693) at the same endpoint as CI's for a fifteen-minute sign-in as the
|
|
5
|
+
* person it names. The provider must opt in from the config or the server, the
|
|
6
|
+
* token's `aud` must be the audience it names and never a sign-in client id,
|
|
7
|
+
* and the person is found by the claim that names them across the provider's
|
|
8
|
+
* apps, as their last sign-in recorded it. docs/remote-protocol.md, "Signing
|
|
9
|
+
* in as a person through a provider".
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
type Db,
|
|
13
|
+
ExternalLoginRepository,
|
|
14
|
+
externalLoginProvider,
|
|
15
|
+
RemoteExchangeIds,
|
|
16
|
+
} from '@crombolo/data'
|
|
17
|
+
import { type JWTPayload, jwtVerify } from 'jose'
|
|
18
|
+
import { type ExternalAccount, syncedGroups } from './external-sign-in.ts'
|
|
19
|
+
import type { IdentityProvider } from './identity-providers.ts'
|
|
20
|
+
import {
|
|
21
|
+
ACCESS_TOKEN_TYPE,
|
|
22
|
+
issuerKeys,
|
|
23
|
+
JWT_TOKEN_TYPE,
|
|
24
|
+
overHttps,
|
|
25
|
+
TOKEN_EXCHANGE_GRANT,
|
|
26
|
+
unverifiedIssuer,
|
|
27
|
+
usableIssuer,
|
|
28
|
+
} from './remote-ci.ts'
|
|
29
|
+
import { AttemptLimiter } from './setup.ts'
|
|
30
|
+
|
|
31
|
+
/** How long an exchanged sign-in lasts. There is no refresh: the holder exchanges again. */
|
|
32
|
+
export const PERSON_TOKEN_SECONDS = 15 * 60
|
|
33
|
+
/** A provider's token valid for longer than this is refused; Entra's last 60 to 90 minutes. */
|
|
34
|
+
export const MAX_PROVIDER_TOKEN_SECONDS = 90 * 60
|
|
35
|
+
|
|
36
|
+
const ASYMMETRIC = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512']
|
|
37
|
+
|
|
38
|
+
const text = (claims: JWTPayload, name: string | undefined): string | undefined => {
|
|
39
|
+
const value = name ? claims[name] : undefined
|
|
40
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Text from a token for the history: control characters gone, and no longer than `limit`. */
|
|
44
|
+
const plain = (value: string, limit: number) =>
|
|
45
|
+
value
|
|
46
|
+
.replace(/\p{Cc}/gu, '')
|
|
47
|
+
.trim()
|
|
48
|
+
.slice(0, limit)
|
|
49
|
+
|
|
50
|
+
/** Who acts for the person (story 366): the tool a token names, by id and by name. */
|
|
51
|
+
export interface ExchangeActor {
|
|
52
|
+
id: string
|
|
53
|
+
name: string | null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The actor a verified token names: its `act` (RFC 8693), or else the client it
|
|
58
|
+
* was issued to (`azp`, or Entra v1's `appid`), named by the provider's `actors`.
|
|
59
|
+
* `malformed` for an `act` with no string `sub`.
|
|
60
|
+
*/
|
|
61
|
+
export function actorOf(
|
|
62
|
+
claims: JWTPayload,
|
|
63
|
+
actors: Readonly<Record<string, string>> = {},
|
|
64
|
+
): ExchangeActor | undefined | 'malformed' {
|
|
65
|
+
if (claims.act !== undefined) {
|
|
66
|
+
const act = claims.act
|
|
67
|
+
if (!act || typeof act !== 'object' || Array.isArray(act)) return 'malformed'
|
|
68
|
+
const { sub, name } = act as Record<string, unknown>
|
|
69
|
+
const id = typeof sub === 'string' ? plain(sub, 200) : ''
|
|
70
|
+
if (!id) return 'malformed'
|
|
71
|
+
const named = typeof name === 'string' ? plain(name, 100) : ''
|
|
72
|
+
return { id, name: named || (Object.hasOwn(actors, id) ? (actors[id] ?? null) : null) }
|
|
73
|
+
}
|
|
74
|
+
const client = text(claims, 'azp') ?? text(claims, 'appid')
|
|
75
|
+
const id = client ? plain(client, 200) : ''
|
|
76
|
+
if (!id) return undefined
|
|
77
|
+
return { id, name: Object.hasOwn(actors, id) ? (actors[id] ?? null) : null }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Entra's v1 issuer for a tenant, which the exchange recognises only to refuse. */
|
|
81
|
+
const entraV1Issuer = (tenantId: string) => `https://sts.windows.net/${tenantId}`
|
|
82
|
+
|
|
83
|
+
const list = (claims: JWTPayload, name: string | undefined): string[] => {
|
|
84
|
+
const value = name ? claims[name] : undefined
|
|
85
|
+
if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string')
|
|
86
|
+
return typeof value === 'string' && value !== '' ? [value] : []
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The person-side of the site the exchange needs: back-office users, as sign-in finds them. */
|
|
90
|
+
export interface ExchangeAccounts {
|
|
91
|
+
byKey(key: string): Promise<ExternalAccount | undefined>
|
|
92
|
+
byEmail(email: string): Promise<ExternalAccount | undefined>
|
|
93
|
+
setGroups(account: ExternalAccount, groups: string[]): Promise<void>
|
|
94
|
+
/** Why the person may not sign in now: locked out, disabled, or with no back-office section. */
|
|
95
|
+
refusal(key: string): Promise<string | undefined>
|
|
96
|
+
/** Signs them in as a device of their own, or says why not. */
|
|
97
|
+
signIn(
|
|
98
|
+
key: string,
|
|
99
|
+
provider: { id: string; name: string },
|
|
100
|
+
seconds: number,
|
|
101
|
+
ip: string | undefined,
|
|
102
|
+
actor: ExchangeActor | undefined,
|
|
103
|
+
): Promise<{ accessToken: string } | { refused: string }>
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type PeopleExchangeOutcome =
|
|
107
|
+
| {
|
|
108
|
+
ok: true
|
|
109
|
+
provider: IdentityProvider
|
|
110
|
+
account: ExternalAccount
|
|
111
|
+
actor: ExchangeActor | undefined
|
|
112
|
+
}
|
|
113
|
+
| { ok: false; reason: string; provider?: IdentityProvider }
|
|
114
|
+
|
|
115
|
+
export interface PeopleExchange {
|
|
116
|
+
/** What the discovery document says, when any provider exchanges. */
|
|
117
|
+
discovery(origin: string, api: string): Promise<Record<string, unknown> | undefined>
|
|
118
|
+
/** Whether a token's issuer is an exchanging provider's, so this exchange answers it. */
|
|
119
|
+
handles(issuer: string): Promise<boolean>
|
|
120
|
+
exchange(request: Request, url: URL, ip: string | undefined): Promise<Response>
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function createPeopleExchange(options: {
|
|
124
|
+
db: Db
|
|
125
|
+
/** The providers that exchange, as declared. */
|
|
126
|
+
providers: readonly IdentityProvider[]
|
|
127
|
+
/** Every back-office provider, as declared: none of their client ids is ever an audience. */
|
|
128
|
+
backoffice: readonly IdentityProvider[]
|
|
129
|
+
/** A provider as sign-in uses it, with an administrator's overrides (033). */
|
|
130
|
+
resolve(provider: IdentityProvider): Promise<IdentityProvider>
|
|
131
|
+
accounts: ExchangeAccounts
|
|
132
|
+
/** Told of each exchange, accepted or refused, for the audit log. */
|
|
133
|
+
onExchange(outcome: PeopleExchangeOutcome, request: Request): Promise<void>
|
|
134
|
+
}): PeopleExchange {
|
|
135
|
+
const logins = new ExternalLoginRepository(options.db)
|
|
136
|
+
const ids = new RemoteExchangeIds(options.db)
|
|
137
|
+
const keysOf = issuerKeys()
|
|
138
|
+
const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
|
|
139
|
+
|
|
140
|
+
const effective = () =>
|
|
141
|
+
Promise.all(
|
|
142
|
+
options.providers.map(async (declared) => {
|
|
143
|
+
const provider = await options.resolve(declared).catch(() => declared)
|
|
144
|
+
return { ...provider, remoteExchange: declared.remoteExchange }
|
|
145
|
+
}),
|
|
146
|
+
)
|
|
147
|
+
const issuerOf = (provider: IdentityProvider) => provider.oidc.issuer.replace(/\/+$/, '')
|
|
148
|
+
const audienceOf = (provider: IdentityProvider, origin: string) =>
|
|
149
|
+
provider.remoteExchange?.audience ?? origin
|
|
150
|
+
const usable = (provider: IdentityProvider) =>
|
|
151
|
+
!provider.unavailable && usableIssuer(issuerOf(provider))
|
|
152
|
+
/** The exchanging provider a token's issuer is, and whether it came as Entra's v1 token. */
|
|
153
|
+
const providerFor = async (issuer: string | undefined) => {
|
|
154
|
+
if (!issuer) return undefined
|
|
155
|
+
const bare = issuer.replace(/\/+$/, '')
|
|
156
|
+
for (const p of await effective()) {
|
|
157
|
+
if (!usable(p)) continue
|
|
158
|
+
if (issuerOf(p) === issuer) return { provider: p, v1: false }
|
|
159
|
+
if (p.kind === 'entra' && p.tenantId && entraV1Issuer(p.tenantId) === bare)
|
|
160
|
+
return { provider: p, v1: true }
|
|
161
|
+
}
|
|
162
|
+
return undefined
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const json = (body: unknown, status: number) =>
|
|
166
|
+
Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
|
|
167
|
+
|
|
168
|
+
const refuse = async (
|
|
169
|
+
request: Request,
|
|
170
|
+
ip: string | undefined,
|
|
171
|
+
reason: string,
|
|
172
|
+
provider?: IdentityProvider,
|
|
173
|
+
) => {
|
|
174
|
+
limiter.fail(`ip:${ip ?? 'unknown'}`)
|
|
175
|
+
if (provider) limiter.fail(`issuer:${issuerOf(provider)}`)
|
|
176
|
+
await options.onExchange({ ok: false, reason, provider }, request)
|
|
177
|
+
// The same answer whatever went wrong: the audit log has the reason, the caller does not.
|
|
178
|
+
return json(
|
|
179
|
+
{ error: 'invalid_grant', error_description: 'The identity token was not accepted.' },
|
|
180
|
+
400,
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The account the token names: by its recorded identity, else by email where allowed. */
|
|
185
|
+
const accountFor = async (
|
|
186
|
+
provider: IdentityProvider,
|
|
187
|
+
issuer: string,
|
|
188
|
+
claims: JWTPayload,
|
|
189
|
+
): Promise<ExternalAccount | string> => {
|
|
190
|
+
const loginProvider = externalLoginProvider('user', provider.oidc.id)
|
|
191
|
+
const value = text(claims, provider.oidc.claims.identity ?? 'sub')
|
|
192
|
+
if (!value) return 'the token names no person'
|
|
193
|
+
const linked = await logins.findByIdentity(loginProvider, { value, issuer })
|
|
194
|
+
if (linked) {
|
|
195
|
+
const account = await options.accounts.byKey(linked.ownerKey)
|
|
196
|
+
return account ?? 'the person it is linked to no longer exists'
|
|
197
|
+
}
|
|
198
|
+
// Story 364, D5: never an account made, and a link is only ever made by a sign-in.
|
|
199
|
+
const email = text(claims, provider.oidc.claims.email)?.toLowerCase()
|
|
200
|
+
const verified = claims.email_verified === true || claims.email_verified === 'true'
|
|
201
|
+
if (!provider.linkByEmail || !email || !(verified || provider.emailsVerified))
|
|
202
|
+
return 'nobody is linked to this person; they sign in to the back office once first'
|
|
203
|
+
const sameEmail = await options.accounts.byEmail(email)
|
|
204
|
+
if (!sameEmail) return 'nobody here has their email address, and an exchange makes no account'
|
|
205
|
+
const links = await logins.forOwner(sameEmail.key)
|
|
206
|
+
if (links.some((l) => l.loginProvider === loginProvider))
|
|
207
|
+
return 'the account with their email is linked to someone else at this provider'
|
|
208
|
+
return sameEmail
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
async discovery(origin, api) {
|
|
213
|
+
const providers = (await effective()).filter(usable)
|
|
214
|
+
if (providers.length === 0) return undefined
|
|
215
|
+
return {
|
|
216
|
+
tokenExchange: `${api}/token`,
|
|
217
|
+
grantType: TOKEN_EXCHANGE_GRANT,
|
|
218
|
+
subjectTokenType: JWT_TOKEN_TYPE,
|
|
219
|
+
audience: origin,
|
|
220
|
+
providers: providers.map((p) => ({
|
|
221
|
+
id: p.oidc.id,
|
|
222
|
+
name: p.oidc.name,
|
|
223
|
+
issuer: issuerOf(p),
|
|
224
|
+
audience: audienceOf(p, origin),
|
|
225
|
+
})),
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
async handles(issuer) {
|
|
230
|
+
return (await providerFor(issuer)) !== undefined
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async exchange(request, url, ip) {
|
|
234
|
+
if (!overHttps(request, url))
|
|
235
|
+
return json(
|
|
236
|
+
{ error: 'invalid_request', error_description: 'Signing in from elsewhere needs HTTPS.' },
|
|
237
|
+
400,
|
|
238
|
+
)
|
|
239
|
+
if (limiter.blocked(`ip:${ip ?? 'unknown'}`))
|
|
240
|
+
return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
|
|
241
|
+
const form = new URLSearchParams(await request.text())
|
|
242
|
+
if (form.get('grant_type') !== TOKEN_EXCHANGE_GRANT)
|
|
243
|
+
return json({ error: 'unsupported_grant_type' }, 400)
|
|
244
|
+
if (form.get('subject_token_type') !== JWT_TOKEN_TYPE)
|
|
245
|
+
return json({ error: 'invalid_request', error_description: 'A JWT is expected.' }, 400)
|
|
246
|
+
const token = form.get('subject_token') ?? ''
|
|
247
|
+
|
|
248
|
+
const issuer = unverifiedIssuer(token)
|
|
249
|
+
const found = await providerFor(issuer)
|
|
250
|
+
if (!issuer || !found)
|
|
251
|
+
return refuse(request, ip, 'an issuer that is not an exchanging provider')
|
|
252
|
+
const { provider } = found
|
|
253
|
+
if (limiter.blocked(`issuer:${issuerOf(provider)}`))
|
|
254
|
+
return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
|
|
255
|
+
if (found.v1)
|
|
256
|
+
return refuse(
|
|
257
|
+
request,
|
|
258
|
+
ip,
|
|
259
|
+
'it is an Entra v1 token: set requestedAccessTokenVersion to 2 in the manifest of the app it was issued for',
|
|
260
|
+
provider,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
const audience = audienceOf(provider, url.origin)
|
|
264
|
+
const signInClients = await Promise.all(
|
|
265
|
+
options.backoffice.map(
|
|
266
|
+
async (p) => (await options.resolve(p).catch(() => p)).oidc.clientId,
|
|
267
|
+
),
|
|
268
|
+
)
|
|
269
|
+
if (signInClients.includes(audience))
|
|
270
|
+
return refuse(request, ip, 'its audience is a sign-in client id', provider)
|
|
271
|
+
|
|
272
|
+
let claims: JWTPayload
|
|
273
|
+
try {
|
|
274
|
+
;({ payload: claims } = await jwtVerify(token, await keysOf(issuer), {
|
|
275
|
+
issuer,
|
|
276
|
+
audience,
|
|
277
|
+
algorithms: ASYMMETRIC,
|
|
278
|
+
requiredClaims: ['exp', 'iat'],
|
|
279
|
+
}))
|
|
280
|
+
} catch (error) {
|
|
281
|
+
return refuse(
|
|
282
|
+
request,
|
|
283
|
+
ip,
|
|
284
|
+
`the token did not verify: ${error instanceof Error ? error.message : String(error)}`,
|
|
285
|
+
provider,
|
|
286
|
+
)
|
|
287
|
+
}
|
|
288
|
+
if (claims.nonce !== undefined)
|
|
289
|
+
return refuse(request, ip, 'it is a sign-in ID token, which carries a nonce', provider)
|
|
290
|
+
const exp = claims.exp as number
|
|
291
|
+
if (exp - (claims.iat as number) > MAX_PROVIDER_TOKEN_SECONDS)
|
|
292
|
+
return refuse(request, ip, 'the token is valid for too long', provider)
|
|
293
|
+
// Entra calls its one-time id `uti`.
|
|
294
|
+
const tokenId = text(claims, 'jti') ?? text(claims, 'uti')
|
|
295
|
+
if (!tokenId) return refuse(request, ip, 'the token has no one-time id', provider)
|
|
296
|
+
if (!(await ids.spend(issuer, tokenId, new Date(exp * 1000))))
|
|
297
|
+
return refuse(request, ip, 'the token was already used', provider)
|
|
298
|
+
const actor = actorOf(claims, provider.remoteExchange?.actors)
|
|
299
|
+
if (actor === 'malformed')
|
|
300
|
+
return refuse(request, ip, 'its act claim names no actor by a string sub', provider)
|
|
301
|
+
|
|
302
|
+
const person = await accountFor(provider, issuer, claims)
|
|
303
|
+
if (typeof person === 'string') return refuse(request, ip, person, provider)
|
|
304
|
+
const refusal = await options.accounts.refusal(person.key)
|
|
305
|
+
if (refusal) return refuse(request, ip, refusal, provider)
|
|
306
|
+
|
|
307
|
+
let account = person
|
|
308
|
+
if (Object.keys(provider.groupMap).length > 0) {
|
|
309
|
+
const groups = syncedGroups(
|
|
310
|
+
account.groups,
|
|
311
|
+
list(claims, provider.oidc.claims.groups),
|
|
312
|
+
provider.groupMap,
|
|
313
|
+
)
|
|
314
|
+
if (groups.join('\n') !== account.groups.join('\n')) {
|
|
315
|
+
await options.accounts.setGroups(account, groups)
|
|
316
|
+
account = { ...account, groups }
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const signedIn = await options.accounts.signIn(
|
|
320
|
+
account.key,
|
|
321
|
+
{ id: provider.oidc.id, name: provider.oidc.name },
|
|
322
|
+
PERSON_TOKEN_SECONDS,
|
|
323
|
+
ip,
|
|
324
|
+
actor,
|
|
325
|
+
)
|
|
326
|
+
if ('refused' in signedIn) return refuse(request, ip, signedIn.refused, provider)
|
|
327
|
+
await options.onExchange({ ok: true, provider, account, actor }, request)
|
|
328
|
+
return json(
|
|
329
|
+
{
|
|
330
|
+
access_token: signedIn.accessToken,
|
|
331
|
+
issued_token_type: ACCESS_TOKEN_TYPE,
|
|
332
|
+
token_type: 'Bearer',
|
|
333
|
+
expires_in: PERSON_TOKEN_SECONDS,
|
|
334
|
+
},
|
|
335
|
+
200,
|
|
336
|
+
)
|
|
337
|
+
},
|
|
338
|
+
}
|
|
339
|
+
}
|
package/src/remote.ts
CHANGED
|
@@ -71,10 +71,11 @@ import { type MediaStore, streamOf } from './media-store.ts'
|
|
|
71
71
|
import { siteMemberPorts } from './member-admin.ts'
|
|
72
72
|
import { describeProvenance, provenanceProblem, verifyProvenance } from './provenance.ts'
|
|
73
73
|
import { createBackgroundJobRoutes } from './remote-background-jobs.ts'
|
|
74
|
-
import { createCiSignIn, readRuleInput, trustedIssuers } from './remote-ci.ts'
|
|
74
|
+
import { createCiSignIn, readRuleInput, trustedIssuers, unverifiedIssuer } from './remote-ci.ts'
|
|
75
75
|
import { createExtensionActivityRoutes } from './remote-extension-activity.ts'
|
|
76
76
|
import { createMediaLibraryRoutes } from './remote-media-library.ts'
|
|
77
77
|
import { createMemberRoutes } from './remote-members.ts'
|
|
78
|
+
import type { PeopleExchange } from './remote-people.ts'
|
|
78
79
|
import { createUndoRoutes } from './remote-undo.ts'
|
|
79
80
|
import { createUserRoutes } from './remote-users.ts'
|
|
80
81
|
import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
|
|
@@ -86,7 +87,7 @@ import type { UserPorts } from './user-admin.ts'
|
|
|
86
87
|
|
|
87
88
|
export const REMOTE_PROTOCOL_VERSION = '1'
|
|
88
89
|
export { REMOTE_DISCOVERY_PATH }
|
|
89
|
-
export const REMOTE_API_PATH = '/
|
|
90
|
+
export const REMOTE_API_PATH = '/crombolo/remote/v1'
|
|
90
91
|
|
|
91
92
|
/** How long a finished job's file stays downloadable, and its row with it. */
|
|
92
93
|
const JOB_FILE_SECONDS = 60 * 60
|
|
@@ -102,6 +103,8 @@ export interface RemoteOptions {
|
|
|
102
103
|
db: Db
|
|
103
104
|
config: CromboloConfig
|
|
104
105
|
authenticate(request: Request): Promise<Principal | undefined>
|
|
106
|
+
/** Story 364: a back-office provider's token exchanged for a sign-in as the person it names. */
|
|
107
|
+
people?: PeopleExchange
|
|
105
108
|
/**
|
|
106
109
|
* Told once a push has landed, so this node's published cache is rebuilt: the
|
|
107
110
|
* import's cache instruction carries this node's id, and a node skips its own.
|
|
@@ -223,7 +226,7 @@ export function createRemote(options: RemoteOptions): Remote {
|
|
|
223
226
|
// Under the back office, as the editor's own API calls are; a command line
|
|
224
227
|
// follows these addresses rather than building its own.
|
|
225
228
|
const managementApi = managementApiPath(config.backOfficePath.replace(/\/+$/, ''))
|
|
226
|
-
const discovery = (origin: string) => ({
|
|
229
|
+
const discovery = async (origin: string) => ({
|
|
227
230
|
protocol: 'crombolo-remote',
|
|
228
231
|
versions: [REMOTE_PROTOCOL_VERSION],
|
|
229
232
|
// The bundle formats this site reads, oldest and newest (story 306).
|
|
@@ -237,6 +240,11 @@ export function createRemote(options: RemoteOptions): Remote {
|
|
|
237
240
|
grantType: DEVICE_CODE_GRANT,
|
|
238
241
|
// Story 160: a CI job's identity token, exchanged for a token acting as a trust rule.
|
|
239
242
|
ci: ci.discovery(origin, `${origin}${REMOTE_API_PATH}`),
|
|
243
|
+
// Story 364: a person's token from one of this site's own back-office providers.
|
|
244
|
+
...(await (async () => {
|
|
245
|
+
const people = await options.people?.discovery(origin, `${origin}${REMOTE_API_PATH}`)
|
|
246
|
+
return people ? { people } : {}
|
|
247
|
+
})()),
|
|
240
248
|
},
|
|
241
249
|
capabilities: [
|
|
242
250
|
...(atLeast('content') ? ['bundle-apply'] : []),
|
|
@@ -1297,6 +1305,12 @@ export function createRemote(options: RemoteOptions): Remote {
|
|
|
1297
1305
|
title: 'A command-line token cannot approve pushes',
|
|
1298
1306
|
detail: 'Approve or decline it signed in as yourself.',
|
|
1299
1307
|
})
|
|
1308
|
+
if (principal.viaExchange)
|
|
1309
|
+
return problem(403, {
|
|
1310
|
+
code: 'exchange-cannot-approve',
|
|
1311
|
+
title: 'A sign-in through another service cannot approve pushes',
|
|
1312
|
+
detail: 'Approve or decline it signed in as yourself.',
|
|
1313
|
+
})
|
|
1300
1314
|
const job = await jobs.get(id)
|
|
1301
1315
|
if (job?.kind !== 'push')
|
|
1302
1316
|
return problem(404, { code: 'not-found', title: 'There is no such push' })
|
|
@@ -1513,16 +1527,31 @@ export function createRemote(options: RemoteOptions): Remote {
|
|
|
1513
1527
|
if (pathname === REMOTE_DISCOVERY_PATH) {
|
|
1514
1528
|
if (!settings.enabled) return undefined
|
|
1515
1529
|
return request.method === 'GET'
|
|
1516
|
-
? Response.json(discovery(url.origin), {
|
|
1530
|
+
? Response.json(await discovery(url.origin), {
|
|
1531
|
+
headers: { 'cache-control': 'no-store' },
|
|
1532
|
+
})
|
|
1517
1533
|
: new Response(null, { status: 405 })
|
|
1518
1534
|
}
|
|
1519
1535
|
if (!pathname.startsWith(`${REMOTE_API_PATH}/`)) return undefined
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
if (pathname === `${REMOTE_API_PATH}/token`)
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1536
|
+
const notEnabled = () =>
|
|
1537
|
+
problem(404, { code: 'not-enabled', title: 'This site is not a remote' })
|
|
1538
|
+
if (pathname === `${REMOTE_API_PATH}/token`) {
|
|
1539
|
+
const people = options.people
|
|
1540
|
+
if (!settings.enabled && !people) return notEnabled()
|
|
1541
|
+
if (request.method !== 'POST') return new Response(null, { status: 405 })
|
|
1542
|
+
const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
|
|
1543
|
+
// One endpoint for both: the token's issuer says whether it is CI's or a person's.
|
|
1544
|
+
// A person's exchange answers with the remote off too (story 365); CI's does not.
|
|
1545
|
+
const issuer = people
|
|
1546
|
+
? unverifiedIssuer(
|
|
1547
|
+
new URLSearchParams(await request.clone().text()).get('subject_token') ?? '',
|
|
1548
|
+
)
|
|
1549
|
+
: undefined
|
|
1550
|
+
if (people && issuer && (await people.handles(issuer)))
|
|
1551
|
+
return people.exchange(request, url, ip)
|
|
1552
|
+
return settings.enabled ? ci.exchange(request, url, ip) : notEnabled()
|
|
1553
|
+
}
|
|
1554
|
+
if (!settings.enabled) return notEnabled()
|
|
1526
1555
|
// A CI token is good here and nowhere else; a person's is the back office's own.
|
|
1527
1556
|
const principal = (await ci.principalOf(request)) ?? (await options.authenticate(request))
|
|
1528
1557
|
if (!principal)
|
package/src/server.ts
CHANGED
|
@@ -89,6 +89,7 @@ import {
|
|
|
89
89
|
} from '@crombolo/core'
|
|
90
90
|
import {
|
|
91
91
|
appendCacheInstruction,
|
|
92
|
+
byActor,
|
|
92
93
|
currentAuditContext,
|
|
93
94
|
type Db,
|
|
94
95
|
ensureFormLibraryTypes,
|
|
@@ -108,6 +109,7 @@ import {
|
|
|
108
109
|
readUrlOptions,
|
|
109
110
|
searchProvidersOf,
|
|
110
111
|
TransferRunRepository,
|
|
112
|
+
UserRepository,
|
|
111
113
|
type WritesPaused,
|
|
112
114
|
withAuditContext,
|
|
113
115
|
} from '@crombolo/data'
|
|
@@ -247,6 +249,7 @@ import {
|
|
|
247
249
|
import { principalOf } from './principal.ts'
|
|
248
250
|
import { provenanceProblem } from './provenance.ts'
|
|
249
251
|
import { createRemote, may, type RestartOutcome } from './remote.ts'
|
|
252
|
+
import { createPeopleExchange } from './remote-people.ts'
|
|
250
253
|
import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
|
|
251
254
|
import { SiteAssets } from './site-assets.ts'
|
|
252
255
|
import { unknownHostProvided } from './site-file.ts'
|
|
@@ -279,6 +282,7 @@ import { backofficeAudience } from './backoffice-external.ts'
|
|
|
279
282
|
import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
|
|
280
283
|
import { createExternalSignIn } from './external-sign-in.ts'
|
|
281
284
|
import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
|
|
285
|
+
import { exchangingProviders } from './identity-providers.ts'
|
|
282
286
|
import {
|
|
283
287
|
builtIslandFile,
|
|
284
288
|
devServerIslandManifest,
|
|
@@ -678,6 +682,15 @@ export async function createServer(
|
|
|
678
682
|
const principal = await principalFrom(identity)
|
|
679
683
|
// Story 314: what this session writes says whose groups it was seen as.
|
|
680
684
|
const context = currentAuditContext()
|
|
685
|
+
// Story 364: and that it came by a token exchanged through a provider.
|
|
686
|
+
if (context && identity.exchangedThrough)
|
|
687
|
+
context.exchange = {
|
|
688
|
+
userKey: normaliseUuid(principal.id),
|
|
689
|
+
provider:
|
|
690
|
+
config.backofficeIdentityProviders.find((p) => p.oidc.id === identity.exchangedThrough)
|
|
691
|
+
?.oidc.name ?? identity.exchangedThrough,
|
|
692
|
+
...(identity.exchangedActor ? { actor: identity.exchangedActor } : {}),
|
|
693
|
+
}
|
|
681
694
|
if (context && principal.viewingAs)
|
|
682
695
|
context.viewing = {
|
|
683
696
|
userKey: normaliseUuid(principal.id),
|
|
@@ -919,10 +932,101 @@ export async function createServer(
|
|
|
919
932
|
source: 'request',
|
|
920
933
|
...clientAddress(request),
|
|
921
934
|
})
|
|
935
|
+
// Story 364: a back-office provider's token exchanged at the remote for a sign-in as the person.
|
|
936
|
+
const exchanging = exchangingProviders(
|
|
937
|
+
config.backofficeIdentityProviders,
|
|
938
|
+
config.remoteExchangeProviders,
|
|
939
|
+
)
|
|
940
|
+
for (const id of config.remoteExchangeProviders)
|
|
941
|
+
if (!config.backofficeIdentityProviders.some((p) => p.oidc.id === id))
|
|
942
|
+
log.warning(
|
|
943
|
+
'CROMBOLO_REMOTE_EXCHANGE_PROVIDERS names {id}, which the config declares no back-office identity provider as.',
|
|
944
|
+
{ id },
|
|
945
|
+
)
|
|
946
|
+
if (exchanging.length > 0)
|
|
947
|
+
log.info(
|
|
948
|
+
config.remote.enabled
|
|
949
|
+
? 'The remote exchanges tokens from {providers}'
|
|
950
|
+
: "The remote is off, and its token endpoint answers only {providers}'s exchange for a person",
|
|
951
|
+
{ providers: exchanging.map((p) => p.oidc.id).join(', ') },
|
|
952
|
+
)
|
|
953
|
+
const people =
|
|
954
|
+
exchanging.length === 0
|
|
955
|
+
? undefined
|
|
956
|
+
: (() => {
|
|
957
|
+
const users = new UserRepository(db)
|
|
958
|
+
const accounts = backofficeAudience(db, {
|
|
959
|
+
auth,
|
|
960
|
+
providers: exchanging,
|
|
961
|
+
backOfficePath: paths.backOfficePath,
|
|
962
|
+
sessionCookie: () => '',
|
|
963
|
+
})
|
|
964
|
+
const overrides = new IdentityProviderOverrides(
|
|
965
|
+
db,
|
|
966
|
+
config.secretKey,
|
|
967
|
+
config.lockedIdentityProviders,
|
|
968
|
+
)
|
|
969
|
+
return createPeopleExchange({
|
|
970
|
+
db,
|
|
971
|
+
providers: exchanging,
|
|
972
|
+
backoffice: config.backofficeIdentityProviders,
|
|
973
|
+
resolve: (provider) => overrides.apply('user', provider),
|
|
974
|
+
accounts: {
|
|
975
|
+
byKey: accounts.byKey,
|
|
976
|
+
byEmail: accounts.byEmail,
|
|
977
|
+
setGroups: accounts.setGroups,
|
|
978
|
+
refusal: async (key) => {
|
|
979
|
+
const user = await users.byKey(key)
|
|
980
|
+
if (!user) return 'the person no longer exists'
|
|
981
|
+
if (user.isLockedOut) return 'the person is locked out'
|
|
982
|
+
if (!user.isApproved) return 'the person is disabled or not yet approved'
|
|
983
|
+
const identity = await auth.identityOf(user.id)
|
|
984
|
+
return (identity?.allowedSections.length ?? 0) > 0
|
|
985
|
+
? undefined
|
|
986
|
+
: 'the person has no access to the back office'
|
|
987
|
+
},
|
|
988
|
+
signIn: async (key, provider, seconds, ip, actor) => {
|
|
989
|
+
const user = await users.byKey(key)
|
|
990
|
+
if (!user) return { refused: 'the person no longer exists' }
|
|
991
|
+
const result = await auth.signInByExchange(
|
|
992
|
+
user.userName,
|
|
993
|
+
provider,
|
|
994
|
+
seconds,
|
|
995
|
+
ip,
|
|
996
|
+
actor,
|
|
997
|
+
)
|
|
998
|
+
if (result.status === 'success') return { accessToken: result.accessToken }
|
|
999
|
+
return {
|
|
1000
|
+
refused:
|
|
1001
|
+
result.reason === 'lockedOut'
|
|
1002
|
+
? 'the person is locked out'
|
|
1003
|
+
: 'the person is disabled or not yet approved',
|
|
1004
|
+
}
|
|
1005
|
+
},
|
|
1006
|
+
},
|
|
1007
|
+
onExchange: (outcome, request) =>
|
|
1008
|
+
recordAudit(db, {
|
|
1009
|
+
category: 'sign-in',
|
|
1010
|
+
action: outcome.ok ? 'RemoteExchangeSignIn' : 'RemoteExchangeSignInRefused',
|
|
1011
|
+
source: 'request',
|
|
1012
|
+
userKey: outcome.ok ? outcome.account.key : null,
|
|
1013
|
+
userName: null,
|
|
1014
|
+
entityType: 'User',
|
|
1015
|
+
entityKey: outcome.ok ? outcome.account.key : null,
|
|
1016
|
+
entityName: outcome.ok ? outcome.account.email : null,
|
|
1017
|
+
detail: outcome.ok
|
|
1018
|
+
? `Signed in through ${outcome.provider.oidc.name}${byActor(outcome.actor)}, by exchange at the remote`
|
|
1019
|
+
: `Refused${outcome.provider ? ` through ${outcome.provider.oidc.name}` : ''}: ${outcome.reason}`,
|
|
1020
|
+
actor: outcome.ok ? (outcome.actor ?? null) : null,
|
|
1021
|
+
...clientAddress(request),
|
|
1022
|
+
}),
|
|
1023
|
+
})
|
|
1024
|
+
})()
|
|
922
1025
|
const remote = createRemote({
|
|
923
1026
|
db,
|
|
924
1027
|
config,
|
|
925
1028
|
authenticate,
|
|
1029
|
+
people,
|
|
926
1030
|
bundles: bundleAdmin,
|
|
927
1031
|
operations: core.operations,
|
|
928
1032
|
nodeState: schema.nodeState,
|
|
@@ -2628,6 +2732,8 @@ export async function createServer(
|
|
|
2628
2732
|
if (pathname === viewAsPath) {
|
|
2629
2733
|
const identity = await identify(request)
|
|
2630
2734
|
if (!identity) return new Response('Unauthorized', { status: 401 })
|
|
2735
|
+
// Story 364: a token exchanged through a provider never sees as anyone else.
|
|
2736
|
+
if (identity.exchangedThrough) return new Response('Forbidden', { status: 403 })
|
|
2631
2737
|
return viewAs.handle(request, identity, clientAddress(request))
|
|
2632
2738
|
}
|
|
2633
2739
|
|
package/src/settings.ts
CHANGED
|
@@ -284,6 +284,13 @@ const DECLARED = [
|
|
|
284
284
|
description:
|
|
285
285
|
"Identity providers nobody can change in the back office, by id, separated by commas, or `all`: they sign in by the site's configuration alone. A provider declared `locked: true` is locked too.",
|
|
286
286
|
},
|
|
287
|
+
{
|
|
288
|
+
env: 'CROMBOLO_REMOTE_EXCHANGE_PROVIDERS',
|
|
289
|
+
kind: 'list',
|
|
290
|
+
section: 'Sign-in and secrets',
|
|
291
|
+
description:
|
|
292
|
+
"Back-office identity providers, by id, separated by commas, whose tokens the remote exchanges for a sign-in as the person they name, besides those the site's configuration opts in.",
|
|
293
|
+
},
|
|
287
294
|
{
|
|
288
295
|
env: 'CROMBOLO_SECRET_KEY',
|
|
289
296
|
kind: 'string',
|
package/src/telemetry.ts
CHANGED
|
@@ -361,6 +361,7 @@ export function withTraceHeaders(headers: Record<string, string>): Record<string
|
|
|
361
361
|
export function routeOf(pathname: string, backOfficePath: string): string {
|
|
362
362
|
if (pathname === '/health') return '/health'
|
|
363
363
|
if (pathname.startsWith('/umbraco/delivery/api/')) return '/umbraco/delivery/api/*'
|
|
364
|
+
if (pathname.startsWith('/crombolo/remote/v1/')) return '/crombolo/remote/v1/*'
|
|
364
365
|
if (pathname.startsWith(`${backOfficePath}/management/api/`))
|
|
365
366
|
return `${backOfficePath}/management/api/*`
|
|
366
367
|
if (pathname === backOfficePath || pathname.startsWith(`${backOfficePath}/`))
|