Skip to content

Commit 0ff3b14

Browse files
fix(auth)!: the environment-access gate on /oauth2/authorize judges every client the request names (#33937)
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. ## 维护者速读 - 改了什么:`/oauth2/authorize` 上的环境访问门(`oidcAuthorizeGate`)现在对请求点名的每一个客户端逐一裁决(查询串与请求体里的 `client_id`,字符串或数组,去重),任一被拒即以现有的 403 `ENV_ACCESS_DENIED` 拒绝。 - 为什么改:门的裁决范围应覆盖请求点名的全部客户端,规则以此为准。 - 风险与回滚:只影响设置了 `oidcAuthorizeGate` 的部署(托管控制面);开源版与自托管不设,行为不变。回滚即 revert 本提交。 - 先看:`packages/plugins/plugin-auth/src/auth-manager-before-hook.ts`(`authorizeRequestClientIds` 与门的循环)、`packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts`(新增两个 describe)、`.changeset/authorize-gate-judges-every-client-id.md`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/oauth-authorize-refusal.test.ts`,预期 31 个测试全绿。 - 需要你做的:无,席位落地。 ## What changes The ADR-0069 D5.1 environment-access gate on `/oauth2/authorize` 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 (query first). It refuses with its existing refusal if any one is refused: `403 ENV_ACCESS_DENIED` for a fetch or API client, and for a browser the redirect or readable page it already gets (`oauth-authorize-refusal.ts`, unchanged). A request that names no client anywhere is unchanged, and so is an unauthenticated request. BREAKING only for a host whose `oidcAuthorizeGate` assumes one call per request: it can now be called once per distinct client named. The callback signature does not change. ## Tests `packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts` (real `AuthManager` + `@better-auth/oauth-provider`), two new top-level describes in the existing harness: - the gate judges every client the request names: GET refused; form POST refused (envelope); form POST from a browser navigation answers the page, as a refused POST is answered today; JSON POST answers the provider's 415; a query/body pair refused in either order; a form body naming two clients is issued a code only for a client the gate judged and admitted, in either order; a query naming the client twice is refused when either is refused, each judged by itself, in either order; a client named in both judged once; CONTROL an admitted form POST is handed a code; CONTROL a request naming no client is not judged. - the gate judges every pass that resumes an authorization: sign-in resume, `POST /oauth2/consent`, `POST /oauth2/continue`, each with a denying-gate leg (refused) and an admitting control (code). A resume pass naming a client that is not a string is judged on that value and refused when it is refused. `packages/qa/dogfood/test/oidc-authorize-env-gate.dogfood.test.ts`: form POST naming the client in the body refused; query/body pair refused; CONTROL admitting gate hands a code. ## Acceptance notes - PR overlap: PR 33268 edited the same insertion point in `auth-manager-before-hook.ts`. It landed first, and the merge at `8e83084f92` keeps both declarations. ## Verification <details><summary>Readings</summary> - Before the fix (merge base 4b5024d): the new pins `Tests 4 failed | 23 passed (27)`; every resume-pass leg was already green. - With the fix: `Tests 27 passed (27)`. Ablation of the body read: the same 4 red, restored to the HEAD blob. - `pnpm --filter @objectstack/plugin-auth test` at `f050ae909b`: `Test Files 277 passed (277)`, `Tests 5501 passed | 10 skipped`; typecheck OK (lock VERDICT command-exit 0). The head `a65fcc623d` adds only a `packages/cli` merge from main. - dispatch-gates at `fed9ed9668`: 70 derived, 69 run, 1 NOT-MEASURED (`check:dual-build-cjs-loads`, prerequisite dist; CI runs it). - Dogfood battery at `fed9ed9668`: `Tests 3962 passed | 42 skipped (4004)`, VERDICT command-exit 0. - Dogfood battery at `a65fcc623d`: `Test Files 467 passed | 3 skipped (470)` · `Tests 3962 passed | 42 skipped (4004)`, no failures, VERDICT command-exit 0. It carries to `8a779dea16`, whose diff changes only tests, a jsdoc comment and the changeset. - Review round 2 at `8a779dea16`: `oauth-authorize-refusal.test.ts` `Tests 31 passed (31)`. Ablation of the repeated-parameter arm: 2 red. Ablation of the non-string arm: 1 red. Both restored to the HEAD blob. plugin-auth `Tests 5505 passed | 10 skipped`, and typecheck OK. The changeset gates and the 9 gate families added by `auth-manager.ts` all exit 0. - Main merged at `8e83084f92`, after PR 33268 landed at the same insertion point in `auth-manager-before-hook.ts`. The conflict was positional and both declarations are kept, with no line of either changed. plugin-auth at that tree: `Test Files 277 passed (277)` · `Tests 5515 passed | 10 skipped (5525)`, and typecheck OK. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcT1w3zpekijraHJE4f)_ <!-- signed: security#1 · sunhaolin · session_017xRBcT1w3zpekijraHJE4f --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0bbb211 commit 0ff3b14

5 files changed

Lines changed: 428 additions & 10 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(auth)!: the environment-access gate on `/oauth2/authorize` judges every client the request names, from the query and the body
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
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.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped: the change is a runtime refusal at one auth endpoint, judged by a host callback whose signature does not change, so there is nothing stored for a migration to rewrite and no tombstone. -->
12+
13+
**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.
14+
15+
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<boolean>`, does not change.
16+
17+
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.

‎packages/plugins/plugin-auth/src/auth-manager-before-hook.ts‎

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,29 @@ import { ssoDiscoveryCompanionContext } from './sso-discovery-companion-origins.
8989
import { snapshotRoleChangeGrants, UPDATE_MEMBER_ROLE_PATH } from './role-change-granted-set.js';
9090
import { refuseVisitorResendWithoutLiveTransport } from './visitor-verification-resend.js';
9191

92+
/**
93+
* Every client an `/oauth2/authorize` request names, for the ADR-0069 D5.1
94+
* environment-access gate: the query's `client_id` first, then the body's,
95+
* each a string or an array of them, de-duplicated in that order. An empty
96+
* value names nothing; any other present value is judged by its string form
97+
* rather than skipped, so the gate is never asked about fewer clients than
98+
* the request names.
99+
*/
100+
function authorizeRequestClientIds(ctx: any): string[] {
101+
const named = new Set<string>();
102+
const collect = (source: unknown): void => {
103+
if (typeof source !== 'object' || source === null || Array.isArray(source)) return;
104+
const value = (source as Record<string, unknown>).client_id;
105+
for (const one of Array.isArray(value) ? value : [value]) {
106+
if (one === undefined || one === null || one === '') continue;
107+
named.add(String(one));
108+
}
109+
};
110+
collect(ctx?.query);
111+
collect(ctx?.body);
112+
return [...named];
113+
}
114+
92115
/**
93116
* [#33203] The self-service reset doors a cloud-managed environment refuses:
94117
* the two that set the password and the two that send their link or code.
@@ -550,20 +573,26 @@ export async function globalBeforeHook(
550573
// read as unauthenticated and this env-access check never evaluated
551574
// at all. Two resolution sites are what let them diverge, so the fix
552575
// is to delete one, not to correct it in place.
576+
//
577+
// The gate judges EVERY client the request names — the query's and the
578+
// body's `client_id`, each a string or an array, de-duplicated
579+
// ({@link authorizeRequestClientIds}) — and refuses if any one of them
580+
// is refused. A request that names no client anywhere is not judged here.
553581
if (ctx?.path === '/oauth2/authorize' && this.config.oidcAuthorizeGate) {
554-
const clientId = ctx?.query?.client_id;
555-
if (clientId) {
582+
const clientIds = authorizeRequestClientIds(ctx);
583+
if (clientIds.length > 0) {
556584
const actor = await this.resolveActor(ctx);
557585
// Unauthenticated → fall through, per the contract above. Only an
558586
// AUTHENTICATED subject is gated here. `resolveActor` also returns
559587
// `activeOrgId`; this gate deliberately does not consume it — the
560588
// D5.1 host contract is `(userId, clientId)` and the control plane
561589
// derives org membership / app assignment from the user itself.
562590
if (actor?.userId) {
563-
const allowed = await this.config.oidcAuthorizeGate({
564-
userId: actor.userId,
565-
clientId: String(clientId),
566-
});
591+
let allowed = true;
592+
for (const clientId of clientIds) {
593+
allowed = await this.config.oidcAuthorizeGate({ userId: actor.userId, clientId });
594+
if (!allowed) break;
595+
}
567596
if (!allowed) {
568597
// The refusal, delivered by who is asking (`oauth-authorize-refusal.ts`):
569598
// the `403` envelope for a fetch or an API client, unchanged; for a

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -960,7 +960,10 @@ export interface AuthManagerOptions extends Partial<AuthConfig> {
960960
* D5.1 — OIDC OP authorization gate (cloud-as-IdP app-assignment).
961961
* When set, it is called for an AUTHENTICATED subject on
962962
* `/oauth2/authorize` before an authorization code is issued, with the
963-
* subject + the requesting `clientId`. Return `false` to DENY (no code).
963+
* subject + a `clientId` the request names. Return `false` to DENY (no code).
964+
* It can be called once for each distinct client the request names (the
965+
* query's and the body's `client_id`); if any one call answers `false`,
966+
* the request is refused and no further client is asked about.
964967
* The cloud control plane uses it to require org-membership: a cloud user
965968
* may only obtain a code for an env client (`project_<envId>`) of an org
966969
* they belong to. Unset (open editions / self-host, where the OP is not a

0 commit comments

Comments
 (0)