Skip to content

Commit 38c528e

Browse files
fix(plugin-auth): a refused IdP-initiated SAML sign-in lands on the platform's sign-in page with its error (#32193)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB5566d24165XFeca3tgBhXU)_ Fixes #32132 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么:** 企业用户在 IdP 门户(如 Okta 应用图标)直接发起 SAML 登录、而服务端拒绝时(默认没有开「允许 IdP 发起登录」),拒绝现在落到 Console 登录页 `/_console/login?error=unsolicited_response`,和其他 SAML 拒绝、OIDC 拒绝是同一个页面。只改 plugin-auth 的 SAML 拒绝落地层,没有新增任何接受路径。 - **为什么改:** 以前这次拒绝跳到站点根 `/?error=unsolicited_response`,根路径再跳 `/_console/` 时把参数丢了,登录页什么都不显示,用户只看到被弹回来(cloud#3666 的 Okta 实测遇到)。 - **风险与回滚:** 只移动拒绝响应的 `Location`:拒绝照旧是拒绝,不发会话、不建用户(测试有断言);允许 IdP 发起时的成功登录照旧落站点根;运营方给 provider 配了自己的 `idpInitiatedCallbackUrl` 的,拒绝照旧落那里。回滚 = revert 本 PR。 - **先看:** `packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.ts` 的 `readSamlAcsLanding`(无 relay state 时的新分支)和 `isOnBareFallback` / `landSamlRefusal`(只改写站点根上的拒绝);然后是测试文件里新增的 describe。 - **两分钟验证:** `pnpm --filter @objectstack/plugin-auth exec vitest run src/sso-saml-refusal-landing.test.ts`,预期 31 个测试全绿;其中 `off (the default)` 一条断言落点是 `http://localhost:3000/_console/login`、`error=unsolicited_response`。 - **需要你做的:** 无,席位落地。之后 UI 卡 #32087 在 `ssoCallbackRefusal.ts` 为 `unsolicited_response` 加一行文案。 ## Step 0: the three readings (at `origin/main` `45f0f81f`) Taken through the real SAML ACS harness (`sso-saml-refusal-landing.test.ts`: a real `AuthManager` and the real `@better-auth/sso` 1.7.12, the IdP played with `samlify`) and the OIDC harness (`sso-oidc-refusal-cause.test.ts`), with the source of both modules at `45f0f81f` and a throwaway probe that wrote each 302 `Location` to a scratch file (removed; `git diff HEAD` empty afterwards). | Refusal | Test | 302 `Location` at `45f0f81f` | |---|---|---| | SAML `account_not_linked`, sign-in with no `errorCallbackURL` | `takeover with no errorCallbackURL: lands on the platform error page, …` | `http://localhost:3000/_console/login?error=account_not_linked` | | SAML `saml_error` (tampered assertion), same sign-in | same test | `http://localhost:3000/_console/login?error=saml_error&error_description=Invalid+SAML+response` | | **SAML `unsolicited_response`** (IdP-initiated, toggle off) | `off (the default): an unsolicited Response is refused …` | `http://localhost:3000/?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed` | | SAML IdP-initiated, toggle on (success, control) | `on: the same Response signs the person in` | `http://localhost:3000` | | OIDC `state_not_found` (IdP-initiated, toggle off) | OIDC `off (the default): a stateless callback is refused …` | `http://localhost:3000/_console/login?error=state_not_found` | With an `errorCallbackURL`, every SAML refusal lands there instead (`takeover: lands on errorCallbackURL …`, `a refusal the vendor already lands on errorCallbackURL …`). **OIDC (PR #32129, merged as `cc8c4b0f`).** That PR changes no server code: its files are all under `ui/**` plus a changeset. OIDC's landing is the vendor's own: `@better-auth/sso` sends `state_not_found` to `onAPIError.errorURL`, which plugin-auth sets to the console login page (`auth-manager-auth-instance.ts`, `getConsolePageUrl('/login')`). The SAML refusal now lands on that same URL. **Why SAML landed on the root** (read in `@better-auth/sso` 1.7.12, `processSAMLResponse` and `validateInResponseTo`). With no relay state, the vendor's target is the first safe one of the provider's `idpInitiatedCallbackUrl`, the plugin's `saml.idpInitiatedCallbackUrl` and the provider's `callbackUrl`, else the bare app origin. The Register SAML Provider bridge stores `callbackUrl` as the ACS itself, which the vendor's safety rule refuses, and sets neither IdP-initiated callback, so the target is the app origin. For a response with no relay state the error target is that same URL, and `validateInResponseTo` builds `unsolicited_response` on it. plugin-auth's SAML landing scope read the relay state only, so it left this answer alone. ## FROM → TO | | Landing | |---|---| | FROM | `http://localhost:3000/?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed` (then `/` redirects to `/_console/` and the query is gone) | | TO | `http://localhost:3000/_console/login?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed` | **Door: the landing, not the root redirect.** The refusal can know the login URL: the SAML landing scope already reads `onAPIError.errorURL` before the vendor runs, and only skipped a response with no relay state. Keeping the query through the `/` redirects in `packages/cli/src/utils/console.ts` would put the user on `/_console/?error=…`, which is not the page that reads `?error=` (the login page is), so it would also need a console change, and it would change every `/` visit. `console.ts` is not touched. ## What changes `packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.ts` (internal module, not exported from the package): - `readSamlAcsLanding`: a response with no relay-state row to read (no `RelayState`, no row, an unreadable row, or one that names no `callbackURL`) now answers `{ fallback: appOrigin, error: platformErrorPage }` instead of nothing. The platform error page is the default a sign-in with no `errorCallbackURL` lands on (`onAPIError.errorURL`, else `baseURL/error`), checked with the same vendor safety rule; an unsafe one still answers nothing, and the vendor's answer stands. - `landSamlRefusal`: for that landing, only a redirect that carries `error=` and sits on the bare fallback (the site root, no fragment, no query but `error` and `error_description`) is re-based onto the platform error page, `error` and `error_description` as the vendor wrote them, every other header kept. A success (`http://localhost:3000`, no query) and any IdP-initiated callback an operator configured are returned untouched. - The module docblock's "SAML: where a refusal lands" section states the new case; `auth-manager.ts` `runSsoCallback`'s docblock names it (comment only). **Security posture.** The vendor still runs and refuses exactly as before. Only the `Location` of a 302 that already carries `error=` moves, to the platform's own login page, through the vendor's redirect safety rule. No unsolicited Response is newly accepted; the tests assert the refused Response sets no session cookie and creates no user. **Same class, same rule.** With the toggle on, an IdP-initiated sign-in refused for another reason (`SELF_REGISTRATION_CLOSED`, `account_not_linked`, `saml_error`) sat on the same root and lost its error the same way. The one rule covers it; the tests pin each. ## Tests All in the shared harness `packages/plugins/plugin-auth/src/sso-saml-refusal-landing.test.ts` (its `makeRp` gains a `samlConfig` option, `idpInitiated` a `shapeResponse`): - `off (the default) …` now asserts the landing `{ base: '…/_console/login', error: 'unsolicited_response' }`, status 302, no session cookie and no user created; `another provider's toggle does not open this one` asserts the same landing. - New describe `a refused IdP-initiated SAML sign-in lands on the platform error page, as one with no errorCallbackURL does`: `SELF_REGISTRATION_CLOSED`, `account_not_linked` and `saml_error` (tampered Response) each land on the login page with no session; CONTROL an allowed IdP-initiated sign-in still lands on `http://localhost:3000` with a session; CONTROL a provider's own `idpInitiatedCallbackUrl` keeps its `unsolicited_response` there. - Unit: `readSamlAcsLanding` answers the fallback landing for no `RelayState`, no row, an unreadable row and a row with no `callbackURL`; the `baseURL/error` default; no landing for an unsafe platform page. `landSamlRefusal` re-bases a root refusal (absolute and relative) and leaves the success and six other shapes alone (a configured callback, the root with a query of its own, a fragment, another origin, a protocol-relative URL). ## Acceptance notes - The UI half, one `unsolicited_response` row in `ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts`, is #32087's. Until it lands, the login page shows the generic SSO sentence with the code under Technical details. - `content/docs/permissions/sso.mdx` ("IdP-initiated sign-in") already says this refusal "redirects to the error page with `error=unsolicited_response`". After this PR that is what happens, so the page is not edited. - The unreleased `.changeset/30966-saml-refusal-lands-on-error-url.md` says every SAML refusal now lands where OIDC's does. This PR closes the IdP-initiated exception to that sentence, so it becomes true and is not edited. - One shape the bare-fallback rule cannot tell apart: an IdP-initiated callback an operator configures as the site root with an `error` query of its own (`/?error=x`). A successful sign-in there would be re-based to the login page, still signed in. Nobody configures that; noted, not handled. ## Verification Readings name the head they were taken at. <details> <summary>plugin-auth tests, build, typecheck, eslint</summary> At `9d1fa1e5` (the fix and its changeset; `623d29e3` after it changes two docblocks only), under `scripts/pm/os-verify-lock.sh`: - `vitest run src/sso-saml-refusal-landing.test.ts src/sso-oidc-refusal-cause.test.ts`: Test Files 2 passed (2), Tests 67 passed (67); the same two files at `45f0f81f`: 59 passed. - `vitest run` over the whole package: Test Files 255 passed (255), Tests 4595 passed, 10 skipped (4605), exit 0. - `pnpm --filter @objectstack/plugin-auth build`: exit 0. `pnpm typecheck` (tsc, the examples project, `check:test-typecheck`): exit 0. At `6be22da7` (after `git merge origin/main`: 9 commits, none under `packages/plugins/plugin-auth` or `packages/cli`): `pnpm install --frozen-lockfile` exit 0; `pnpm --filter '@objectstack/plugin-auth...' build` exit 0; the whole package again Test Files 255 passed (255), Tests 4595 passed, 10 skipped, exit 0; `pnpm typecheck` exit 0. `eslint --no-inline-config` over the three changed source files: exit 0. `node scripts/check-nul-bytes.mjs`: exit 0. </details> <details> <summary>Ablation (the landing pin, once)</summary> At `9d1fa1e5`, `node scripts/ablation-replace.mjs` on `sso-oidc-refusal-cause.ts`: anchor `return error ? { fallback: appOrigin, error } : undefined;` (x1 to x0) replaced by `return undefined; // ABLATED-32132 …` (x0 to x1), which puts the old landing back (a response with no relay state keeps the vendor's answer); blob `0679c797` to `903ad1f7`. The tests import the source directly (`./auth-manager`), so no build sits between the mutation and the run. - `vitest run src/sso-saml-refusal-landing.test.ts`: 7 failed, 24 passed (31). The `off (the default)` case received `base: "http://localhost:3000/"` against the expected `http://localhost:3000/_console/login`: the FROM landing. The other six reds are the new describe's three refusals, `another provider's toggle`, and the two `readSamlAcsLanding` cases. The two CONTROL cases and the `landSamlRefusal` unit cases stayed green, as they should. - Restored: blob after restore `0679c797` equals the HEAD blob, `git diff HEAD` empty. </details> <details> <summary>Derived gates (dispatch-gates --commands, then --ran)</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 74 families for the 4 changed paths (241 changed lines). Each ran serially; the record is `CMD :: exit N` per line. - At `6be22da7` (the head this PR opens with): 74 of 74 exit 0. `dispatch-gates --ran`: "74 derived, 74 run, 0 NOT-MEASURED, 0 UNRUN". - At `623d29e3` (before the main merge, same 74-family list): 73 exit 0; `check:dual-build-cjs-loads` exit 3 (PREREQUISITE NOT MET: unbuilt dist), measured exit 0 at `6be22da7` once the post-merge build had built plugin-auth's dependents. `check:changeset-no-major`, `check-empty-changeset` and `check:adr-0087-registration` (all in the 74) read the committed changeset `.changeset/32132-saml-idp-initiated-refusal-landing.md` (`@objectstack/plugin-auth` patch). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (n/a, not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (no formatter ran; eslint over the three changed source files exit 0; the repo-wide run is CI's `Lint & Repo Gates`) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. (`@objectstack/plugin-auth` patch) - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (n/a) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [ ] 8. Title, body and comments are in English. (the 维护者速读 section is in Chinese, as the dispatch order asks) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfp1uE2GE28SdQSaqN)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9052363 commit 38c528e

4 files changed

Lines changed: 204 additions & 37 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): a refused IdP-initiated SAML sign-in lands on the platform's sign-in page with its error
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A SAML sign-in the identity provider starts on its own (an Okta or Entra app tile) carries no relay state, so `@better-auth/sso` redirected every refusal of it to the bare app origin, for example `/?error=unsolicited_response` when the provider's `allowIdpInitiated` option is off. The Console's root redirect drops the query string, so the sign-in page showed nothing. Such a refusal now lands on the platform's sign-in page (`/_console/login`), the same page a sign-in that names no `errorCallbackURL` lands on, with `error=` and `error_description` unchanged: `unsolicited_response`, and also `SELF_REGISTRATION_CLOSED`, `account_not_linked` or `saml_error` when the option is on. The refusal is unchanged otherwise, and nobody is signed in. An allowed IdP-initiated sign-in still lands on the app origin, and a provider whose stored SAML configuration names its own `idpInitiatedCallbackUrl` keeps sending its refusals there.

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4032,7 +4032,8 @@ export class AuthManager {
40324032
* whose refusal names its cause on the redirect's `error_description` and in
40334033
* one `warn` line on this manager's logger, and a SAML ACS
40344034
* (`/sso/saml2/sp/acs/:providerId`) whose refusal lands on the sign-in's error
4035-
* URL, read from the relay state before better-auth consumes it.
4035+
* URL, read from the relay state before better-auth consumes it, or for an
4036+
* IdP-initiated response (no relay state) on the platform error page.
40364037
*/
40374038
private runSsoCallback(callback: SsoCallbackRequest, run: () => Promise<Response>): Promise<Response> {
40384039
// A SAML ACS request runs with its provider's IdP-initiated toggle in

‎packages/plugins/plugin-auth/src/sso-oidc-refusal-cause.ts‎

Lines changed: 89 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,23 @@
7979
* is then a redirect carrying `error=` that is not the success URL, it is
8080
* re-based onto that error URL with its `error` and `error_description` as
8181
* the vendor wrote them, built the way the vendor builds every other SAML
82-
* refusal. A refusal already on the error URL comes out byte-identical; a
83-
* success, an IdP-initiated response (no relay state), and a relay state the
84-
* vendor itself cannot read are left as the vendor answered them.
82+
* refusal. A refusal already on the error URL comes out byte-identical, and a
83+
* success is left as the vendor answered it.
84+
*
85+
* A response with no relay-state row to read (IdP-initiated: no `RelayState`,
86+
* or one this app never wrote or cannot read) names no error URL. The vendor
87+
* lands it, success and refusal alike, on the provider's IdP-initiated
88+
* callback, and with none configured (every provider the Register SAML
89+
* Provider bridge stores) on its fallback, the bare app origin. The site root
90+
* reads no `?error=`: the console mount redirects `/` to the console without
91+
* the query, so the refusal reached the sign-in page with nothing to show.
92+
* {@link readSamlAcsLanding} answers such a response with the platform error
93+
* page (`onAPIError.errorURL`, the default a sign-in that names no
94+
* `errorCallbackURL` lands on), and only a refusal on the bare fallback (the
95+
* site root, with no query but the refusal's own `error` and
96+
* `error_description`) is re-based onto it. Any other IdP-initiated callback an
97+
* operator configured is their landing and is left as the vendor answered it.
98+
* The refusal stays a refusal: only its `Location` moves.
8599
*/
86100

87101
import { AsyncLocalStorage } from 'node:async_hooks';
@@ -371,11 +385,16 @@ export interface SamlLandingContext {
371385
internalAdapter: { findVerificationValue: (identifier: string) => Promise<{ value: string } | null | undefined> };
372386
}
373387

374-
/** Where one SAML sign-in lands: its success URL, and the error URL for every refusal. */
375-
export interface SamlAcsLanding {
376-
success: string;
377-
error: string;
378-
}
388+
/**
389+
* Where one SAML sign-in lands.
390+
*
391+
* - A sign-in this app started (its relay-state row read): its `success` URL,
392+
* and the `error` URL for every refusal.
393+
* - A response with no relay-state row to read (IdP-initiated): `fallback` is
394+
* the vendor's last-resort landing, the bare app origin, and only a refusal
395+
* on it is re-based onto `error`, the platform error page.
396+
*/
397+
export type SamlAcsLanding = { success: string; error: string } | { fallback: string; error: string };
379398

380399
/** The `RelayState` an ACS `POST` carries, form-encoded or JSON (the two media types the vendor admits). */
381400
async function relayStateOf(request: Request): Promise<string | undefined> {
@@ -427,19 +446,16 @@ function safeSamlTarget(
427446
}
428447

429448
/**
430-
* Where this ACS request's refusals land, read BEFORE the vendor runs: the
431-
* relay-state row the vendor wrote at `/sign-in/sso` (`auth-state:<RelayState>`,
432-
* read through the vendor's own `internalAdapter`, which the vendor deletes
433-
* once it has read it), with the same default and the same safety rule the
434-
* vendor applies to it. `undefined` when there is no relay state, the row is
435-
* gone or unreadable, or the error URL is not a safe target: the vendor then
436-
* has no error URL either, and its answer stands.
449+
* The relay-state row the vendor wrote at `/sign-in/sso` for this ACS request
450+
* (`auth-state:<RelayState>`, read through the vendor's own `internalAdapter`,
451+
* which the vendor deletes once it has read it), or `undefined` when there is
452+
* no relay state, the row is gone, or it is unreadable or names no
453+
* `callbackURL`.
437454
*/
438-
export async function readSamlAcsLanding(
455+
async function readRelayStateRow(
439456
context: SamlLandingContext,
440-
providerId: string,
441457
request: Request,
442-
): Promise<SamlAcsLanding | undefined> {
458+
): Promise<{ callbackURL: string; errorURL?: unknown } | undefined> {
443459
const relayState = await relayStateOf(request);
444460
if (!relayState) return undefined;
445461
const row = await context.internalAdapter.findVerificationValue(`auth-state:${relayState}`);
@@ -450,14 +466,37 @@ export async function readSamlAcsLanding(
450466
} catch {
451467
return undefined;
452468
}
453-
if (typeof state?.callbackURL !== 'string') return undefined;
454-
const errorURL =
455-
typeof state.errorURL === 'string' && state.errorURL
456-
? state.errorURL
457-
: context.options.onAPIError?.errorURL || `${context.baseURL}/error`;
469+
return typeof state?.callbackURL === 'string' ? { callbackURL: state.callbackURL, errorURL: state.errorURL } : undefined;
470+
}
471+
472+
/**
473+
* Where this ACS request's refusals land, read BEFORE the vendor runs, with the
474+
* same default and the same safety rule the vendor applies to an error URL:
475+
*
476+
* - with a relay-state row, the sign-in's own error URL (its
477+
* `errorCallbackURL`, else the platform error page);
478+
* - with none (an IdP-initiated response), the platform error page, for a
479+
* refusal the vendor puts on its bare app-origin fallback.
480+
*
481+
* `undefined` when that error URL is not a safe target: the vendor then has no
482+
* error URL either, and its answer stands.
483+
*/
484+
export async function readSamlAcsLanding(
485+
context: SamlLandingContext,
486+
providerId: string,
487+
request: Request,
488+
): Promise<SamlAcsLanding | undefined> {
489+
const platformErrorURL = context.options.onAPIError?.errorURL || `${context.baseURL}/error`;
458490
const appOrigin = new URL(context.baseURL).origin;
459491
const acsPathname = new URL(`${context.baseURL}${SAML_ACS_PATH_PREFIX}${providerId}`).pathname;
460-
const error = safeSamlTarget(errorURL, acsPathname, appOrigin, context.isTrustedOrigin);
492+
const safe = (url: string) => safeSamlTarget(url, acsPathname, appOrigin, context.isTrustedOrigin);
493+
const state = await readRelayStateRow(context, request);
494+
if (!state) {
495+
const error = safe(platformErrorURL);
496+
return error ? { fallback: appOrigin, error } : undefined;
497+
}
498+
const errorURL = typeof state.errorURL === 'string' && state.errorURL ? state.errorURL : platformErrorURL;
499+
const error = safe(errorURL);
461500
return error ? { success: state.callbackURL, error } : undefined;
462501
}
463502

@@ -477,14 +516,37 @@ function rebaseSamlRefusal(location: string, target: string): string {
477516
return target.startsWith('/') && !target.startsWith('//') ? `${url.pathname}${url.search}${url.hash}` : url.toString();
478517
}
479518

519+
/**
520+
* Whether `location` sits on the vendor's bare app-origin fallback: the site
521+
* root, with no fragment and no query but the `error` and `error_description`
522+
* the vendor sets on a refusal. The fallback itself carries no query, so a
523+
* success there carries no `error=` and is never re-based.
524+
*/
525+
function isOnBareFallback(location: string, fallback: string): boolean {
526+
let url: URL;
527+
try {
528+
url = new URL(location, fallback);
529+
} catch {
530+
return false;
531+
}
532+
return (
533+
url.origin === new URL(fallback).origin &&
534+
url.pathname === '/' &&
535+
url.hash === '' &&
536+
[...url.searchParams.keys()].every((key) => key === 'error' || key === 'error_description')
537+
);
538+
}
539+
480540
/**
481541
* Put one SAML ACS answer on its landing: a redirect that carries `error=` and
482-
* is not the success URL is re-based onto the error URL. Every other answer is
483-
* returned untouched.
542+
* is not the success URL (for an IdP-initiated response: that sits on the bare
543+
* fallback) is re-based onto the error URL. Every other answer is returned
544+
* untouched.
484545
*/
485546
export function landSamlRefusal(response: Response, landing: SamlAcsLanding): Response {
486547
const location = response.headers.get('location');
487-
if (!location || location === landing.success) return response;
548+
if (!location) return response;
549+
if ('success' in landing ? location === landing.success : !isOnBareFallback(location, landing.fallback)) return response;
488550
if (!new URL(location, 'http://better-auth.local').searchParams.has('error')) return response;
489551
const landed = rebaseSamlRefusal(location, landing.error);
490552
if (landed === location) return response;

‎packages/plugins/plugin-auth/src/sso-saml-refusal-landing.test.ts‎

Lines changed: 103 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,8 @@ interface RpOptions {
116116
provider?: Record<string, unknown>;
117117
/** Extra `AuthManager` config (e.g. `audience`). */
118118
config?: Record<string, unknown>;
119+
/** Extra stored SAML configuration members (e.g. `idpInitiatedCallbackUrl`). */
120+
samlConfig?: Record<string, unknown>;
119121
}
120122

121123
async function makeRp(opts: RpOptions = {}): Promise<Rp> {
@@ -150,6 +152,7 @@ async function makeRp(opts: RpOptions = {}): Promise<Rp> {
150152
identifierFormat: EMAIL_FORMAT,
151153
idpMetadata: { entityID: IDP_ENTITY },
152154
spMetadata: { entityID: SP_ENTITY },
155+
...opts.samlConfig,
153156
}),
154157
...opts.provider,
155158
},
@@ -329,10 +332,19 @@ describe('reading the landing from the relay state', () => {
329332
expect(await readSamlAcsLanding(ctx, PROVIDER_ID, acsPost('RelayState=rs'))).toEqual({ success: AFTER, error: CONSOLE_LOGIN });
330333
});
331334

332-
it('no landing without a relay state, a row, or a readable row', async () => {
333-
expect(await readSamlAcsLanding(context(stateRow({ callbackURL: AFTER })), PROVIDER_ID, acsPost('SAMLResponse=x'))).toBeUndefined();
334-
expect(await readSamlAcsLanding(context(null), PROVIDER_ID, acsPost('RelayState=rs'))).toBeUndefined();
335-
expect(await readSamlAcsLanding(context({ value: '{not json' }), PROVIDER_ID, acsPost('RelayState=rs'))).toBeUndefined();
335+
it('with no relay state, no row, or no readable row (IdP-initiated): the platform error page, for the bare fallback', async () => {
336+
const idpInitiatedLanding = { fallback: BASE, error: CONSOLE_LOGIN };
337+
expect(await readSamlAcsLanding(context(stateRow({ callbackURL: AFTER })), PROVIDER_ID, acsPost('SAMLResponse=x'))).toEqual(idpInitiatedLanding);
338+
expect(await readSamlAcsLanding(context(null), PROVIDER_ID, acsPost('RelayState=rs'))).toEqual(idpInitiatedLanding);
339+
expect(await readSamlAcsLanding(context({ value: '{not json' }), PROVIDER_ID, acsPost('RelayState=rs'))).toEqual(idpInitiatedLanding);
340+
expect(await readSamlAcsLanding(context(stateRow({ errorURL: FAILED })), PROVIDER_ID, acsPost('RelayState=rs'))).toEqual(idpInitiatedLanding);
341+
});
342+
343+
it('with no relay-state row and no platform error page configured, the vendor default; an unsafe one, no landing', async () => {
344+
const bare = { ...context(null), options: {} };
345+
expect(await readSamlAcsLanding(bare, PROVIDER_ID, acsPost('SAMLResponse=x'))).toEqual({ fallback: BASE, error: `${AUTH}/error` });
346+
const elsewhere = { ...context(null), options: { onAPIError: { errorURL: 'https://elsewhere.example/login' } } };
347+
expect(await readSamlAcsLanding(elsewhere, PROVIDER_ID, acsPost('SAMLResponse=x'))).toBeUndefined();
336348
});
337349

338350
it('applies the vendor redirect safety rule to the error URL', async () => {
@@ -375,6 +387,31 @@ describe('putting an ACS answer on its landing', () => {
375387
expect(landSamlRefusal(json, landingOf)).toBe(json);
376388
});
377389

390+
it('IdP-initiated: a refusal on the bare app-origin fallback is re-based onto the platform error page, every header kept', () => {
391+
const idp = { fallback: BASE, error: CONSOLE_LOGIN };
392+
const res = landSamlRefusal(redirect(`${BASE}/?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed`), idp);
393+
expect(res.status).toBe(302);
394+
expect(res.headers.get('location')).toBe(`${CONSOLE_LOGIN}?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed`);
395+
expect(res.headers.get('set-cookie')).toBe('a=1');
396+
expect(landSamlRefusal(redirect('/?error=account_not_linked'), idp).headers.get('location')).toBe(`${CONSOLE_LOGIN}?error=account_not_linked`);
397+
});
398+
399+
it('IdP-initiated: a success on the fallback, and anything not on the bare fallback, are left alone', () => {
400+
const idp = { fallback: BASE, error: CONSOLE_LOGIN };
401+
for (const location of [
402+
BASE, // the vendor's success on its fallback
403+
`${BASE}/`,
404+
`${BASE}/sso-landing?error=unsolicited_response`, // a configured IdP-initiated callback
405+
`${BASE}/?tenant=acme&error=unsolicited_response`, // the root, with a query of its own
406+
`${BASE}/?error=unsolicited_response#top`,
407+
`https://elsewhere.example/?error=unsolicited_response`,
408+
`//elsewhere.example/?error=unsolicited_response`,
409+
]) {
410+
const res = redirect(location);
411+
expect(landSamlRefusal(res, idp), location).toBe(res);
412+
}
413+
});
414+
378415
it('with no landing read, the vendor answer stands', async () => {
379416
const vendor = redirect(`${AFTER}?error=account_not_linked`);
380417
const saml = { protocol: 'saml' as const, providerId: PROVIDER_ID, request: new Request(ACS, { method: 'POST' }) };
@@ -393,7 +430,11 @@ const seedAdmin = async (rp: Rp) => {
393430
};
394431

395432
/** An IdP-initiated Response: the IdP posts an assertion no AuthnRequest asked for (no InResponseTo, no RelayState). */
396-
async function idpInitiated(rp: Rp, email: string): Promise<Response> {
433+
async function idpInitiated(
434+
rp: Rp,
435+
email: string,
436+
shapeResponse: (samlResponse: string) => string = (r) => r,
437+
): Promise<Response> {
397438
const spMetadata = await (await rp.manager.handleRequest(
398439
new Request(`${AUTH}/sso/saml2/sp/metadata?providerId=${PROVIDER_ID}`),
399440
)).text();
@@ -411,19 +452,20 @@ async function idpInitiated(rp: Rp, email: string): Promise<Response> {
411452
new Request(ACS, {
412453
method: 'POST',
413454
headers: { 'content-type': 'application/x-www-form-urlencoded' },
414-
body: new URLSearchParams({ SAMLResponse: context }).toString(),
455+
body: new URLSearchParams({ SAMLResponse: shapeResponse(context) }).toString(),
415456
}),
416457
);
417458
}
418459

419460
describe('SAML IdP-initiated sign-in is a per-provider toggle, off by default', () => {
420-
it('off (the default): an unsolicited Response is refused 302 error=unsolicited_response, and signs nobody in', async () => {
461+
it('off (the default): an unsolicited Response is refused 302 error=unsolicited_response on the platform error page, and signs nobody in', async () => {
421462
const rp = await makeRp({ provider: { allowJit: true } });
422463
await seedAdmin(rp);
423464
const res = await idpInitiated(rp, 'new.person@acme.com');
424465
expect(res.status).toBe(302);
425-
expect(landing(res).error).toBe('unsolicited_response');
466+
expect(landing(res)).toEqual({ base: CONSOLE_LOGIN, error: 'unsolicited_response' });
426467
expect(cookiesOf(res)).not.toMatch(/session_token=[^;]/);
468+
expect(rp.engine.tables.get('sys_user')?.map((u: any) => u.email)).toEqual(['admin@acme.com']);
427469
});
428470

429471
it('on: the same Response signs the person in', async () => {
@@ -445,7 +487,8 @@ describe('SAML IdP-initiated sign-in is a per-provider toggle, off by default',
445487
data: { providerId: 'other-idp', issuer: 'https://other.example/entity', domain: 'other.example', allowIdpInitiated: true },
446488
});
447489
const res = await idpInitiated(rp, 'new.person@acme.com');
448-
expect(landing(res).error).toBe('unsolicited_response');
490+
expect(landing(res)).toEqual({ base: CONSOLE_LOGIN, error: 'unsolicited_response' });
491+
expect(cookiesOf(res)).not.toMatch(/session_token=[^;]/);
449492
});
450493

451494
it('CONTROL: an SP-initiated sign-in is answered as before with the toggle off', async () => {
@@ -457,6 +500,57 @@ describe('SAML IdP-initiated sign-in is a per-provider toggle, off by default',
457500
});
458501
});
459502

503+
describe('a refused IdP-initiated SAML sign-in lands on the platform error page, as one with no errorCallbackURL does', () => {
504+
// With no relay state the vendor lands every IdP-initiated answer on its
505+
// fallback, the bare app origin, whose console redirect drops the query.
506+
507+
it('on, but the person may not be provisioned: error=SELF_REGISTRATION_CLOSED on the platform error page, no user created', async () => {
508+
const rp = await makeRp({ provider: { allowIdpInitiated: true } });
509+
await seedAdmin(rp);
510+
const res = await idpInitiated(rp, 'new.person@acme.com');
511+
expect(res.status).toBe(302);
512+
expect(landing(res)).toEqual({ base: CONSOLE_LOGIN, error: 'SELF_REGISTRATION_CLOSED' });
513+
expect(cookiesOf(res)).not.toMatch(/session_token=[^;]/);
514+
expect(rp.engine.tables.get('sys_user')?.map((u: any) => u.email)).toEqual(['admin@acme.com']);
515+
});
516+
517+
it('on, and the email belongs to an account this provider is not linked to: error=account_not_linked on the platform error page', async () => {
518+
const rp = await makeRp({ provider: { allowIdpInitiated: true, allowJit: true } });
519+
await rp.engine.insert('sys_user', { id: 'usr_known', email: KNOWN_EMAIL, name: 'Mia Chen', email_verified: true });
520+
const res = await idpInitiated(rp, KNOWN_EMAIL);
521+
expect(res.status).toBe(302);
522+
expect(landing(res)).toEqual({ base: CONSOLE_LOGIN, error: 'account_not_linked' });
523+
expect(cookiesOf(res)).not.toMatch(/session_token=[^;]/);
524+
});
525+
526+
it("a Response the vendor's signature check refuses: error=saml_error on the platform error page", async () => {
527+
const rp = await makeRp({ provider: { allowIdpInitiated: true, allowJit: true } });
528+
await seedAdmin(rp);
529+
const res = await idpInitiated(rp, 'someone@acme.com', tamper);
530+
expect(res.status).toBe(302);
531+
expect(landing(res)).toEqual({ base: CONSOLE_LOGIN, error: 'saml_error' });
532+
expect(cookiesOf(res)).not.toMatch(/session_token=[^;]/);
533+
});
534+
535+
it('CONTROL: an allowed IdP-initiated sign-in still lands on the app origin, signed in', async () => {
536+
const rp = await makeRp({ provider: { allowIdpInitiated: true, allowJit: true } });
537+
await seedAdmin(rp);
538+
const res = await idpInitiated(rp, 'new.person@acme.com');
539+
expect(res.status).toBe(302);
540+
expect(res.headers.get('location')).toBe(BASE);
541+
expect(cookiesOf(res)).toMatch(/session_token=[^;]/);
542+
});
543+
544+
it("CONTROL: a provider's own IdP-initiated callback keeps its refusals, as the operator configured", async () => {
545+
const rp = await makeRp({ provider: { allowJit: true }, samlConfig: { idpInitiatedCallbackUrl: `${BASE}/sso-landing` } });
546+
await seedAdmin(rp);
547+
const res = await idpInitiated(rp, 'new.person@acme.com');
548+
expect(res.status).toBe(302);
549+
expect(landing(res)).toEqual({ base: `${BASE}/sso-landing`, error: 'unsolicited_response' });
550+
expect(cookiesOf(res)).not.toMatch(/session_token=[^;]/);
551+
});
552+
});
553+
460554
describe('invite_only refuses an unknown SAML user unless the provider allows JIT', () => {
461555
it('invite_only (the default) + no account + no invitation: refused 302 error=SELF_REGISTRATION_CLOSED on the error URL, no user created', async () => {
462556
const rp = await makeRp();

0 commit comments

Comments
 (0)