diff --git a/.changeset/authorize-gate-judges-every-client-id.md b/.changeset/authorize-gate-judges-every-client-id.md new file mode 100644 index 00000000000..3498004a8a9 --- /dev/null +++ b/.changeset/authorize-gate-judges-every-client-id.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(auth)!: the environment-access gate on `/oauth2/authorize` judges every client the request names, from the query and the body + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` and no hand-written page under `content/docs/**` teaches `oidcAuthorizeGate` or the authorize endpoint's environment-access gate. + + + +**BREAKING** for a deployment that sets `oidcAuthorizeGate` (the ADR-0069 D5.1 environment-access gate; open editions and self-host leave it unset). The gate on `/oauth2/authorize` now judges every client the request names: the query's `client_id` and the body's `client_id`, each a string or an array, de-duplicated ("each a string or an array" describes what the gate collects from the parsed request, not a promise that every transport accepts both forms). If any one of them is refused, the request is refused with the existing refusal: `403 ENV_ACCESS_DENIED` for a fetch or an API client, and for a browser the redirect or the readable page it already gets. A request that names no client anywhere is unchanged, and so is an unauthenticated request, which still goes on to sign in. + +Who moves: only a host whose `oidcAuthorizeGate` assumes it is called at most once per request. It can now be called once for each distinct client the request names, and the first refusal ends the request. The callback's signature, `({ userId, clientId }) => boolean | Promise`, does not change. + +Unchanged: a deployment with no `oidcAuthorizeGate`; a `GET` naming one client; the passes that resume an authorization (sign-in, `/oauth2/consent`, `/oauth2/continue`), which the gate already judged; and the refusal's code, status, message and delivery. diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index 2a0dfda14fb..169dbb80e0f 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -89,6 +89,29 @@ import { ssoDiscoveryCompanionContext } from './sso-discovery-companion-origins. import { snapshotRoleChangeGrants, UPDATE_MEMBER_ROLE_PATH } from './role-change-granted-set.js'; import { refuseVisitorResendWithoutLiveTransport } from './visitor-verification-resend.js'; +/** + * Every client an `/oauth2/authorize` request names, for the ADR-0069 D5.1 + * environment-access gate: the query's `client_id` first, then the body's, + * each a string or an array of them, de-duplicated in that order. An empty + * value names nothing; any other present value is judged by its string form + * rather than skipped, so the gate is never asked about fewer clients than + * the request names. + */ +function authorizeRequestClientIds(ctx: any): string[] { + const named = new Set(); + const collect = (source: unknown): void => { + if (typeof source !== 'object' || source === null || Array.isArray(source)) return; + const value = (source as Record).client_id; + for (const one of Array.isArray(value) ? value : [value]) { + if (one === undefined || one === null || one === '') continue; + named.add(String(one)); + } + }; + collect(ctx?.query); + collect(ctx?.body); + return [...named]; +} + /** * [#33203] The self-service reset doors a cloud-managed environment refuses: * the two that set the password and the two that send their link or code. @@ -550,9 +573,14 @@ export async function globalBeforeHook( // read as unauthenticated and this env-access check never evaluated // at all. Two resolution sites are what let them diverge, so the fix // is to delete one, not to correct it in place. + // + // The gate judges EVERY client the request names — the query's and the + // body's `client_id`, each a string or an array, de-duplicated + // ({@link authorizeRequestClientIds}) — and refuses if any one of them + // is refused. A request that names no client anywhere is not judged here. if (ctx?.path === '/oauth2/authorize' && this.config.oidcAuthorizeGate) { - const clientId = ctx?.query?.client_id; - if (clientId) { + const clientIds = authorizeRequestClientIds(ctx); + if (clientIds.length > 0) { const actor = await this.resolveActor(ctx); // Unauthenticated → fall through, per the contract above. Only an // AUTHENTICATED subject is gated here. `resolveActor` also returns @@ -560,10 +588,11 @@ export async function globalBeforeHook( // D5.1 host contract is `(userId, clientId)` and the control plane // derives org membership / app assignment from the user itself. if (actor?.userId) { - const allowed = await this.config.oidcAuthorizeGate({ - userId: actor.userId, - clientId: String(clientId), - }); + let allowed = true; + for (const clientId of clientIds) { + allowed = await this.config.oidcAuthorizeGate({ userId: actor.userId, clientId }); + if (!allowed) break; + } if (!allowed) { // The refusal, delivered by who is asking (`oauth-authorize-refusal.ts`): // the `403` envelope for a fetch or an API client, unchanged; for a diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 719dd67fda4..9affdd9d3aa 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -960,7 +960,10 @@ export interface AuthManagerOptions extends Partial { * D5.1 — OIDC OP authorization gate (cloud-as-IdP app-assignment). * When set, it is called for an AUTHENTICATED subject on * `/oauth2/authorize` before an authorization code is issued, with the - * subject + the requesting `clientId`. Return `false` to DENY (no code). + * subject + a `clientId` the request names. Return `false` to DENY (no code). + * It can be called once for each distinct client the request names (the + * query's and the body's `client_id`); if any one call answers `false`, + * the request is refused and no further client is asked about. * The cloud control plane uses it to require org-membership: a cloud user * may only obtain a code for an env client (`project_`) of an org * they belong to. Unset (open editions / self-host, where the OP is not a diff --git a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts index 7b9c1184d99..7aacabebb34 100644 --- a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts +++ b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts @@ -68,14 +68,15 @@ interface GateCall { const arrange = async () => { const engine = createMemoryEngine(); - const gate = { allow: false, calls: [] as GateCall[] }; + // `allow` admits every client; `admitted` admits the clients it names. + const gate = { allow: false, admitted: new Set(), calls: [] as GateCall[] }; const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN, dataEngine: engine, oidcAuthorizeGate: (params: GateCall) => { gate.calls.push({ userId: params.userId, clientId: params.clientId }); - return gate.allow; + return gate.allow || gate.admitted.has(params.clientId); }, } as any); @@ -135,7 +136,26 @@ const arrange = async () => { ); }; - return { manager, gate, userId, register, clientRow, authorize, call, cookie }; + /** A form-encoded `POST /oauth2/authorize`; `body` may repeat a key by giving it an array. */ + const authorizeForm = ( + query: Record, + body: Record, + headers: Record, + ) => { + const url = new URL(`${ISSUER}/oauth2/authorize`); + for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v); + const form = new URLSearchParams(); + for (const [k, v] of Object.entries(body)) for (const one of typeof v === 'string' ? [v] : v) form.append(k, one); + return manager.handleRequest( + new Request(url.toString(), { + method: 'POST', + headers: { origin: ORIGIN, ...headers, cookie, 'content-type': 'application/x-www-form-urlencoded' }, + body: form.toString(), + }), + ); + }; + + return { manager, gate, userId, register, clientRow, authorize, authorizeForm, call, cookie }; }; const codeRequest = (clientId: string, redirectUri: string): Record => ({ @@ -322,3 +342,261 @@ describe('a /oauth2/authorize with no signed-in subject is not judged', () => { expect(new URL(location).searchParams.has('error')).toBe(false); }); }); + +/** The URL an authorize answer sends the caller to: a `302`'s `Location`, or a fetch caller's `{ redirect, url }`. */ +async function nextUrl(res: Response): Promise { + const location = res.headers.get('location'); + if (location) return location; + const body: any = await res.clone().json().catch(() => null); + return typeof body?.url === 'string' ? body.url : ''; +} + +/** The authorization code an answer hands the client, or `null`. */ +async function codeIn(res: Response): Promise { + const url = await nextUrl(res); + return url.startsWith(ENV_CALLBACK) ? new URL(url).searchParams.get('code') : null; +} + +/** The refusal's `403` envelope: code and status (ADR-0112), and no code handed out. */ +async function expectRefusalEnvelope(res: Response): Promise { + const text = await res.clone().text(); + expect(res.status, text).toBe(403); + const body: any = JSON.parse(text); + expect(body.code ?? body.error?.code).toBe(ENV_ACCESS_DENIED_CODE); + expect(res.headers.get('location')).toBeNull(); + expect(text).not.toContain('code='); +} + +describe('the environment-access gate judges every client an /oauth2/authorize request names, from the query and the body', () => { + /** A signed-in subject, a refused client that would skip consent, and (when asked) an admitted one. */ + const arrangeClients = async () => { + const rig = await arrange(); + const refused = await rig.register(ENV_CALLBACK, 'web'); + const admitted = await rig.register(ENV_CALLBACK, 'web'); + rig.clientRow(refused).skip_consent = true; + rig.clientRow(admitted).skip_consent = true; + rig.gate.admitted.add(admitted); + return { rig, refused, admitted }; + }; + + it('a GET naming a refused client is refused', async () => { + const { rig, refused } = await arrangeClients(); + + const res = await rig.authorize(codeRequest(refused, ENV_CALLBACK), CONSOLE_FETCH); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId: refused }]); + await expectRefusalEnvelope(res); + }); + + it('a form-encoded POST naming a refused client in the body is refused', async () => { + const { rig, refused } = await arrangeClients(); + + const res = await rig.authorizeForm({}, codeRequest(refused, ENV_CALLBACK), CONSOLE_FETCH); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId: refused }]); + await expectRefusalEnvelope(res); + }); + + it('a form-encoded POST from a browser navigation is refused with the readable page, as a refused POST is answered today', async () => { + const { rig, refused } = await arrangeClients(); + + const res = await rig.authorizeForm({}, codeRequest(refused, ENV_CALLBACK), NAVIGATION); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId: refused }]); + expect(res.status).toBe(403); + expect(res.headers.get('location')).toBeNull(); + expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8'); + const page = await readPage(res); + expect(page.html).toContain(`data-refusal-code="${ENV_ACCESS_DENIED_CODE}"`); + expect(page.html).not.toContain(ENV_CALLBACK); + }); + + it('a JSON POST is answered with the provider\'s own 415, and no code is handed out', async () => { + const { rig, refused } = await arrangeClients(); + + const res = await rig.manager.handleRequest( + new Request(`${ISSUER}/oauth2/authorize`, { + method: 'POST', + headers: { origin: ORIGIN, cookie: rig.cookie, ...CONSOLE_FETCH, 'content-type': 'application/json' }, + body: JSON.stringify(codeRequest(refused, ENV_CALLBACK)), + }), + ); + + expect(res.status, await res.clone().text()).toBe(415); + expect(await codeIn(res)).toBeNull(); + }); + + const pairs: ReadonlyArray<[string, 'query' | 'body']> = [ + ['an admitted client in the query and a refused client in the body', 'body'], + ['a refused client in the query and an admitted client in the body', 'query'], + ]; + for (const [name, refusedIn] of pairs) { + it(`a form-encoded POST naming ${name} is refused`, async () => { + const { rig, refused, admitted } = await arrangeClients(); + const inQuery = refusedIn === 'query' ? refused : admitted; + const inBody = refusedIn === 'body' ? refused : admitted; + + const res = await rig.authorizeForm({ client_id: inQuery }, codeRequest(inBody, ENV_CALLBACK), CONSOLE_FETCH); + + expect(rig.gate.calls).toContainEqual({ userId: rig.userId, clientId: refused }); + await expectRefusalEnvelope(res); + }); + } + + for (const order of ['admitted first', 'refused first'] as const) { + it(`a query naming client_id twice, one of them refused, is refused, each client judged by itself (${order})`, async () => { + const { rig, refused, admitted } = await arrangeClients(); + const url = new URL(`${ISSUER}/oauth2/authorize`); + const { client_id: _omit, ...params } = codeRequest(refused, ENV_CALLBACK); + for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); + for (const one of order === 'admitted first' ? [admitted, refused] : [refused, admitted]) url.searchParams.append('client_id', one); + + const res = await rig.manager.handleRequest( + new Request(url.toString(), { headers: { ...CONSOLE_FETCH, cookie: rig.cookie } }), + ); + + expect(rig.gate.calls).toContainEqual({ userId: rig.userId, clientId: refused }); + await expectRefusalEnvelope(res); + }); + + it(`a form body naming client_id twice is handed no code unless the gate judged and admitted the client (${order})`, async () => { + const { rig, refused, admitted } = await arrangeClients(); + + const res = await rig.authorizeForm( + {}, + { ...codeRequest(refused, ENV_CALLBACK), client_id: order === 'admitted first' ? [admitted, refused] : [refused, admitted] }, + CONSOLE_FETCH, + ); + + expect(rig.gate.calls.length, 'the gate judged no client').toBeGreaterThan(0); + if (await codeIn(res)) { + expect(rig.gate.calls.every((c) => c.clientId === admitted), JSON.stringify(rig.gate.calls)).toBe(true); + } else { + await expectRefusalEnvelope(res); + } + }); + } + + it('a resume pass whose body names a client_id that is not a string is judged on that value, and refused when it is refused', async () => { + const { rig, admitted } = await arrangeClients(); + const first = await rig.authorize(codeRequest(admitted, ENV_CALLBACK), NAVIGATION, 'anonymous'); + const location = first.headers.get('location') ?? ''; + rig.gate.calls.length = 0; + + const res = await rig.call('/sign-in/email', { + body: { email: EMAIL, password: PASSWORD, oauth_query: location.slice(location.indexOf('?')), client_id: 12345 }, + headers: CONSOLE_FETCH, + }); + + expect(rig.gate.calls).toContainEqual({ userId: rig.userId, clientId: '12345' }); + await expectRefusalEnvelope(res); + }); + + it('a client named in both the query and the body is judged once', async () => { + const { rig, refused } = await arrangeClients(); + + const res = await rig.authorizeForm({ client_id: refused }, codeRequest(refused, ENV_CALLBACK), CONSOLE_FETCH); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId: refused }]); + await expectRefusalEnvelope(res); + }); + + it('control: an admitted subject\'s form-encoded POST is handed a code, every named client judged', async () => { + const { rig, admitted } = await arrangeClients(); + + const res = await rig.authorizeForm({ client_id: admitted }, codeRequest(admitted, ENV_CALLBACK), CONSOLE_FETCH); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId: admitted }]); + expect(await codeIn(res), await res.clone().text()).toBeTruthy(); + }); + + it('control: a request that names no client anywhere is not judged', async () => { + const { rig } = await arrangeClients(); + const { client_id: _omit, ...params } = codeRequest('unused', ENV_CALLBACK); + + const getRes = await rig.authorize(params, CONSOLE_FETCH); + const postRes = await rig.authorizeForm({}, params, CONSOLE_FETCH); + + expect(rig.gate.calls).toHaveLength(0); + expect(getRes.status).not.toBe(403); + expect(postRes.status).not.toBe(403); + expect(await codeIn(getRes)).toBeNull(); + expect(await codeIn(postRes)).toBeNull(); + }); +}); + +describe('the environment-access gate judges every pass that resumes an authorization', () => { + /** The signed authorization request a provider redirect carries, as the Console posts it back. */ + const oauthQueryOf = (location: string): string => { + expect(location.includes('?'), `expected a redirect carrying the signed request, got ${location}`).toBe(true); + return location.slice(location.indexOf('?')); + }; + + /** + * One resume pass: `prepare` runs with the gate admitting the client and + * hands back the signed request; `resume` then runs with the gate as the + * leg sets it. + */ + interface ResumePass { + readonly name: string; + readonly skipConsent: boolean; + readonly session: 'signed-in' | 'anonymous'; + resume(rig: Awaited>, oauthQuery: string): Promise; + } + + const passes: readonly ResumePass[] = [ + { + name: 'the sign-in that resumes an authorization', + skipConsent: true, + session: 'anonymous', + resume: (rig, oauthQuery) => + rig.call('/sign-in/email', { body: { email: EMAIL, password: PASSWORD, oauth_query: oauthQuery }, headers: CONSOLE_FETCH }), + }, + { + name: 'POST /oauth2/consent', + skipConsent: false, + session: 'signed-in', + resume: (rig, oauthQuery) => + rig.call('/oauth2/consent', { body: { accept: true, oauth_query: oauthQuery }, headers: { ...CONSOLE_FETCH, cookie: rig.cookie } }), + }, + { + name: 'POST /oauth2/continue', + skipConsent: true, + session: 'anonymous', + resume: (rig, oauthQuery) => + rig.call('/oauth2/continue', { body: { postLogin: true, oauth_query: oauthQuery }, headers: { ...CONSOLE_FETCH, cookie: rig.cookie } }), + }, + ]; + + const prepare = async (pass: ResumePass) => { + const rig = await arrange(); + const clientId = await rig.register(ENV_CALLBACK, 'web'); + rig.clientRow(clientId).skip_consent = pass.skipConsent; + rig.gate.allow = true; + const first = await rig.authorize(codeRequest(clientId, ENV_CALLBACK), NAVIGATION, pass.session); + const oauthQuery = oauthQueryOf(first.headers.get('location') ?? ''); + rig.gate.calls.length = 0; + return { rig, clientId, oauthQuery }; + }; + + for (const pass of passes) { + it(`${pass.name}: a denying gate refuses it`, async () => { + const { rig, clientId, oauthQuery } = await prepare(pass); + rig.gate.allow = false; + + const res = await pass.resume(rig, oauthQuery); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId }]); + await expectRefusalEnvelope(res); + }); + + it(`${pass.name}: control — an admitting gate is judged on it and the pass hands out a code`, async () => { + const { rig, clientId, oauthQuery } = await prepare(pass); + + const res = await pass.resume(rig, oauthQuery); + + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId }]); + expect(await codeIn(res), await res.clone().text()).toBeTruthy(); + }); + } +}); diff --git a/packages/qa/dogfood/test/oidc-authorize-env-gate.dogfood.test.ts b/packages/qa/dogfood/test/oidc-authorize-env-gate.dogfood.test.ts index 01744c00d19..0060bd128d9 100644 --- a/packages/qa/dogfood/test/oidc-authorize-env-gate.dogfood.test.ts +++ b/packages/qa/dogfood/test/oidc-authorize-env-gate.dogfood.test.ts @@ -328,6 +328,97 @@ describe('#8102: the D5.1 /oauth2/authorize env-access gate runs on every creden ]); }); + describe('the gate judges every client the request names, from the query and the body', () => { + /** A client id the patched gate below admits; the request's body names the seeded one. */ + const ADMITTED_CLIENT_ID = 'project_envgate_admitted'; + + /** A form-encoded authorize request, as a fetch caller sends it. */ + async function authorizeForm(query: Record): Promise { + const { res: signInRes } = await signIn(); + expect(signInRes.status, await signInRes.clone().text()).toBe(200); + const search = new URLSearchParams(query).toString(); + return stack.api(`/auth/oauth2/authorize${search ? `?${search}` : ''}`, { + method: 'POST', + headers: { + Cookie: cookieHeader(signInRes), + origin: 'http://localhost:3000', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded', + }, + body: authorizeQuery(), + redirect: 'manual', + }); + } + + /** Where the answer sends the caller: a `302`'s `Location`, or a fetch caller's `{ url }`. */ + async function nextUrl(res: Response): Promise { + const location = res.headers.get('location'); + if (location) return location; + const body: any = await res.clone().json().catch(() => null); + return typeof body?.url === 'string' ? body.url : ''; + } + + async function expectRefused(res: Response): Promise { + const text = await res.clone().text(); + expect(res.status, text).toBe(403); + const refusal: any = JSON.parse(text); + expect(refusal?.code ?? refusal?.error?.code).toBe('ENV_ACCESS_DENIED'); + expect(await nextUrl(res)).toBe(''); + expect(text).not.toContain('code='); + } + + /** Install `admits` as the gate for one leg, then put the denying recorder back. */ + async function withGate(admits: (clientId: string) => boolean, leg: () => Promise): Promise { + const auth = await stack.kernel.getServiceAsync('auth'); + auth.applyConfigPatch({ + oidcAuthorizeGate: (params: { userId: string; clientId: string }) => { + gateCalls.push({ userId: params.userId, clientId: params.clientId }); + return admits(params.clientId); + }, + }); + try { + await leg(); + } finally { + auth.applyConfigPatch({ + oidcAuthorizeGate: (params: { userId: string; clientId: string }) => { + gateCalls.push({ userId: params.userId, clientId: params.clientId }); + return false; + }, + }); + } + } + + it('a form-encoded POST naming the client in the body only is refused by a denying gate', async () => { + gateCalls = []; + const res = await authorizeForm({}); + + expect(gateCalls).toEqual([{ userId: adminUserId, clientId: CLIENT_ID }]); + await expectRefused(res); + }, 120_000); + + it('a form-encoded POST naming an admitted client in the query and a refused client in the body is refused', async () => { + await withGate((clientId) => clientId === ADMITTED_CLIENT_ID, async () => { + gateCalls = []; + const res = await authorizeForm({ client_id: ADMITTED_CLIENT_ID }); + + expect(gateCalls).toContainEqual({ userId: adminUserId, clientId: CLIENT_ID }); + await expectRefused(res); + }); + }, 120_000); + + it('control: the same form-encoded POST with an admitting gate is handed a code', async () => { + await withGate(() => true, async () => { + gateCalls = []; + const res = await authorizeForm({}); + + expect(gateCalls).toEqual([{ userId: adminUserId, clientId: CLIENT_ID }]); + const url = await nextUrl(res); + expect(url.startsWith(REDIRECT_URI), `${res.status}: ${await res.clone().text()}`).toBe(true); + expect(new URL(url).searchParams.get('code')).toBeTruthy(); + }); + }, 120_000); + }); + it('an UNAUTHENTICATED caller still falls through to the OP login redirect (the fail-open default is deliberate)', async () => { gateCalls = []; const res = await stack.api(`/auth/oauth2/authorize?${authorizeQuery()}`, {