Skip to content

Commit 97b9ddd

Browse files
committed
wip: decision matrix, option unit pins, audit-trail pin
Claude-Session: https://claude.ai/code/session_01FEkQ5nXM5CEyYnbaY58Spo Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 853626c commit 97b9ddd

6 files changed

Lines changed: 351 additions & 15 deletions

File tree

‎packages/plugins/plugin-audit/src/audit-internal-field-omission.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,3 +449,40 @@ describe('the ledger CRUD mirror omits encrypted key-material columns', () => {
449449
expect(created.value_enc).toBe('control-b');
450450
});
451451
});
452+
453+
/**
454+
* The SSO provider's sign-in toggles (`allow_idp_initiated`, `allow_jit`) widen
455+
* who can sign in, so a change to either must leave its audit trail: the
456+
* ledger row with both sides, and an activity line naming the field (both are
457+
* `trackHistory`). Same in-memory boot as above, on the REAL `SysSsoProvider`
458+
* definition; the write is shaped as plugin-auth's adapter makes it (better-auth
459+
* stores a boolean as `1` / `0`).
460+
*/
461+
describe('a change to an SSO provider sign-in toggle is recorded in the ledger and the activity feed', () => {
462+
const def = SysSsoProvider as unknown as ObjectDef;
463+
464+
it('declares both toggles as tracked, default off', () => {
465+
for (const field of ['allow_idp_initiated', 'allow_jit']) {
466+
const fd = def.fields[field] as { type?: string; trackHistory?: unknown; defaultValue?: unknown };
467+
expect(fd, field).toMatchObject({ type: 'boolean', trackHistory: true, defaultValue: false });
468+
}
469+
});
470+
471+
it.each(['allow_idp_initiated', 'allow_jit'])('turning %s on and off writes one update row per change, each with both sides', async (field) => {
472+
const { engine, storeFor } = await boot(def);
473+
const created = await engine.insert(def.name, { ...seedRow(def, [], 'issuer', 'create'), [field]: 0 }, SYS);
474+
const id = String(created.id);
475+
await engine.update(def.name, { [field]: 1 }, { where: { id }, ...SYS } as any);
476+
await engine.update(def.name, { [field]: 0 }, { where: { id }, ...SYS } as any);
477+
478+
const updates = ledgerRows(storeFor, def.name).filter((r) => r.action === 'update');
479+
expect(updates).toHaveLength(2);
480+
expect([parse(updates[0].old_value)[field], parse(updates[0].new_value)[field]].map(Boolean)).toEqual([false, true]);
481+
expect([parse(updates[1].old_value)[field], parse(updates[1].new_value)[field]].map(Boolean)).toEqual([true, false]);
482+
for (const row of updates) expect(row.record_id).toBe(id);
483+
484+
const activity = activityRows(storeFor, def.name).filter((r) => r.type === 'updated');
485+
expect(activity).toHaveLength(2);
486+
for (const row of activity) expect(String(row.summary)).toContain(String((def.fields[field] as { label?: string }).label));
487+
});
488+
});

‎packages/plugins/plugin-auth/src/audience-posture.test.ts‎

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,52 @@ describe('admission decision matrix (#11739): posture × creation class', () =>
363363
}
364364
});
365365

366+
// Ruling record 6718355623: an SSO provider (`ssoProvider` present) under
367+
// invite_only admits an unknown user only by its allowJit toggle, an
368+
// invitation or the bootstrap carve-out.
369+
it('invite_only refuses an SSO-provider creation with allowJit off: SELF_REGISTRATION_CLOSED', () => {
370+
const verdict = decideAudienceAdmission({ ...base, audience: audience(), creationClass: 'provider', ssoProvider: { allowJit: false } });
371+
expect(verdict.admit).toBe(false);
372+
if (!verdict.admit) expect(verdict.code).toBe(SELF_REGISTRATION_CLOSED);
373+
});
374+
375+
it('invite_only admits an SSO-provider creation with allowJit on, an invitation, or at bootstrap, never with the grant', () => {
376+
const aud = audience();
377+
for (const input of [
378+
{ ssoProvider: { allowJit: true } },
379+
{ ssoProvider: { allowJit: false }, hasPendingInvitation: true },
380+
{ ssoProvider: { allowJit: false }, isBootstrap: true },
381+
]) {
382+
expect(decideAudienceAdmission({ ...base, audience: aud, creationClass: 'provider', ...input })).toEqual({
383+
admit: true,
384+
grantPermissionSet: false,
385+
});
386+
}
387+
});
388+
389+
it('CONTROL: email_domain and open admit an SSO-provider creation with allowJit off, as before', () => {
390+
for (const posture of ['email_domain', 'open'] as const) {
391+
const verdict = decideAudienceAdmission({
392+
...base,
393+
email: 'someone@elsewhere.com',
394+
audience: audience({ posture, allowedEmailDomains: posture === 'email_domain' ? ['acme.com'] : [], selfRegistrationPermissionSet: 'portal_user' }),
395+
creationClass: 'provider',
396+
ssoProvider: { allowJit: false },
397+
});
398+
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
399+
}
400+
});
401+
402+
it('CONTROL: an off-vocabulary posture admits an SSO-provider creation as before (it is judged only under a valid invite_only)', () => {
403+
const verdict = decideAudienceAdmission({
404+
...base,
405+
audience: audience({ invalid: { raw: "'inviteOnly'" } }),
406+
creationClass: 'provider',
407+
ssoProvider: { allowJit: false },
408+
});
409+
expect(verdict).toEqual({ admit: true, grantPermissionSet: false });
410+
});
411+
366412
it('the three refusal codes are DISTINCT and the two new ones are registered in the ADR-0112 ledger', () => {
367413
expect(SELF_REGISTRATION_CLOSED).not.toBe(EMAIL_DOMAIN_NOT_ALLOWED);
368414
expect(SELF_REGISTRATION_CLOSED).not.toBe(AUDIENCE_CONFIG_ERROR);
@@ -968,14 +1014,24 @@ describe('end of the chain: better-auth pipeline over the memory engine (#11739)
9681014
nonBootstrapCtx,
9691015
);
9701016
expect(social?.error).toBe(SELF_REGISTRATION_CLOSED);
971-
// SSO JIT and SCIM ride their own methods — admitted under invite_only.
972-
for (const method of ['sso-oidc', 'sso-saml', 'scim', 'admin']) {
1017+
// SCIM and admin creation ride their own methods — admitted under invite_only.
1018+
for (const method of ['scim', 'admin']) {
9731019
const verdict = await (manager as any).validateAudienceAdmission(
9741020
{ user: { email: 'x@corp.com' }, source: { action: 'create-user', method } },
9751021
nonBootstrapCtx,
9761022
);
9771023
expect(verdict).toBeUndefined();
9781024
}
1025+
// An @better-auth/sso provider is admitted under invite_only only by its own
1026+
// allowJit toggle (ruling record 6718355623): no provider row here, so it
1027+
// reads OFF and the posture refuses.
1028+
for (const method of ['sso-oidc', 'sso-saml']) {
1029+
const verdict = await (manager as any).validateAudienceAdmission(
1030+
{ user: { email: 'x@corp.com' }, source: { action: 'create-user', method, sso: { providerId: 'acme' } } },
1031+
nonBootstrapCtx,
1032+
);
1033+
expect(verdict?.error).toBe(SELF_REGISTRATION_CLOSED);
1034+
}
9791035
// link-account / sign-in actions are not audience admission.
9801036
const linking = await (manager as any).validateAudienceAdmission(
9811037
{ user: { email: 'x@corp.com' }, source: { action: 'link-account', method: 'oauth', oauth: { providerId: 'google' } } },

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ import {
6464
import { GRANT_SET_NAME_FIELD } from './grant-set-name.js';
6565
import { withSystemReadContext } from './objectql-adapter.js';
6666
import { reconcileMembership, type ReconcileOutcome } from './reconcile-membership.js';
67-
import { readSsoProviderSignInOptions, ssoProviderIdOfSource } from './sso-sign-in-options.js';
67+
import { isSsoProviderSource, readSsoProviderSignInOptions, ssoProviderIdOfSource } from './sso-sign-in-options.js';
6868
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
6969

7070
/**
@@ -152,14 +152,13 @@ export async function validateAudienceAdmission(
152152
// An SSO provider's own JIT toggle, read only where it can decide: a
153153
// provider-class creation through `@better-auth/sso` under `invite_only`
154154
// (`sso-sign-in-options.ts`; unreadable ⇒ off, so the posture applies).
155-
const ssoProviderId = creationClass === 'provider' ? ssoProviderIdOfSource(data?.source) : undefined;
156155
const ssoProvider =
157-
ssoProviderId !== undefined && audience.posture === 'invite_only' && !audience.invalid
156+
creationClass === 'provider' && isSsoProviderSource(data?.source) && audience.posture === 'invite_only' && !audience.invalid
158157
? {
159158
allowJit: (
160159
await readSsoProviderSignInOptions(
161160
this.config.dataEngine ? (withSystemReadContext(this.config.dataEngine) as never) : undefined,
162-
ssoProviderId,
161+
ssoProviderIdOfSource(data?.source),
163162
)
164163
).allowJit,
165164
}

‎packages/plugins/plugin-auth/src/sso-register-platform-admin-gate.test.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ import { inviteForAudienceGate } from './audience-gate-test-support';
8989
import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit';
9090
import { ADMIN_FULL_ACCESS_CAPABILITIES } from '@objectstack/spec';
9191
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
92+
import { withSystemReadContext } from './objectql-adapter.js';
93+
import { readSsoProviderSignInOptions } from './sso-sign-in-options.js';
9294

9395
const BASE = 'http://localhost:3000';
9496
const AUTH = `${BASE}/api/v1/auth`;
@@ -458,3 +460,96 @@ describe('[#10009] the two doors onto SSO registration now answer the same org o
458460
expect(directBody?.code ?? directBody?.error?.code).toBe('SSO_REGISTER_FORBIDDEN');
459461
});
460462
});
463+
464+
// ---------------------------------------------------------------------------
465+
// The provider's sign-in toggles are written through the vendor's own
466+
// /sso/update-provider (`sso-sign-in-options.ts`), on a real SQL store.
467+
// ---------------------------------------------------------------------------
468+
469+
describe('the per-provider sign-in toggles are written by the provider writer, default off', () => {
470+
async function providerOwnedBy(engine: ObjectQL, manager: AuthManager, userId: string): Promise<void> {
471+
const auth: any = await manager.getAuthInstance();
472+
const ctx = await auth.$context;
473+
await ctx.adapter.create({
474+
model: 'ssoProvider',
475+
data: {
476+
providerId: 'acme-okta',
477+
issuer: 'https://idp.acme.example',
478+
domain: 'acme.example',
479+
userId,
480+
oidcConfig: JSON.stringify({ issuer: 'https://idp.acme.example', clientId: 'cid', pkce: true }),
481+
},
482+
});
483+
}
484+
485+
const postUpdate = (send: (r: Request) => Promise<Response>, cookie: string, body: Record<string, unknown>) =>
486+
send(
487+
new Request(`${AUTH}/sso/update-provider`, {
488+
method: 'POST',
489+
headers: { 'content-type': 'application/json', origin: BASE, cookie },
490+
body: JSON.stringify({ providerId: 'acme-okta', ...body }),
491+
}),
492+
);
493+
494+
it('a new provider stores both OFF; update-provider turns each on and off; the store reads what was written', async () => {
495+
const engine = await bootEngine();
496+
const manager = makeManager(engine);
497+
const send = (r: Request) => manager.handleRequest(r);
498+
const email = 'platformadmin@example.com';
499+
const cookie = await signUp(send, email, engine);
500+
const userId = await userIdOf(engine, email);
501+
await grantPlatformAdmin(engine, userId);
502+
await providerOwnedBy(engine, manager, userId);
503+
504+
const reader = withSystemReadContext(engine as never) as never;
505+
expect(await readSsoProviderSignInOptions(reader, 'acme-okta')).toEqual({ allowIdpInitiated: false, allowJit: false });
506+
507+
const on = await postUpdate(send, cookie, { allowIdpInitiated: true, allowJit: true });
508+
expect(on.status, await on.clone().text()).toBe(200);
509+
expect(await readSsoProviderSignInOptions(reader, 'acme-okta')).toEqual({ allowIdpInitiated: true, allowJit: true });
510+
511+
const off = await postUpdate(send, cookie, { allowJit: false });
512+
expect(off.status, await off.clone().text()).toBe(200);
513+
expect(await readSsoProviderSignInOptions(reader, 'acme-okta')).toEqual({ allowIdpInitiated: true, allowJit: false });
514+
});
515+
516+
it('a value that is not a boolean is refused 400, and nothing is written', async () => {
517+
const engine = await bootEngine();
518+
const manager = makeManager(engine);
519+
const send = (r: Request) => manager.handleRequest(r);
520+
const email = 'platformadmin@example.com';
521+
const cookie = await signUp(send, email, engine);
522+
const userId = await userIdOf(engine, email);
523+
await grantPlatformAdmin(engine, userId);
524+
await providerOwnedBy(engine, manager, userId);
525+
526+
const res = await postUpdate(send, cookie, { allowJit: 'yes' });
527+
const body = (await res.clone().json()) as Record<string, any>;
528+
expect(res.status, await res.clone().text()).toBe(400);
529+
expect(body?.code).toBe('VALIDATION_ERROR');
530+
expect(await readSsoProviderSignInOptions(withSystemReadContext(engine as never) as never, 'acme-okta')).toEqual({
531+
allowIdpInitiated: false,
532+
allowJit: false,
533+
});
534+
});
535+
536+
it('a member who does not write the provider cannot flip it (the vendor provider-access check)', async () => {
537+
const engine = await bootEngine();
538+
const manager = makeManager(engine);
539+
const send = (r: Request) => manager.handleRequest(r);
540+
const adminCookie = await signUp(send, 'platformadmin@example.com', engine);
541+
const adminId = await userIdOf(engine, 'platformadmin@example.com');
542+
await grantPlatformAdmin(engine, adminId);
543+
await providerOwnedBy(engine, manager, adminId);
544+
expect(adminCookie).toBeTruthy();
545+
546+
const memberCookie = await signUp(send, 'member@example.com', engine);
547+
const res = await postUpdate(send, memberCookie, { allowJit: true });
548+
// The vendor's own refusal (403, no `code` member on @better-auth/sso 1.7.12).
549+
expect(res.status, await res.clone().text()).toBe(403);
550+
expect(await readSsoProviderSignInOptions(withSystemReadContext(engine as never) as never, 'acme-okta')).toEqual({
551+
allowIdpInitiated: false,
552+
allowJit: false,
553+
});
554+
});
555+
});

0 commit comments

Comments
 (0)