Skip to content

Commit 0208b68

Browse files
fix(plugin-auth)!: the SSO domain check refuses a subdomain listed beside its parent, and compares one spelling (#32383)
Fixes #32308 Clause-②: no (narrowing) Metadata-protocol: none > Declaration corrected by the seat (card comment 6784574779 on #32308): the newly refused shapes were accepted before, so this is the narrowing arm, as contract review 6771575242 graded the same refusal class on this door. The changeset carries `!`, the BREAKING banner and one ADR-0087 marker; the whole dogfood battery is green on the final head. ## 维护者速读 - 改了什么:SSO 提供方的"同一域名只能一个"检查补了两种漏判:多域名列表里的子域与父域并存(两种注册顺序都拒),以及同一域名的不同写法(punycode 对 Unicode、末尾的点);另加域名长度上限(整值 255、单项 253),超长在解析前拒绝 400;非平台管理员收到的 child 拒绝只点名自己请求的父域。 - 为什么改:厂商按"整值精确匹配,否则按存储行序取第一个列表匹配"路由,列表里的子域赢不了第一步,由行序决定;不同写法是同一个 DNS 域名。上一轮复审还指出去尾点的正则对请求可控输入是二次方回溯,现改为线性扫描。 - 风险与回滚:只会多拒绝注册和域名修改,不放行任何今天被拒的请求;已存的提供方不受影响。回滚即还原本 PR。 - 先看:`packages/plugins/plugin-auth/src/sso-provider-lifecycle.ts`(`withoutTrailingDots`、`ssoDomainTooLong`、`claimSentence` 的 child 分支)、`auth-manager.ts`(`assertSsoProviderDomainFree`:先判长度再解析)、`sso-provider-lifecycle.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/sso-provider-lifecycle.test.ts`,预期 29 个用例全过。 - 需要你做的:无,席位落地。 ## What changes `assertSsoProviderDomainFree` already refused `409 RESOURCE_CONFLICT` (`field: 'domain'`) an exact domain entry another provider lists. This PR closes N2 and N3b of contract review 6774898717, records why N3a stays open, and takes every finding of contract review 6787108839. **Measured vendor routing** (`@better-auth/sso` 1.7.12, `/sign-in/sso`, read from the installed `dist/index.mjs`): step 1 is `findOne({ domain: EMAIL_DOMAIN })`, an equality on the whole stored value; step 2 is `findMany({ model: 'ssoProvider' })` with no `sortBy`, then `.find(domainMatches)` (an entry equal to the domain, or the domain ending with `.` plus the entry). The adapter passes no `orderBy` when no `sortBy` is given, so "first" at step 2 is the store's row order, which no contract fixes. - **N2 fixed.** `findSsoDomainClaim` reads every provider row and returns one of three kinds. `exact` is the old rule. `parent`: the request lists a subdomain, does not win step 1 for it (its value is a list, or another spelling of the entry), and another provider lists the parent. `child`: the request lists a parent of an entry another provider holds in a list (or in another spelling). Judged in both registration orders, because row order is not registration order. `code`, `status`, `field` and the `heldBy` rule are unchanged. - **N3b fixed.** The store read is no longer narrowed by `$icontains` on the requested spelling. Every entry on both sides goes through one `bareDomain`: the URL parser's lower-case ASCII host (punycode for an internationalised name), trailing root dots dropped, as the vendor's own parse (`tldts`) does. - **N3a not fixed: recorded** in the seat's answer 6784574779 (no transaction on the vendor's register, no store constraint that expresses the rule, a claim table needs a backfill). - **N6, N7** as before: the `skip_user_info` edit pin through `/admin/sso/update-provider`, and the ruled wording in the `assertSsoProviderDeletable` comment. Contract review 6787108839: - **F1.** `bareDomain` runs no pattern: trailing dots are dropped by one backward index scan and one `slice` (`withoutTrailingDots`); the trailing-run pattern it replaces backtracked quadratically on a dot run that does not end the string. A length cap refuses before any parse, `400 VALIDATION_FAILED`, `field: 'domain'`, `fields: [{ field: 'domain', code: 'max_length' }]`: a value longer than **255** characters (`sys_sso_provider.domain` declares `maxLength: 255`, so a longer value could never be saved), or an entry longer than **253** characters (the DNS host-name limit: RFC 1035's 255-octet wire form less its leading length octet and the root label; one trailing root dot not counted). The cap is asked after the session check, so a sessionless caller's domain is only type-checked and trimmed, never parsed; the vendor answers that caller `401` as before. - **F2.** To a caller who is not a platform administrator, the `child` refusal names only the parent the request holds ("A subdomain of the email domain 'acme.example' is served by another SSO provider ..."), never the other provider's listed subdomain; a platform administrator is told the subdomain and `heldBy`. - **F3.** `winsExactStep` compares the stored value by plain equality, with no trim, as the vendor's step 1 does: a single entry stored padded with whitespace does not win step 1, so its parent is refused, and a padded subdomain requested beside a stored parent is refused. - **F4, F5 (changeset).** Two spelling legs are named as newly refused: a punycode entry requested beside the same name stored in Unicode, and the trailing root dot, either way round (`acme.com.` beside a stored `acme.com`, and `acme.com` beside a stored `acme.com.`). The reverse internationalised leg (Unicode requested beside punycode stored) was already refused on `main` and is named as such. The reason given is that the two spellings are one DNS domain; sign-in itself does not convert between Unicode and punycode. ## Tests `packages/plugins/plugin-auth/src/sso-provider-lifecycle.test.ts` (29 cases), on the real engine, `AuthManager`, `sso()` plugin and route registration: - refused `409` + `RESOURCE_CONFLICT` + `field: 'domain'`: a listed subdomain beside its parent (`eng.acme.example, foo.example`, `https://eng.acme.example`, `Eng.Acme.example`); a parent beside a listed subdomain; a domain edit adding a listed subdomain; `xn--bcher-kva.example` beside a stored `bücher.example`; `MÜNCHEN.example` and `xn--mnchen-3ya.example.` beside a stored `xn--mnchen-3ya.example`; `globex.example` beside a stored `globex.example.`. Nothing written in each case. - F2: the `child` refusal to an organization administrator (no `heldBy`, the requested parent only, no listed subdomain, no provider id) and to a platform administrator (`heldBy` and the subdomain), on the same request. - F3: a single entry stored as `' eng.acme.example '` does not shield its parent; `' eng.globex.example '` requested beside a stored `globex.example` is refused. - F1: a 300 000-dot value is refused `400 VALIDATION_FAILED` at `/sso/register` and `/sso/update-provider`, nothing written, and a sessionless caller gets the vendor's `401`; an entry of 254 characters is refused, one of 253 (with or without a root dot) is saved; `providerDomains` on a 200 000-dot entry returns within a 5 s bound. - controls that stay accepted: the single-entry subdomain beside its parent, both ways round; `xacme.example, foo.example` beside `acme.example`; `bucher.example` beside `bücher.example`. ## Acceptance notes - Not filed: with a parent `acme.com` and a child provider whose whole domain is `eng.acme.com` (the ruled-accepted configuration), a deeper name such as `x.eng.acme.com` matches both lists at step 2, so row order picks. The module comment says so. It is the ruled configuration, left as it is. - The vendor's step-2 read sees only `limit || 100` rows while this check reads every row: filed by the seat as #32388. - From review F5, a candidate follow-up rather than a fix here: a single-entry subdomain typed in Unicode beside its parent is refused as "another spelling", and the vendor will only ever match a provider stored in Unicode for an address typed in Unicode. ## Verification All readings at `7a24843d1c` (the final head: the F1 to F5 commits, then `origin/main` merged). <details> <summary>Tests and typecheck</summary> - `pnpm --filter @objectstack/plugin-auth test`: exit 0, Test Files 262 passed (262), Tests 4835 passed, 10 skipped (4845). - `pnpm --filter @objectstack/plugin-auth typecheck`: exit 0, `check:test-typecheck: OK`. </details> <details> <summary>Ablations (scripts/ablation-replace.mjs, each anchor 1 to 0, restored to the HEAD blob, `git diff HEAD` empty)</summary> - B1, the length cap off in `assertSsoProviderDomainFree`: red, the long-dot-run case and the over-long-entry case (2 of 29). - B2, the trailing-dot drop off in `bareDomain`: red, the spelling case at its dotted leg and the linear-scan case (2 of 29). - B3, the trailing-run pattern put back in place of the scan: red, the linear-scan case timed out at its 5000 ms bound (ran 28 553 ms; 1 of 29). </details> <details> <summary>Dogfood battery and gates</summary> - Whole battery, under the lock, no `OS_TEST_SHARD`, closure built at this head: `pnpm --filter @objectstack/dogfood test`, VERDICT command-exit 0, Test Files 451 passed, 3 skipped (454), Tests 3775 passed, 42 skipped (3817). One run, no failure. - `node scripts/pm/dispatch-gates.mjs --commands`: 75 derived families, all exit 0; `--ran` reconciliation 75 run, 0 NOT-MEASURED (a derived zero: every line records its exit code). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYm8sWjp2Pk76warN7w)_ <!-- signed: domain:server#7 · os-justin · session_01QSeKYm8sWjp2Pk76warN7w --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c5758b0 commit 0208b68

4 files changed

Lines changed: 567 additions & 50 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth)!: the SSO domain check refuses a subdomain listed beside its parent's provider, and compares every domain in one spelling
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type changes. The new refusals are answers of the auth routes to a request; no stored provider row is rewritten or re-checked by the upgrade, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** accept-set narrowing on SSO provider registration and provider domain edits (`@objectstack/plugin-auth`).
13+
14+
`POST /api/v1/auth/sso/register`, the `register_sso_provider` / `register_saml_provider` actions behind `/api/v1/auth/admin/sso/register` and `/register-saml`, and `POST /api/v1/auth/sso/update-provider` with a `domain` already refuse `409 RESOURCE_CONFLICT` (`field: 'domain'`) a domain entry another SSO provider lists. Sign-in first looks for a provider whose whole `domain` value equals the address's domain, then takes the first provider, in the store's row order, whose list holds the domain or a parent of it. Three more shapes are now refused the same way: the first two because sign-in would not reliably reach the second provider by address, the third because its two spellings name one DNS domain. Each was accepted before this release and saved the provider; each is now refused `409 RESOURCE_CONFLICT` with `field: 'domain'`, and nothing is saved:
15+
16+
- **A listed subdomain beside its parent's provider.** Before: `eng.acme.com, foo.com` (or `https://eng.acme.com`, or `Eng.Acme.com`), registered or written by a domain edit beside a provider for `acme.com`, was saved, and sign-in for `eng.acme.com` went to whichever of the two came first in row order. Now: refused, naming the parent entry (`through its entry 'acme.com'`) and, to a platform administrator, the provider that holds it (`heldBy`).
17+
- **A parent beside a provider that lists the subdomain.** Before: `acme.com`, registered or written by a domain edit beside a provider whose list holds `eng.acme.com`, was saved. Now: refused, naming the subdomain entry and, to a platform administrator, its provider.
18+
- **One domain in another spelling.** Two spelling legs are newly refused. First, a punycode entry requested beside the same name stored in Unicode (`xn--bcher-kva.de` beside a stored `bücher.de`): before, it was saved, because the store was narrowed by the raw text of the request. (The reverse internationalised leg, `MÜNCHEN.de` requested beside a stored `xn--mnchen-3ya.de`, was already refused: the request was parsed to punycode before the store was read.) Second, the trailing root dot, either way round (`acme.com.` beside a stored `acme.com`, and `acme.com` beside a stored `acme.com.`): before, both were saved, because each side kept its root dot when parsed. Now: every entry on both sides is compared as one lower-case ASCII host (punycode for an internationalised name, trailing root dot dropped), and both legs are refused because the two spellings are one DNS domain. Sign-in itself does not convert between Unicode and punycode, so each internationalised spelling routes only to a provider stored in that spelling; the refusal rests on the two being one DNS domain, which the platform gives one provider.
19+
20+
A `domain` too long to be a list of hosts is refused before it is read: `400 VALIDATION_FAILED` with `field: 'domain'` (and `fields: [{ field: 'domain', code: 'max_length' }]`) for a value longer than the 255 characters `sys_sso_provider.domain` holds, or an entry longer than the 253 characters of a host name (one trailing root dot not counted; a scheme or path around the host counts). Before: this check measured no length, and such a value went on to the vendor's own handling (an entry of 254 or 255 characters fits the column, so a register carrying one could be saved). Only a signed-in caller is answered so; without a session the vendor answers as before, and the value is not parsed.
21+
22+
Still accepted, either way round: a provider whose whole domain is exactly `eng.acme.com` beside one for `acme.com`, and entries that only look alike (`xacme.com` beside `acme.com`, `bucher.de` beside `bücher.de`). To register a refused provider, give the subdomain a provider whose only domain entry it is, or edit the parent (or the listed subdomain) off the provider that holds it.
23+
24+
**Providers already stored are not touched.** A pair that already collides in one of these shapes stays stored, and this release does not change how sign-in routes between them; nothing re-checks the store at upgrade or at boot. The check runs only on a request that writes a domain: a register, or an `update-provider` that carries `domain`. An `update-provider` without `domain` (an OIDC or SAML settings edit) is not judged and passes. An `update-provider` that carries `domain` is judged even when it re-saves the provider's stored value unchanged, so either provider of a stored colliding pair is refused `409` on a domain write until one of them edits the colliding entry off; after that, both save cleanly. Deleting either provider is not affected.
25+
26+
Two registers racing for one domain can still both pass: the check is a read before the vendor's insert, and the store holds no constraint that expresses the rule.

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

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ import {
136136
providerDomains,
137137
settleSsoProviderDelete as settleDeletedSsoProvider,
138138
ssoDomainClaimedRefusal,
139+
ssoDomainTooLong,
139140
stageSsoProviderDeleteImpact,
140141
} from './sso-provider-lifecycle.js';
141142
import {
@@ -5744,8 +5745,9 @@ export class AuthManager {
57445745
*
57455746
* [#32085] A delete the floor admits is then counted before the vendor's
57465747
* first write (`sso-provider-lifecycle.ts` `stageSsoProviderDeleteImpact`):
5747-
* the users it unlinks, those it locks out, the group mappings and projected
5748-
* grants it leaves behind. {@link settleSsoProviderDelete} removes those and
5748+
* the users it unlinks and, of those,
5749+
* users with no other sign-in method linked; the group mappings and
5750+
* projected grants it leaves behind. {@link settleSsoProviderDelete} removes those and
57495751
* names the counts in the answer. A count that cannot be read refuses the
57505752
* delete `503 SERVICE_UNAVAILABLE`, because an unlink cannot be taken back.
57515753
*/
@@ -5793,30 +5795,46 @@ export class AuthManager {
57935795
* already serves (`409 RESOURCE_CONFLICT`, `field: 'domain'`), before the
57945796
* vendor writes. Sign-in routes an address to a provider by its domain, so
57955797
* the second provider would not be reached by address
5796-
* (`sso-provider-lifecycle.ts` `findSsoDomainClaim`).
5798+
* (`sso-provider-lifecycle.ts` `findSsoDomainClaim`): the same entry, or a
5799+
* subdomain and its parent where the subdomain's provider does not hold it
5800+
* as its whole domain, each entry compared as one ASCII spelling.
57975801
*
57985802
* Asked only of an authenticated caller whose body carries a domain: what
57995803
* the vendor itself answers (no session, a malformed body) falls through to
5800-
* it. The holding provider is named to a platform administrator, who may
5801-
* read every provider; any other caller (an organization administrator on
5802-
* `/sso/update-provider`) is told only that the domain is served, which
5803-
* `/sign-in/sso` already answers anyone. A provider-table read that fails
5804+
* it, and nothing of the domain is parsed for a caller without a session.
5805+
* A value longer than a provider row holds, or with an entry longer than a
5806+
* host name, is refused `400 VALIDATION_FAILED` on `domain` before it is
5807+
* parsed (`ssoDomainTooLong`).
5808+
*
5809+
* The holding provider is named to a platform administrator, who may read
5810+
* every provider; any other caller (an organization administrator on
5811+
* `/sso/update-provider`) is told only that a domain its request names, or
5812+
* a subdomain of it, is served, which `/sign-in/sso` already answers anyone
5813+
* for a name they supply: never the row, nor the subdomain another
5814+
* provider lists. A provider-table read that fails
58045815
* refuses `503`: a guard that could not be evaluated does not pass.
58055816
*/
58065817
private async assertSsoProviderDomainFree(ctx: any): Promise<void> {
58075818
const path = ctx?.path;
58085819
if (path !== SSO_PROVIDER_REGISTER_PATH && path !== SSO_PROVIDER_UPDATE_PATH) return;
5809-
const domains = providerDomains(ctx?.body?.domain);
5810-
if (domains.length === 0) return;
5820+
const requested: unknown = ctx?.body?.domain;
5821+
if (typeof requested !== 'string' || !requested.trim()) return;
58115822
const engine = this.getDataEngine();
58125823
if (!engine) return;
58135824
const actor = await this.resolveActor(ctx);
58145825
if (!actor?.userId) return;
5815-
const providerId = typeof ctx?.body?.providerId === 'string' ? ctx.body.providerId : '';
58165826
const { APIError } = await import('better-auth/api');
5827+
// Lengths before any parse: the value is request-controlled.
5828+
const tooLong = ssoDomainTooLong(requested);
5829+
if (tooLong) {
5830+
throw new APIError(tooLong.status, { code: tooLong.code, message: tooLong.message, field: tooLong.field, fields: tooLong.fields });
5831+
}
5832+
const domains = providerDomains(requested);
5833+
if (domains.length === 0) return;
5834+
const providerId = typeof ctx?.body?.providerId === 'string' ? ctx.body.providerId : '';
58175835
let claim;
58185836
try {
5819-
claim = await findSsoDomainClaim(engine, domains, path === SSO_PROVIDER_UPDATE_PATH ? providerId : undefined);
5837+
claim = await findSsoDomainClaim(engine, requested, path === SSO_PROVIDER_UPDATE_PATH ? providerId : undefined);
58205838
} catch {
58215839
throw new APIError('SERVICE_UNAVAILABLE', {
58225840
code: 'SERVICE_UNAVAILABLE',

0 commit comments

Comments
 (0)