Skip to content

Commit a2be78d

Browse files
fix(plugin-auth): a SCIM bearer write carrying a Cookie and no Origin is no longer refused 403 MISSING_OR_NULL_ORIGIN (#33243)
Fixes #33237 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`AuthManager.handleRequest` 在把请求交给 better-auth 之前,对带 `Authorization: Bearer` 的 `/scim/v2/*` 请求去掉 `Cookie` 头;其余路由一律不动。 - 为什么改:better-auth 的来源检查只要请求带任何 Cookie 就要求 `Origin`,于是带 Cookie 罐(如 Cloudflare `__cf_bm`、粘性会话 Cookie)的身份提供方(Okta 已实测)做 SCIM 开通与停用全部被拒 403,离职员工的访问无法由目录撤销。SCIM 只认 bearer,Cookie 在该路径上不带任何权限。 - 风险与回滚:风险面只有「`/scim/v2/*` 且带 bearer」这一种请求;无 bearer 的 SCIM 请求与所有浏览器路由仍走原来的来源检查。回滚即 revert 本 PR 的那一个 `if` 块。 - 先看:`packages/plugins/plugin-auth/src/auth-manager-request-routing.ts`(新增的 `if` 块,判定条件三项是风险点);`packages/plugins/plugin-auth/src/scim-bearer-cookie-origin.test.ts`(四个用例与 `boot()` 里把来源检查打开的那几行)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/scim-bearer-cookie-origin.test.ts`,预期 4 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes `packages/plugins/plugin-auth/src/auth-manager-request-routing.ts`, `handleRequest`: right after the vendor client-address rewrite, a request whose better-auth endpoint path is under `/scim/v2` (`isScimProtocolPath`, the predicate the SCIM request scope already keys on) AND that carries `Authorization: Bearer` followed by a credential AND that carries a `Cookie` is rebuilt without the `Cookie` header before better-auth sees it. This is the route that relaxes no check: no global or per-path origin-check exemption is added, and `skipOriginCheck` / `disableCSRFCheck` are not touched. Why it is safe, measured on better-auth 1.7.12 and `@better-auth/scim` 1.7.12 as installed: - `validateOrigin` (`dist/api/middlewares/origin-check.mjs`) reads `useCookies = headers.has("cookie")` off the request `handleRequest` hands it; with a cookie and no Origin or Referer it throws `MISSING_OR_NULL_ORIGIN`. That is the whole defect. - Every `/scim/v2/*` mutation endpoint is `use: [authMiddleware]`, and that middleware (`createSCIMConnectionMiddleware`) authenticates from `Authorization: Bearer` alone: no bearer is `401 SCIM bearer token is required`. The platform's `verifyBearerToken` (`auth-manager-plugin-list.ts`) reads only `input.token`. - SCIM writes are attributed to the verified connection (`authSystemWriteContext` returns `actor: svc:scim:CONNECTION_ID` first and never consults the session resolver when a SCIM connection is in scope), so stripping the cookie changes no attribution either. - A SCIM request with NO bearer keeps its cookie and still meets the origin check (pinned below). The landing is the expected file; no producer elsewhere was needed. `auth-manager.ts`, `auth-plugin.ts` and the better-auth pin are untouched. `.changeset/33237-scim-bearer-cookie-origin.md`: `@objectstack/plugin-auth` patch. ## Tests New file `packages/plugins/plugin-auth/src/scim-bearer-cookie-origin.test.ts` (real `AuthManager`, real `ObjectQL` on better-sqlite3, SCIM on, a minted connection credential: the `scim-transaction-scope.test.ts` harness shape). Four cases: 1. SCIM bearer `POST /Users` with `Cookie: __cf_bm=...; better-auth.session_token=` and no Origin: 201 and the `sys_user` row exists. 2. SCIM bearer `PATCH /Users/{id}` `active:false` with the same Cookie and no Origin: 200, resource `active: false`. 3. SCIM `POST /Users` with the Cookie and NO bearer: still 403, `code` `MISSING_OR_NULL_ORIGIN`, no `sys_user` row written. 4. CONTROL: a real session cookie (from sign-up) on `POST /sign-out` with no Origin: still 403, `code` `MISSING_OR_NULL_ORIGIN`. How production semantics are ensured: two things would mask the bug under vitest, and the harness turns off both. `handleRequest` synthesizes a same-origin Origin outside production: every case runs with `vi.stubEnv('NODE_ENV', 'production')` and asserts it reads back. And better-auth reads NODE_ENV once at module load (`@better-auth/core/env`), so under vitest it defaults `skipOriginCheck` to `true` (`create-context.mjs`: `disableOriginCheck` unset means `isTest()`): `boot()` sets the production value `false` on the live `$context` and asserts `skipCSRFCheck` is `false`. Before that line was added, cases 3 and 4 were red on the unfixed tree (the control POST answered 200), which is how the masking was found. Red on the unfixed tree (commit e9076fa, test only): cases 1 and 2 fail with `{"message":"Missing or null Origin","code":"MISSING_OR_NULL_ORIGIN"}: expected 403 to be 201` (and `to be 200`); cases 3 and 4 pass. Ablation (one-time, on the fix commit c8abb27, through `scripts/ablation-replace.mjs`): the anchor `headers.delete('cookie');` replaced by a comment, anchor 1 to 0, blob 944e5a3 to efaf0d39e2b3; cases 1 and 2 red again with 403, cases 3 and 4 green; restored, blob after restore 944e5a3 equals HEAD and `git diff HEAD` empty. The test imports `./auth-manager.js` relatively, so the subject resolves to `src/`, no `dist/` step. ## Acceptance notes - Behaviour change beyond the card's three cases, stated so it is not a surprise: a `/scim/v2/*` bearer request that carries a Cookie AND an untrusted Origin used to be refused 403 `INVALID_ORIGIN`; it now reaches the SCIM bearer check like any bearer client. Same reasoning: the origin check guards cookie authority, and there is none on this path. - The vendor's origin check is skipped wholesale under a test NODE_ENV, so any plugin-auth test that means to observe it must put `skipOriginCheck = false` on the context as `boot()` here does. Observation only; no card. - The cloud hosted proxy strip (cloud#4498) can retire once a release carrying this reaches cloud's pin; that is cloud's and the maintainer's call on cloud#4491. ## Verification All readings at head c8abb27 (worktree on `origin/main` 6c5d31f). <details> <summary>plugin-auth tests and typecheck: 270/270 files, 5118 passed, typecheck exit 0</summary> - `pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2` (whole package): `Test Files 270 passed (270)`, `Tests 5118 passed | 10 skipped (5128)`, lock `VERDICT command-exit 0`. - `pnpm --filter @objectstack/plugin-auth typecheck`: exit 0; `check:test-typecheck: OK ... 10 file(s) / 72 error(s) / 23 pinned signature(s) held` (the new file adds none). </details> <details> <summary>lint: exit 0</summary> - `pnpm lint` (repo-wide, run on the dispatch's request): lock `VERDICT command-exit 0`. - `eslint --no-inline-config` on the two changed TS files: exit 0. </details> <details> <summary>derived gate families: 65 exit 0, 1 NOT MEASURED</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 66 derived families, each run locally; `--ran` reconciliation: `66 derived famil(ies) accounted for — 65 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3)`. - `pnpm check:dual-build-cjs-loads` exit 3 `PREREQUISITE NOT MET` (it needs every package's `dist/`; this worktree built only plugin-auth's closure): NOT MEASURED locally, CI runs it. - `node scripts/check-nul-bytes.mjs`: exit 0. - Not run locally, owned by CI: `test:repo`, the dogfood battery (no `!` in the title, no narrowing arm), the UI lanes. </details> Overlap check before push: open drafts #33227 and #33221 do not touch `auth-manager-request-routing.ts`; no open PR from #32115 was found. --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcSZ51q2s3nMfakhdJ3)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 199e362 commit a2be78d

3 files changed

Lines changed: 289 additions & 0 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): a SCIM bearer write that carries a Cookie and no Origin is no longer refused 403 `MISSING_OR_NULL_ORIGIN`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
better-auth's origin check requires an `Origin` (or `Referer`) whenever a request carries any Cookie, and `AuthManager.handleRequest` used to forward the Cookie into it on `/scim/v2/*`. An identity provider that keeps a cookie jar, or sits behind an edge cookie (`__cf_bm`) or a sticky-session load-balancer cookie, was therefore answered 403 `MISSING_OR_NULL_ORIGIN` on every `POST /Users` and every `PATCH … active:false`: it could neither provision nor deprovision a user.
11+
12+
SCIM authenticates by the `Authorization: Bearer` credential alone and its writes are attributed to the verified connection, so a Cookie carries no authority on that path. `handleRequest` now drops the Cookie from a `/scim/v2/*` request that carries a bearer, before better-auth sees it. No check is relaxed: every other route, and a `/scim/v2/*` request with no bearer, still reaches the origin check with its Cookie and is still refused without an `Origin`. A deployment that strips the Cookie in front of the server for this reason can drop that strip once it runs this release.

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,30 @@ export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'b
117117
// address the D5 allow-list judged, or none. See `client-address-vendor.ts`.
118118
request = withVendorClientAddress(request, clientAddress);
119119

120+
// [#33237] A SCIM protocol request (`/scim/v2/*`) that carries a bearer
121+
// reaches the vendor WITHOUT its Cookie. `@better-auth/scim` authenticates
122+
// that path by the `Authorization: Bearer` credential alone
123+
// (`createSCIMConnectionMiddleware`; the platform's verifier reads only the
124+
// token), and its writes are attributed to the verified connection, never
125+
// to a session (`authSystemWriteContext`), so a Cookie carries no authority
126+
// there. It did carry a refusal: the vendor's origin check
127+
// (`validateOrigin`) demands an `Origin` whenever the request HAS a cookie,
128+
// so an identity provider with a cookie jar, or behind an edge or
129+
// sticky-session cookie, was answered 403 `MISSING_OR_NULL_ORIGIN` on every
130+
// provision and deprovision. Dropping the Cookie relaxes no check: the
131+
// origin check still runs on every request that keeps one — every other
132+
// route, and a `/scim/v2/*` request with no bearer, which the SCIM
133+
// middleware refuses anyway. Pinned by `scim-bearer-cookie-origin.test.ts`.
134+
if (
135+
request.headers.has('cookie') &&
136+
/^Bearer\s+\S/i.test(request.headers.get('authorization') ?? '') &&
137+
isScimProtocolPath(this.betterAuthEndpointPath(request))
138+
) {
139+
const headers = new Headers(request.headers);
140+
headers.delete('cookie');
141+
request = new Request(request, { headers });
142+
}
143+
120144
// Dev DX: better-auth's CSRF protection rejects state-changing requests
121145
// (e.g. `/sign-in/email`) with a 403 when neither `Origin` nor `Referer`
122146
// is present. Browsers always send one; non-browser API clients (curl,
Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#33237] A SCIM bearer write is not refused by the browser origin check
5+
* because some Cookie rode along with it.
6+
*
7+
* ## The defect
8+
*
9+
* better-auth's `validateOrigin` (1.7.12, `dist/api/middlewares/origin-check.mjs`)
10+
* decides `useCookies = headers.has("cookie")` and, when it is true, requires an
11+
* `Origin` (or `Referer`) — `403 MISSING_OR_NULL_ORIGIN` without one. It reads
12+
* the request `AuthManager.handleRequest` hands it, and `handleRequest` used to
13+
* forward the Cookie header untouched on `/scim/v2/*`. So an identity provider
14+
* that keeps a cookie jar (an edge cookie such as `__cf_bm`, a sticky-session
15+
* load-balancer cookie) could neither provision nor deprovision a user: a SCIM
16+
* POST or `PATCH active:false` with any Cookie and no Origin answered 403.
17+
*
18+
* `@better-auth/scim` authenticates `/scim/v2/*` by the `Authorization: Bearer`
19+
* credential alone (`createSCIMConnectionMiddleware`), and the platform's
20+
* verifier reads only that token (`verifyScimBearerToken`), so a Cookie carries
21+
* no authority on that path: the origin check protected nothing there.
22+
* `handleRequest` now drops the Cookie from a `/scim/v2/*` request that carries
23+
* a bearer, before the vendor sees it. No check is relaxed: every other route,
24+
* and a SCIM request with no bearer, still reaches the origin check with its
25+
* Cookie.
26+
*
27+
* ## Why NODE_ENV is production here
28+
*
29+
* Two things would let every case below pass with or without the fix, and the
30+
* harness turns both off. Outside production `handleRequest` synthesizes a
31+
* same-origin `Origin` for a request that has none (the dev-DX block): each
32+
* case runs with `NODE_ENV=production` stubbed, and its first assertion reads
33+
* it back. And better-auth skips the origin check outright under a test
34+
* NODE_ENV: `boot()` puts the production value on the live context (the note
35+
* there says why it cannot come from the stub).
36+
*
37+
* Harness: a real `AuthManager` over a real `ObjectQL` on better-sqlite3 with
38+
* SCIM on and a minted connection credential — the shape of
39+
* `scim-transaction-scope.test.ts`.
40+
*/
41+
42+
import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
43+
import { ObjectQL } from '@objectstack/objectql';
44+
import { SqlDriver } from '@objectstack/driver-sql';
45+
import { AuthManager } from './auth-manager.js';
46+
import { authIdentityObjects } from './manifest.js';
47+
import { createTenancyService } from './tenancy-service.js';
48+
import { mintScimConnectionCredential } from './scim-connection-service.js';
49+
50+
const BASE = 'http://localhost:3000';
51+
const AUTH = `${BASE}/api/v1/auth`;
52+
const SECRET = 'test-secret-at-least-32-chars-long-33237';
53+
const PASSWORD = 'correct-horse-battery-staple-33237';
54+
55+
const USER_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User';
56+
const PATCH_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:PatchOp';
57+
58+
/** An edge cookie of the kind a CDN sets on every response, plus an expired empty one. */
59+
const EDGE_COOKIE = '__cf_bm=Zm9vYmFyLWJvdC1tYW5hZ2VtZW50; better-auth.session_token=';
60+
61+
const SYSTEM = { context: { isSystem: true } } as const;
62+
63+
const engines: ObjectQL[] = [];
64+
beforeEach(() => {
65+
vi.stubEnv('NODE_ENV', 'production');
66+
});
67+
afterEach(async () => {
68+
vi.unstubAllEnvs();
69+
vi.restoreAllMocks();
70+
while (engines.length) {
71+
const e = engines.pop();
72+
try {
73+
await (e as unknown as { destroy?(): Promise<void> })?.destroy?.();
74+
} catch {
75+
/* noop */
76+
}
77+
}
78+
});
79+
80+
interface Harness {
81+
engine: ObjectQL;
82+
token: string;
83+
send: (request: Request) => Promise<Response>;
84+
}
85+
86+
async function boot(): Promise<Harness> {
87+
const engine = new ObjectQL();
88+
engines.push(engine);
89+
const driver = new SqlDriver({
90+
client: 'better-sqlite3',
91+
connection: { filename: ':memory:' },
92+
useNullAsDefault: true,
93+
});
94+
engine.registerDriver(driver, true);
95+
await engine.init();
96+
for (const object of authIdentityObjects) {
97+
engine.registry.registerObject(object as never, '@objectstack/plugin-auth');
98+
}
99+
await engine.syncSchemas();
100+
101+
const manager = new AuthManager({
102+
secret: SECRET,
103+
baseUrl: BASE,
104+
dataEngine: engine as never,
105+
getTenancy: () => createTenancyService({ requested: 'isolated', probeIsolation: () => true }),
106+
plugins: { scim: true, organization: true },
107+
} as never);
108+
109+
// better-auth reads NODE_ENV ONCE, when `@better-auth/core/env` loads, and
110+
// under vitest that read is `test`, for which it defaults the context's
111+
// `skipOriginCheck` to `true` (`create-context.mjs`: `disableOriginCheck`
112+
// unset ⇒ `isTest()`). A deployment runs with `false`. The stub above comes
113+
// too late for that module-load read, so the production value is put on the
114+
// live context here — and read back, so a harness that never reached the
115+
// origin check fails instead of passing every case below vacuously.
116+
const context = (await (await manager.getAuthInstance()).$context) as {
117+
skipOriginCheck: unknown;
118+
skipCSRFCheck: unknown;
119+
};
120+
context.skipOriginCheck = false;
121+
expect(context.skipCSRFCheck, 'the CSRF check is on, as in a deployment').toBe(false);
122+
123+
const { token } = await mintScimConnectionCredential(engine as never, SECRET, {
124+
connectionId: 'okta-33237',
125+
organizationId: 'org_scim_33237',
126+
});
127+
128+
return { engine, token, send: (request) => manager.handleRequest(request) };
129+
}
130+
131+
/** A SCIM request as an IdP with a cookie jar sends it: a Cookie, NO Origin, no Referer. */
132+
function scimRequest(
133+
path: string,
134+
init: { method: string; bearer?: string; cookie?: string; body?: unknown },
135+
): Request {
136+
const headers: Record<string, string> = {};
137+
if (init.bearer !== undefined) headers.authorization = `Bearer ${init.bearer}`;
138+
if (init.cookie !== undefined) headers.cookie = init.cookie;
139+
if (init.body !== undefined) headers['content-type'] = 'application/scim+json';
140+
return new Request(`${AUTH}/scim/v2${path}`, {
141+
method: init.method,
142+
headers,
143+
...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
144+
});
145+
}
146+
147+
const userBody = (localPart: string) => ({
148+
schemas: [USER_SCHEMA],
149+
userName: `${localPart}@example.com`,
150+
name: { givenName: localPart, familyName: 'Example' },
151+
displayName: `${localPart} Example`,
152+
emails: [{ value: `${localPart}@example.com`, primary: true, type: 'work' }],
153+
active: true,
154+
});
155+
156+
async function errorCode(res: Response): Promise<unknown> {
157+
const body = (await res.clone().json().catch(() => null)) as
158+
| { code?: unknown; error?: { code?: unknown } }
159+
| null;
160+
return body?.code ?? body?.error?.code;
161+
}
162+
163+
async function userRow(h: Harness, email: string): Promise<Record<string, unknown> | null> {
164+
return h.engine.findOne('sys_user', { where: { email }, fields: ['id', 'email'] }, SYSTEM) as Promise<
165+
Record<string, unknown> | null
166+
>;
167+
}
168+
169+
/** The dev-DX Origin synthesis must be OFF, or every case below passes without the fix. */
170+
function assertProductionSemantics(): void {
171+
expect(process.env.NODE_ENV, 'NODE_ENV must read production so no Origin is synthesized').toBe('production');
172+
}
173+
174+
describe('[#33237] a SCIM bearer request is not refused for the Cookie it carries', () => {
175+
it('POST /Users with a SCIM bearer, a Cookie and no Origin is served (201)', async () => {
176+
assertProductionSemantics();
177+
const h = await boot();
178+
179+
const res = await h.send(
180+
scimRequest('/Users', { method: 'POST', bearer: h.token, cookie: EDGE_COOKIE, body: userBody('alice') }),
181+
);
182+
183+
expect(res.status, `SCIM POST /Users: ${await res.clone().text()}`).toBe(201);
184+
expect(await userRow(h, 'alice@example.com'), 'the provisioned sys_user row').not.toBeNull();
185+
}, 60_000);
186+
187+
it('PATCH /Users/{id} active:false with a SCIM bearer, a Cookie and no Origin is served (200)', async () => {
188+
assertProductionSemantics();
189+
const h = await boot();
190+
const created = await h.send(
191+
scimRequest('/Users', { method: 'POST', bearer: h.token, body: userBody('bob') }),
192+
);
193+
expect(created.status, `SCIM POST /Users (setup, no cookie): ${await created.clone().text()}`).toBe(201);
194+
const { id } = (await created.json()) as { id: string };
195+
196+
const res = await h.send(
197+
scimRequest(`/Users/${id}`, {
198+
method: 'PATCH',
199+
bearer: h.token,
200+
cookie: EDGE_COOKIE,
201+
body: { schemas: [PATCH_SCHEMA], Operations: [{ op: 'replace', path: 'active', value: false }] },
202+
}),
203+
);
204+
205+
expect(res.status, `SCIM PATCH active:false: ${await res.clone().text()}`).toBe(200);
206+
expect(((await res.json()) as { active?: unknown }).active, 'the deprovisioned resource').toBe(false);
207+
}, 60_000);
208+
});
209+
210+
describe('[#33237] the origin check still guards every cookie-carrying request it guarded', () => {
211+
it('a SCIM POST with a Cookie and NO bearer is still refused: 403 MISSING_OR_NULL_ORIGIN, nothing written', async () => {
212+
assertProductionSemantics();
213+
const h = await boot();
214+
215+
const res = await h.send(
216+
scimRequest('/Users', { method: 'POST', cookie: EDGE_COOKIE, body: userBody('mallory') }),
217+
);
218+
219+
expect(res.status, await res.clone().text()).toBe(403);
220+
expect(await errorCode(res)).toBe('MISSING_OR_NULL_ORIGIN');
221+
expect(await userRow(h, 'mallory@example.com'), 'no sys_user row may be written').toBeNull();
222+
}, 60_000);
223+
224+
it('CONTROL: a cookie-authenticated non-SCIM POST with no Origin is still refused: 403 MISSING_OR_NULL_ORIGIN', async () => {
225+
assertProductionSemantics();
226+
const h = await boot();
227+
const up = await h.send(
228+
new Request(`${AUTH}/sign-up/email`, {
229+
method: 'POST',
230+
headers: { 'content-type': 'application/json', origin: BASE },
231+
body: JSON.stringify({ email: 'carol@example.com', password: PASSWORD, name: 'Carol Example' }),
232+
}),
233+
);
234+
expect(up.status, `sign-up: ${await up.clone().text()}`).toBeLessThan(300);
235+
const sessionCookie = (up.headers.getSetCookie?.() ?? [])
236+
.map((c) => c.split(';')[0])
237+
.find((c) => c.includes('session_token='));
238+
expect(sessionCookie, 'sign-up set a session cookie').toBeTruthy();
239+
240+
// The same session, presented as a browser would — cookie only — on a
241+
// state-changing route, with no Origin and no Referer.
242+
const res = await h.send(
243+
new Request(`${AUTH}/sign-out`, {
244+
method: 'POST',
245+
headers: { 'content-type': 'application/json', cookie: `${sessionCookie}; __cf_bm=Zm9vYmFy` },
246+
body: '{}',
247+
}),
248+
);
249+
250+
expect(res.status, await res.clone().text()).toBe(403);
251+
expect(await errorCode(res)).toBe('MISSING_OR_NULL_ORIGIN');
252+
}, 60_000);
253+
});

0 commit comments

Comments
 (0)