Skip to content

Commit a5f5e9d

Browse files
committed
fix(plugin-auth): a refused IdP-initiated SAML sign-in lands on the platform error page with its error
With no relay state, @better-auth/sso lands every IdP-initiated answer on its fallback, the bare app origin, and the console mount redirects `/` without the query, so the sign-in page received no `error`. The SAML landing scope now answers such a response with the platform error page (`onAPIError.errorURL`) and re-bases only a refusal on that bare fallback onto it. A success, and any IdP-initiated callback an operator configured, are left as the vendor answered them; the refusal stays a refusal. Claude-Session: https://claude.ai/code/session_01WGufzfp1uE2GE28SdQSaqN Co-authored-by: Claude <noreply@anthropic.com>
1 parent 45f0f81 commit a5f5e9d

3 files changed

Lines changed: 193 additions & 37 deletions

File tree

‎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: 88 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,15 @@ 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.
437453
*/
438-
export async function readSamlAcsLanding(
454+
async function readRelayStateRow(
439455
context: SamlLandingContext,
440-
providerId: string,
441456
request: Request,
442-
): Promise<SamlAcsLanding | undefined> {
457+
): Promise<{ callbackURL: string; errorURL?: unknown } | undefined> {
443458
const relayState = await relayStateOf(request);
444459
if (!relayState) return undefined;
445460
const row = await context.internalAdapter.findVerificationValue(`auth-state:${relayState}`);
@@ -450,14 +465,37 @@ export async function readSamlAcsLanding(
450465
} catch {
451466
return undefined;
452467
}
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`;
468+
return typeof state?.callbackURL === 'string' ? { callbackURL: state.callbackURL, errorURL: state.errorURL } : undefined;
469+
}
470+
471+
/**
472+
* Where this ACS request's refusals land, read BEFORE the vendor runs, with the
473+
* same default and the same safety rule the vendor applies to an error URL:
474+
*
475+
* - with a relay-state row, the sign-in's own error URL (its
476+
* `errorCallbackURL`, else the platform error page);
477+
* - with none (an IdP-initiated response), the platform error page, for a
478+
* refusal the vendor puts on its bare app-origin fallback.
479+
*
480+
* `undefined` when that error URL is not a safe target: the vendor then has no
481+
* error URL either, and its answer stands.
482+
*/
483+
export async function readSamlAcsLanding(
484+
context: SamlLandingContext,
485+
providerId: string,
486+
request: Request,
487+
): Promise<SamlAcsLanding | undefined> {
488+
const platformErrorURL = context.options.onAPIError?.errorURL || `${context.baseURL}/error`;
458489
const appOrigin = new URL(context.baseURL).origin;
459490
const acsPathname = new URL(`${context.baseURL}${SAML_ACS_PATH_PREFIX}${providerId}`).pathname;
460-
const error = safeSamlTarget(errorURL, acsPathname, appOrigin, context.isTrustedOrigin);
491+
const safe = (url: string) => safeSamlTarget(url, acsPathname, appOrigin, context.isTrustedOrigin);
492+
const state = await readRelayStateRow(context, request);
493+
if (!state) {
494+
const error = safe(platformErrorURL);
495+
return error ? { fallback: appOrigin, error } : undefined;
496+
}
497+
const errorURL = typeof state.errorURL === 'string' && state.errorURL ? state.errorURL : platformErrorURL;
498+
const error = safe(errorURL);
461499
return error ? { success: state.callbackURL, error } : undefined;
462500
}
463501

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

518+
/**
519+
* Whether `location` is a refusal on the vendor's bare app-origin fallback:
520+
* the site root, with no query but the `error` and `error_description` the
521+
* vendor sets on it. The fallback itself carries no query, so a success there
522+
* never matches.
523+
*/
524+
function isOnBareFallback(location: string, fallback: string): boolean {
525+
let url: URL;
526+
try {
527+
url = new URL(location, fallback);
528+
} catch {
529+
return false;
530+
}
531+
return (
532+
url.origin === new URL(fallback).origin &&
533+
url.pathname === '/' &&
534+
url.hash === '' &&
535+
[...url.searchParams.keys()].every((key) => key === 'error' || key === 'error_description')
536+
);
537+
}
538+
480539
/**
481540
* 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.
541+
* is not the success URL (for an IdP-initiated response: that sits on the bare
542+
* fallback) is re-based onto the error URL. Every other answer is returned
543+
* untouched.
484544
*/
485545
export function landSamlRefusal(response: Response, landing: SamlAcsLanding): Response {
486546
const location = response.headers.get('location');
487-
if (!location || location === landing.success) return response;
547+
if (!location) return response;
548+
if ('success' in landing ? location === landing.success : !isOnBareFallback(location, landing.fallback)) return response;
488549
if (!new URL(location, 'http://better-auth.local').searchParams.has('error')) return response;
489550
const landed = rebaseSamlRefusal(location, landing.error);
490551
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)