Skip to content

Commit dfcca46

Browse files
committed
wip: SAML refusal causes, mapping tests
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzhMu5u3iHHSSD7mx8c
1 parent a2f67e4 commit dfcca46

6 files changed

Lines changed: 959 additions & 7 deletions

File tree

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ import { resolvePasswordHasher } from './auth-manager-password-hasher.js';
264264
import { createAuthInstance, type AuthInstanceHost } from './auth-manager-auth-instance.js';
265265
import { readSamlAcsLanding, runSsoCallbackScope, type SamlLandingContext, type SsoCallbackRequest } from './sso-oidc-refusal-cause.js';
266266
import { readSsoProviderSignInOptions, runWithSamlIdpInitiated } from './sso-sign-in-options.js';
267+
import { readStoredSamlConfig, runSsoSamlRefusalCauseScope } from './sso-saml-refusal-cause.js';
267268
// [#25224 cut 16] The body of `buildPluginList`; the method of the same name
268269
// below hands it the members it reads (`PluginListHost`). The organization
269270
// plugin's factory (cut 15) is now imported there, by the arrow that moved
@@ -4046,7 +4047,16 @@ export class AuthManager {
40464047
engine ? (withSystemReadContext(engine) as never) : undefined,
40474048
callback.providerId,
40484049
);
4049-
return runWithSamlIdpInitiated(options.allowIdpInitiated, run);
4050+
// [#32086] The vendor's opaque `Invalid SAML response` names its
4051+
// cause, read against the provider's stored configuration
4052+
// (`sso-saml-refusal-cause.ts`).
4053+
const readSamlConfig = async () => {
4054+
const auth: any = await this.getOrCreateAuth();
4055+
return readStoredSamlConfig(await auth.$context, callback.providerId);
4056+
};
4057+
return runWithSamlIdpInitiated(options.allowIdpInitiated, () =>
4058+
runSsoSamlRefusalCauseScope(callback, this.config.logger, readSamlConfig, run),
4059+
);
40504060
}
40514061
: run;
40524062
return runSsoCallbackScope(

‎packages/plugins/plugin-auth/src/register-sso-provider.test.ts‎

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,15 @@ import { betterAuth } from 'better-auth';
55
import { memoryAdapter } from 'better-auth/adapters/memory';
66
import { sso } from '@better-auth/sso';
77
import {
8+
attributeMappingOf,
89
groupsClaimOfMapping,
10+
mappingWithAttributes,
911
mappingWithGroupsClaim,
1012
runRegisterSamlProviderFromForm,
1113
runRegisterSsoProviderFromForm,
14+
runSetSsoAttributeMapping,
1215
runSetSsoGroupsClaim,
16+
runShowSsoAttributeMapping,
1317
runShowSsoGroupsClaim,
1418
type StoredSsoProviderConfigs,
1519
} from './register-sso-provider';
@@ -323,6 +327,46 @@ describe('Register SAML Provider through the REAL route — the INSTALLED @bette
323327
expect(JSON.parse(db.ssoProvider.find((p) => p.providerId === 'acme-saml').samlConfig).mapping).toBeUndefined();
324328
});
325329

330+
it('[#32086] the attribute names on the form are stored where the register door stores them: mapping.email / firstName / lastName / name', async () => {
331+
const ENTRA = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims';
332+
const res = await post({
333+
...COMPLETE_FORM,
334+
providerId: 'acme-saml-mapped',
335+
mapEmail: ` ${ENTRA}/emailaddress `,
336+
mapFirstName: `${ENTRA}/givenname`,
337+
mapLastName: `${ENTRA}/surname`,
338+
mapName: 'http://schemas.microsoft.com/identity/claims/displayname',
339+
mapGroups: 'memberOf',
340+
});
341+
expect(res.status, await res.clone().text()).toBe(200);
342+
const door = await app.request(`${ORIGIN}${BASE}/sso/register`, {
343+
method: 'POST',
344+
headers: { 'content-type': 'application/json', origin: ORIGIN, cookie },
345+
body: JSON.stringify({
346+
providerId: 'acme-saml-mapped-door',
347+
issuer: COMPLETE_FORM.issuer,
348+
domain: COMPLETE_FORM.domain,
349+
samlConfig: {
350+
entryPoint: COMPLETE_FORM.entryPoint,
351+
cert: COMPLETE_FORM.cert,
352+
idpMetadata: { entityID: COMPLETE_FORM.issuer },
353+
spMetadata: { entityID: 'door-sp' },
354+
mapping: {
355+
email: `${ENTRA}/emailaddress`,
356+
firstName: `${ENTRA}/givenname`,
357+
lastName: `${ENTRA}/surname`,
358+
name: 'http://schemas.microsoft.com/identity/claims/displayname',
359+
extraFields: { groups: 'memberOf' },
360+
},
361+
},
362+
}),
363+
});
364+
expect(door.status, await door.clone().text()).toBe(200);
365+
const mappingOf = (providerId: string) => JSON.parse(db.ssoProvider.find((p) => p.providerId === providerId).samlConfig).mapping;
366+
expect(mappingOf('acme-saml-mapped')).toEqual(mappingOf('acme-saml-mapped-door'));
367+
expect(mappingOf('acme-saml-mapped').email).toBe(`${ENTRA}/emailaddress`);
368+
});
369+
326370
// A SAML EntityID is a URI, and many IdPs publish a URN. The bridge sends the
327371
// form's Entity ID both as the top-level `issuer` and as
328372
// `idpMetadata.entityID`, and the vendor's register body types `issuer` as
@@ -533,3 +577,166 @@ describe('the groups-claim bridges: show it, set it, clear it, and answer nothin
533577
}
534578
});
535579
});
580+
581+
describe('[#32086] the attribute names on the SAML register form: mapping.email / firstName / lastName / name', () => {
582+
const sentFor = async (extra: Record<string, unknown>) => {
583+
let dispatched: any = null;
584+
const handle = vi.fn(async (req: Request) => {
585+
if (req.url.endsWith('/get-session')) return new Response('null', { status: 200 });
586+
dispatched = await req.clone().json();
587+
return new Response(JSON.stringify({ providerId: 'p' }), { status: 200 });
588+
});
589+
const res = await runRegisterSamlProviderFromForm(handle, makeReq({ providerId: 'p', issuer: 'https://idp.acme.com/entity', domain: 'acme.com', entryPoint: 'https://idp.acme.com/sso', cert: 'c', ...extra }));
590+
expect(res.status).toBe(200);
591+
return dispatched.samlConfig;
592+
};
593+
594+
it('each named attribute is sent trimmed, beside the groups attribute', async () => {
595+
const sent = await sentFor({ mapEmail: ' mail ', mapFirstName: 'first', mapLastName: 'last', mapName: 'name', mapGroups: 'memberOf' });
596+
expect(sent.mapping).toEqual({ email: 'mail', firstName: 'first', lastName: 'last', name: 'name', extraFields: { groups: 'memberOf' } });
597+
});
598+
599+
it('only the attributes named are sent; a blank one is left to the vendor default', async () => {
600+
expect((await sentFor({ mapName: 'name', mapEmail: ' ', mapFirstName: '' })).mapping).toEqual({ name: 'name' });
601+
});
602+
603+
it('CONTROL: a form naming none of them still sends no mapping', async () => {
604+
expect('mapping' in (await sentFor({ mapEmail: '', mapFirstName: ' ', mapLastName: undefined, mapName: '' }))).toBe(false);
605+
});
606+
});
607+
608+
describe('[#32086] the attribute-mapping bridges: show it, change some members, keep the rest, answer nothing else', () => {
609+
const CLIENT_SECRET = 'SECRET-VALUE-NEVER-ANSWERED';
610+
const CERT = 'CERT-BODY-NEVER-ANSWERED';
611+
const OIDC_STORED = {
612+
issuer: 'https://idp.acme.com',
613+
clientId: 'cid',
614+
clientSecret: CLIENT_SECRET,
615+
mapping: { id: 'sub', email: 'upn', name: 'display_name', image: 'picture', emailVerified: 'email_verified', extraFields: { groups: 'groups', department: 'dept' } },
616+
};
617+
const SAML_STORED = {
618+
entryPoint: 'https://idp.acme.com/sso',
619+
cert: CERT,
620+
privateKey: CLIENT_SECRET,
621+
mapping: { email: 'mail', firstName: 'givenName', emailVerified: 'verified', extraFields: { groups: 'memberOf' } },
622+
};
623+
624+
const storeOf = (configs: Record<string, StoredSsoProviderConfigs>) => {
625+
const read = vi.fn(async (providerId: string) => configs[providerId] ?? null);
626+
const sent: any[] = [];
627+
const handle = vi.fn(async (req: Request) => {
628+
const body = await req.clone().json();
629+
sent.push({ url: req.url, body });
630+
const row = configs[body.providerId];
631+
const key = body.samlConfig ? 'samlConfig' : 'oidcConfig';
632+
row[key] = JSON.stringify({ ...JSON.parse(String(row[key])), mapping: body[key].mapping });
633+
return new Response(JSON.stringify({ ok: true }), { status: 200 });
634+
});
635+
return { read, handle, sent };
636+
};
637+
const stores = () =>
638+
storeOf({
639+
okta: { oidcConfig: JSON.stringify(OIDC_STORED), samlConfig: null },
640+
saml: { oidcConfig: null, samlConfig: JSON.stringify(SAML_STORED) },
641+
bare: { oidcConfig: null, samlConfig: JSON.stringify({ entryPoint: 'https://idp.acme.com/sso', cert: CERT }) },
642+
});
643+
const call = (path: string, body: Record<string, unknown>) =>
644+
new Request(`http://localhost:3000/api/v1/auth/admin/sso/${path}`, {
645+
method: 'POST',
646+
headers: { 'content-type': 'application/json', origin: 'http://localhost:3000' },
647+
body: JSON.stringify(body),
648+
});
649+
const show = (read: any, providerId: string) => runShowSsoAttributeMapping(call('get-attribute-mapping', { providerId }), read);
650+
const set = (handle: any, read: any, body: Record<string, unknown>) => runSetSsoAttributeMapping(handle, call('set-attribute-mapping', body), read);
651+
652+
it('mappingWithAttributes changes only the members named: a value sets, a blank removes, the rest is kept', () => {
653+
const before = { email: 'mail', name: 'cn', extraFields: { groups: 'g' } };
654+
expect(mappingWithAttributes(before, { name: ' displayName ', firstName: 'given' })).toEqual({ email: 'mail', name: 'displayName', firstName: 'given', extraFields: { groups: 'g' } });
655+
expect(mappingWithAttributes(before, { email: ' ' })).toEqual({ name: 'cn', extraFields: { groups: 'g' } });
656+
expect(before).toEqual({ email: 'mail', name: 'cn', extraFields: { groups: 'g' } });
657+
expect(mappingWithAttributes(undefined, { email: '' })).toEqual({});
658+
expect(attributeMappingOf({ email: 'upn', firstName: 'f' }, 'oidc')).toEqual({ email: 'upn', firstName: null, lastName: null, name: null });
659+
});
660+
661+
it('show answers each protocol\'s members, null where the default applies', async () => {
662+
const { read } = stores();
663+
expect((await show(read, 'okta')).body).toEqual({ success: true, data: { providerId: 'okta', protocol: 'oidc', email: 'upn', firstName: null, lastName: null, name: 'display_name' } });
664+
expect((await show(read, 'saml')).body).toEqual({ success: true, data: { providerId: 'saml', protocol: 'saml', email: 'mail', firstName: 'givenName', lastName: null, name: null } });
665+
expect((await show(read, 'bare')).body).toEqual({ success: true, data: { providerId: 'bare', protocol: 'saml', email: null, firstName: null, lastName: null, name: null } });
666+
});
667+
668+
it('set sends update-provider the stored mapping with only the given members changed, and answers it read back', async () => {
669+
const { read, handle, sent } = stores();
670+
const saml = await set(handle, read, { providerId: 'saml', name: 'name', lastName: ' sn ' });
671+
expect(saml.status).toBe(200);
672+
expect(saml.body).toEqual({ success: true, data: { providerId: 'saml', protocol: 'saml', email: 'mail', firstName: 'givenName', lastName: 'sn', name: 'name' } });
673+
expect(sent[0].url).toBe('http://localhost:3000/api/v1/auth/sso/update-provider');
674+
expect(sent[0].body).toEqual({ providerId: 'saml', samlConfig: { mapping: { ...SAML_STORED.mapping, lastName: 'sn', name: 'name' } } });
675+
676+
const oidc = await set(handle, read, { providerId: 'okta', email: 'email' });
677+
expect(oidc.body.data).toEqual({ providerId: 'okta', protocol: 'oidc', email: 'email', firstName: null, lastName: null, name: 'display_name' });
678+
expect(sent[1].body).toEqual({ providerId: 'okta', oidcConfig: { mapping: { ...OIDC_STORED.mapping, email: 'email' } } });
679+
});
680+
681+
it('a blank member is removed, so the default applies again; an absent or null one is kept', async () => {
682+
const { read, handle, sent } = stores();
683+
const res = await set(handle, read, { providerId: 'saml', email: ' ', firstName: null });
684+
expect(res.body.data).toEqual({ providerId: 'saml', protocol: 'saml', email: null, firstName: 'givenName', lastName: null, name: null });
685+
expect(sent[0].body.samlConfig.mapping).toEqual({ firstName: 'givenName', emailVerified: 'verified', extraFields: { groups: 'memberOf' } });
686+
});
687+
688+
it('a body naming no member is 400 INVALID_REQUEST and nothing is written', async () => {
689+
const { read, handle } = stores();
690+
for (const body of [{ providerId: 'saml' }, { providerId: 'saml', email: null, name: undefined }]) {
691+
const res = await set(handle, read, body);
692+
expect(res.status).toBe(400);
693+
expect(res.body.error?.code).toBe('INVALID_REQUEST');
694+
expect(res.body.error?.message).toContain('Nothing to change');
695+
}
696+
expect(handle).not.toHaveBeenCalled();
697+
});
698+
699+
it('first or last name on an OIDC provider is 400 INVALID_REQUEST naming the one claim it reads, and nothing is written', async () => {
700+
const { read, handle } = stores();
701+
const res = await set(handle, read, { providerId: 'okta', name: 'name', firstName: 'given_name' });
702+
expect(res.status).toBe(400);
703+
expect(res.body.error?.code).toBe('INVALID_REQUEST');
704+
expect(res.body.error?.message).toContain('map "name", not firstName');
705+
expect(handle).not.toHaveBeenCalled();
706+
});
707+
708+
it('an unknown provider is 404 RESOURCE_NOT_FOUND on both; a non-text member and a missing providerId are 400; nothing is written', async () => {
709+
const { read, handle } = stores();
710+
for (const res of [await show(read, 'nobody'), await set(handle, read, { providerId: 'nobody', name: 'n' })]) {
711+
expect(res.status).toBe(404);
712+
expect(res.body.error?.code).toBe('RESOURCE_NOT_FOUND');
713+
}
714+
for (const body of [{ providerId: 'saml', name: ['n'] }, { providerId: 'saml', email: 7 }, { name: 'n' }]) {
715+
const res = await set(handle, read, body);
716+
expect(res.status).toBe(400);
717+
expect(res.body.error?.code).toBe('INVALID_REQUEST');
718+
}
719+
expect(handle).not.toHaveBeenCalled();
720+
});
721+
722+
it('no answer carries another member of the stored configuration: not on show, not on set, not on a vendor refusal', async () => {
723+
const { read, handle } = stores();
724+
const answers: unknown[] = [];
725+
for (const providerId of ['okta', 'saml']) {
726+
answers.push((await show(read, providerId)).body);
727+
answers.push((await set(handle, read, { providerId, name: 'n' })).body);
728+
}
729+
const refusing = vi.fn(async () => new Response(JSON.stringify({ message: `bad config: ${CLIENT_SECRET} ${CERT}` }), { status: 400 }));
730+
const refused = await set(refusing, read, { providerId: 'okta', name: 'n2' });
731+
expect(refused.status).toBe(400);
732+
expect(refused.body.error?.code).toBe('VALIDATION_ERROR');
733+
answers.push(refused.body);
734+
735+
for (const answer of answers) {
736+
const text = JSON.stringify(answer);
737+
for (const leaked of [CLIENT_SECRET, CERT, 'cid', 'https://idp.acme.com', 'dept', 'memberOf', 'picture', 'verified']) expect(text).not.toContain(leaked);
738+
const data = (answer as { data?: Record<string, unknown> }).data;
739+
if (data) expect(Object.keys(data).sort()).toEqual(['email', 'firstName', 'lastName', 'name', 'protocol', 'providerId']);
740+
}
741+
});
742+
});

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,9 @@
4545
* nothing that depends on whether an account exists. The refusal happens
4646
* before any user lookup, so the answer is the same for every account.
4747
* - SAML causes: the vendor discards the SAML cause inside the package (a
48-
* bare `catch` around `parseLoginResponse`), so it is not readable here; that
49-
* half waits on the vendor. Where a SAML refusal LANDS is this module's,
48+
* bare `catch` around `parseLoginResponse`), so it is not readable from the
49+
* vendor's lines; `sso-saml-refusal-cause.ts` diagnoses it from the posted
50+
* response instead (#32086). Where a SAML refusal LANDS is this module's,
5051
* below.
5152
*
5253
* The values are lowercase `error_description` tokens in the vendor's own

0 commit comments

Comments
 (0)