diff --git a/.changeset/34971-allowlist-invite-grant.md b/.changeset/34971-allowlist-invite-grant.md new file mode 100644 index 00000000000..891f600eb8f --- /dev/null +++ b/.changeset/34971-allowlist-invite-grant.md @@ -0,0 +1,24 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/spec': patch +--- + +fix(plugin-auth)!: an invited sign-up the audience posture's own rule admits receives the declared self-registration permission set, and is refused when that set cannot be resolved + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the audience posture's invitation sign-up or `selfRegistrationPermissionSet`; `content/docs/deployment/self-hosting.mdx` gains the rule in this change. + + + +**BREAKING** for a deployment under the `open` audience posture, or under `email_domain` for an address on `allowedEmailDomains`, whose declared `selfRegistrationPermissionSet` cannot be resolved (no such set, or the set is switched off) and that relies on an invited person still being able to sign up. + +- Under `open`, and under `email_domain` for an address on the allowlist, a self-serve sign-up is admitted by the posture's own rule, invitation or not. It now receives the declared `selfRegistrationPermissionSet` whether or not it also holds a pending invitation. Before, a pending invitation addressed to it was read ahead of the posture in `decideAudienceAdmission` (`audience-posture.ts`), and the sign-up was admitted with no self-registration grant, though the membership settle already treated it as admitted by the posture and bound it at creation. The verdict and the settle now read one classification, the module-private `isAdmittedByPostureRule`. +- When the declared set cannot be resolved, such an invited sign-up is now refused `403 AUTH_CONFIG_ERROR`, naming the set, as an uninvited one already was. No account is created. Before, the invitation admitted it without the set. +- The invitation still places the sign-up as it names: once the address is verified and the invitation accepted, the membership and role it names are written beside the grant. + +Unchanged: under `invite_only` an invitation admits with no self-registration grant; under `email_domain` an address off the allowlist that an invitation admitted gets the account and no grant, and is not bound while its address is unverified, whatever state the declared set is in; operator, bootstrap and SSO-provider creations; a social-provider creation whose address the provider did not verify is still refused under `email_domain`, and under `open` while email verification is in force; `admin_full_access` is still refused as the self-registration set. + +No authorable key, accepted value or default changes; `selfRegistrationPermissionSet` keeps its meaning, the set each self-registrant receives, and now reaches the invited sign-ups its posture admits. + +What to do: keep `selfRegistrationPermissionSet` naming a permission set that exists and is switched on. A person refused this way signs up again once an administrator has corrected the setting or switched the set on, or an administrator creates the account directly. An invitation can expire while the set is broken; send it again after the fix. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 1264c0a94d3..0005803eef5 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -783,13 +783,28 @@ the list admits that address's sign-up. Verification is forced on under this posture, and while the account's address is unverified it joins no organization: it joins by accepting the invitation once the address is verified, and the acceptance writes the membership the invitation names. Verifying the address binds nothing by itself. -An address on the list is admitted by its domain, invitation or not, and the -membership policy binds it at creation as before. Both admissions have one +An address on the list is admitted by its domain, invitation or not: the +membership policy binds it at creation as before, it receives the declared +`selfRegistrationPermissionSet` like an uninvited sign-up, and a pending +invitation still places it as the invitation names once it accepts. Both admissions have one exception: under this posture a sign-in through a social provider creates an account only when the provider reports the address verified, and is otherwise refused `403 SELF_REGISTRATION_CLOSED`, whatever the list or an invitation says ([Authentication](/docs/permissions/authentication#2-handle-callback)). Once the provider verifies the address, the next sign-in is admitted. +Under `open` every address is admitted by the posture, invitation or not, so an +invited sign-up likewise receives the declared set beside its invitation. + +**A sign-up the posture admits needs its declared set, invited or not.** When +`selfRegistrationPermissionSet` cannot be resolved (no such set, or the set is +switched off), every sign-up the posture's own rule admits is refused +`403 AUTH_CONFIG_ERROR`, and the message names the set: any address under +`open`, an address on the list under `email_domain`, with or without a pending +invitation. Nothing is created, and the deployment logs the same reason at +error level. Correct the setting, or switch the set on, and the next sign-up is +admitted. A pending invitation does not admit such a sign-up without the set. +The two admissions an invitation makes alone, under `invite_only` and for an +address off the list under `email_domain`, ask for no set and are unaffected. **Accepting, declining and listing an invitation need a verified email address, on every deployment.** The invitation's `id`, which its link carries, diff --git a/packages/plugins/plugin-auth/src/audience-posture.test.ts b/packages/plugins/plugin-auth/src/audience-posture.test.ts index 52692b2c82e..02246871408 100644 --- a/packages/plugins/plugin-auth/src/audience-posture.test.ts +++ b/packages/plugins/plugin-auth/src/audience-posture.test.ts @@ -24,6 +24,9 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { ERROR_CODE_LEDGER } from '@objectstack/spec/api'; import { MCP_AGENT_PERMISSION_SETS } from '@objectstack/spec/ai'; import { AuthManager } from './auth-manager'; +// The SSO discovery egress guard the source loads with a dynamic import, paid +// here, during collection (check-test-source-alias, "The source reach"). +import '@objectstack/core/egress'; import { bindTestSecurityCatalog, catalogFromTables } from './__tests__/security-catalog.testkit.js'; import { assertAudienceConfig, @@ -339,6 +342,31 @@ describe('admission decision matrix (#11739): posture × creation class', () => expect(verdict).toEqual({ admit: true, grantPermissionSet: false }); }); + // A sign-up the posture's own rule admits is admitted by that rule, + // invitation or not, and receives the declared set; one admitted by its + // invitation alone gets the account and no grant. + it.each([ + ['email_domain', 'on the allowlist', 'colleague@acme.com', true, { admit: true, grantPermissionSet: true }], + ['email_domain', 'on the allowlist', 'colleague@acme.com', false, { admit: true, grantPermissionSet: true }], + ['email_domain', 'off the allowlist', 'contractor@external.com', true, { admit: true, grantPermissionSet: false }], + ['open', 'any address', 'anyone@external.com', true, { admit: true, grantPermissionSet: true }], + ['open', 'any address', 'anyone@external.com', false, { admit: true, grantPermissionSet: true }], + ['invite_only', 'any address', 'anyone@external.com', true, { admit: true, grantPermissionSet: false }], + ] as const)('%s, an address %s (%s), invited %s: %o', (posture, _where, email, invited, expected) => { + const verdict = decideAudienceAdmission({ + ...base, + email, + hasPendingInvitation: invited, + audience: audience({ + posture, + allowedEmailDomains: posture === 'email_domain' ? ['acme.com'] : [], + selfRegistrationPermissionSet: posture === 'invite_only' ? undefined : 'portal_user', + }), + creationClass: 'self-serve', + }); + expect(verdict).toEqual(expected); + }); + it('open admits self-serve with the grant', () => { const verdict = decideAudienceAdmission({ ...base, @@ -921,6 +949,47 @@ describe('end of the chain: better-auth pipeline over the memory engine (#11739) expect((engine.tables.get('sys_user') ?? []).length).toBe(1); }); + // An invited sign-up the posture's own rule admits is a self-registrant: it + // asks for the declared set like an uninvited one, so a set that cannot be + // resolved refuses it too. The invitation does not admit it without the grant. + it.each([ + ['open', 'missing', { posture: 'open' }, 'invited@anywhere.com'], + ['open', 'switched off', { posture: 'open' }, 'invited@anywhere.com'], + ['email_domain (on the allowlist)', 'missing', { posture: 'email_domain', allowedEmailDomains: ['acme.com'] }, 'invited@acme.com'], + ['email_domain (on the allowlist)', 'switched off', { posture: 'email_domain', allowedEmailDomains: ['acme.com'] }, 'invited@acme.com'], + ] as const)('%s: an invited sign-up whose declared set is %s is refused AUTH_CONFIG_ERROR, like an uninvited one', async (_posture, state, posture, email) => { + const engine = createMemoryEngine(); + seedExistingUser(engine); + if (state === 'switched off') { + seedPermissionSet(engine, 'member_default'); + engine.tables.set('sys_metadata_activation', [ + { id: 'act_member', metadata_type: 'permission', name: 'member_default', package_id: 'pkg', active: false }, + ]); + } + seedPendingInvitation(engine, email); + const set = state === 'missing' ? 'ghost' : 'member_default'; + const manager = makeManager(engine, { audience: { ...posture, selfRegistrationPermissionSet: set } }); + const res = await signUp(manager, email); + expect(res.status).toBe(403); + const body = await res.json(); + expect(body.code).toBe(AUDIENCE_CONFIG_ERROR); + expect(String(body.message)).toContain(`'${set}'`); + expect((engine.tables.get('sys_user') ?? []).length).toBe(1); + }); + + it('CONTROL: email_domain, an invited sign-up OFF the allowlist is admitted by its invitation alone, asking for no set, so a missing set does not refuse it', async () => { + const engine = createMemoryEngine(); + seedExistingUser(engine); + seedPendingInvitation(engine, 'contractor@external.com'); + const manager = makeManager(engine, { + audience: { posture: 'email_domain', allowedEmailDomains: ['acme.com'], selfRegistrationPermissionSet: 'ghost' }, + }); + const res = await signUp(manager, 'contractor@external.com'); + expect(res.status, await res.clone().text()).toBeLessThan(300); + expect((engine.tables.get('sys_user') ?? []).length).toBe(2); + expect(engine.tables.get('sys_user_permission_set') ?? []).toEqual([]); + }); + it('[ADR-0131 D3] the set ROW\'s `active` switches nothing: a row flagged off still admits and grants', async () => { // The resolver reads no catalog row, so the row flag is not a deactivation. const engine = createMemoryEngine(); @@ -1165,6 +1234,8 @@ describe('a self-serve social creation under an address-based posture is admitte admit: true, grantPermissionSet: false, }); + // On the allowlist, the verified creation is admitted by its domain, invitation or not. + expect(decide({ hasPendingInvitation: true, emailVerified: true })).toEqual({ admit: true, grantPermissionSet: true }); }); it('open: refused while email verification is in force (undeclared or declared true), an invitation included', () => { diff --git a/packages/plugins/plugin-auth/src/audience-posture.ts b/packages/plugins/plugin-auth/src/audience-posture.ts index f2f2b8a423f..fc4dbd6fa05 100644 --- a/packages/plugins/plugin-auth/src/audience-posture.ts +++ b/packages/plugins/plugin-auth/src/audience-posture.ts @@ -61,9 +61,13 @@ * `email_domain` an explicit invitation also trumps the domain list — an * operator inviting an external contractor must not dead-end them), except a * social-provider creation whose address the provider did not verify under a - * posture whose admission rests on the address (below). Without - * this carve-out the posture would be "admin-create only" and the invitation - * surface would be dead for new users — the invite dead-end class. + * posture whose admission rests on the address (below), and except a creation + * the posture's own rule already admits ({@link isAdmittedByPostureRule}): that + * one is a self-registrant, invitation or not, so it asks for the declared + * self-registration set and is refused with the uninvited sign-up when the set + * cannot be resolved — the invitation does not admit it without the grant. + * Without this carve-out the posture would be "admin-create only" and the + * invitation surface would be dead for new users — the invite dead-end class. * * What "holding" means is {@link invitationProofFor}'s answer. Under * `invite_only` a self-serve sign-up is admitted only by the invitation it @@ -76,9 +80,14 @@ * * Admission by an invitation alone grants the account and nothing more * ({@link isAdmittedByInvitationAlone}): under `invite_only`, and under - * `email_domain` for an address off the list, the sign-up is not bound into - * the deployment's organization while its address is unverified, and joins by - * accepting the invitation. + * `email_domain` for an address off the list, the sign-up receives no + * self-registration permission set, is not bound into the deployment's + * organization while its address is unverified, and joins by accepting the + * invitation. A sign-up the posture's own rule admits — any address under + * `open`, an address on the list under `email_domain` — is admitted by that + * rule, invitation or not ({@link isAdmittedByPostureRule}): it receives the + * declared set and binds as an uninvited one does, and the invitation still + * places it as the invitation names once it accepts. * * ## A social provider's word on the address * @@ -120,7 +129,8 @@ * ("a valid posture said no") because sending the debugger to re-read a * setting that looks exactly as they left it is the recorded failure mode. A * declared permission set that cannot be resolved refuses admission the same - * way: admitting a self-registrant WITHOUT the declared grant would be the + * way, for every sign-up the posture's rule admits, invited or not: admitting + * a self-registrant WITHOUT the declared grant would be the * ADR-0078 "declared but inert" defect at runtime, and fail-open is the one * direction this gate must never take. */ @@ -603,7 +613,8 @@ export function invitationProofFor(input: { * unexpired and addressed to it ({@link invitationProofFor} `presented`). * - `email_domain`: the sign-up's address is off the allowlist, and a pending * invitation addressed to it admitted it. An address on the list is admitted - * by the domain rule, invitation or not, and binds as before. + * by the domain rule, invitation or not ({@link isAdmittedByPostureRule}), + * binds as before and receives the declared self-registration set. * - `open`, an off-vocabulary posture, and every creation that is not * self-serve: never. */ @@ -616,8 +627,26 @@ export function isAdmittedByInvitationAlone(input: { }): boolean { const { audience, creationClass, email, proof, hasPendingInvitation } = input; if (!hasPendingInvitation || audience.invalid || creationClass !== 'self-serve') return false; + // `open`, and `email_domain` on the allowlist: admitted by the posture's rule. + if (isAdmittedByPostureRule(audience, email)) return false; if (audience.posture === 'invite_only') return proof === 'presented'; - if (audience.posture === 'email_domain') return !emailDomainAllowed(email, audience.allowedEmailDomains); + return audience.posture === 'email_domain'; +} + +/** + * Whether a valid posture's own rule admits a self-serve creation by its + * address, with no invitation: `open` admits every address, `email_domain` an + * address on the allowlist ({@link emailDomainAllowed}), and `invite_only` + * none. The one classification both readers of an invitation share: a + * sign-up the rule admits is admitted by that rule, invitation or not, so the + * admission verdict grants it the declared self-registration set + * ({@link decideAudienceAdmission}) and the membership settle binds it at + * creation ({@link isAdmittedByInvitationAlone}). + */ +function isAdmittedByPostureRule(audience: ResolvedAudience, email: string | undefined): boolean { + if (audience.invalid) return false; + if (audience.posture === 'open') return true; + if (audience.posture === 'email_domain') return emailDomainAllowed(email, audience.allowedEmailDomains); return false; } @@ -636,7 +665,9 @@ const socialAddressUnverifiedMessage = (posture: AudiencePosture): string => /** * THE admission decision — pure, so the posture × method matrix is a table of * direct calls. Order: creation-class exemptions → bootstrap → vocabulary - * guard (fail closed) → the social-provider address rule → posture semantics. + * guard (fail closed) → the social-provider address rule → the posture's own + * rule ({@link isAdmittedByPostureRule}, with the self-registration grant) → + * the invitation carve-out (no grant) → the posture's refusal. * * The social-provider address rule: under a posture whose admission rests on * the address ({@link admissionRestsOnAddress}: `email_domain` always, `open` @@ -682,10 +713,20 @@ export function decideAudienceAdmission(input: AudienceAdmissionInput): Audience ) { return { admit: false, code: SELF_REGISTRATION_CLOSED, message: socialAddressUnverifiedMessage(audience.posture) }; } + if (isAdmittedByPostureRule(audience, email)) { + // The posture's own rule first: `open`, and `email_domain` for an address + // on the allowlist, admit the sign-up by that rule, invitation or not, so + // it receives the declared self-registration set. A pending invitation + // still places it as the invitation names once it accepts. The membership + // settle reads the same classification (`isAdmittedByInvitationAlone`). + return { admit: true, grantPermissionSet: true }; + } if (hasPendingInvitation) { // An explicit invitation is a stronger operator act than any posture — // it admits the invitee's own account creation under invite_only AND // trumps the email_domain allowlist (module doc: the invite dead-end). + // Admitted by the invitation alone, the sign-up gets the account and no + // self-registration grant. return { admit: true, grantPermissionSet: false }; } switch (audience.posture) { @@ -698,9 +739,7 @@ export function decideAudienceAdmission(input: AudienceAdmissionInput): Audience 'Ask an administrator for an invitation.', }; case 'email_domain': - if (emailDomainAllowed(email, audience.allowedEmailDomains)) { - return { admit: true, grantPermissionSet: true }; - } + // An address on the allowlist was admitted by the posture's rule above. return { admit: false, code: EMAIL_DOMAIN_NOT_ALLOWED, @@ -708,10 +747,9 @@ export function decideAudienceAdmission(input: AudienceAdmissionInput): Audience 'Self-registration is limited to approved email domains, and this address ' + 'is not on the list. Use your organization email, or ask an administrator for an invitation.', }; - case 'open': - return { admit: true, grantPermissionSet: true }; default: { - // Unreachable for a well-typed posture; keep the fail-closed floor. + // `open` was admitted by the posture's rule above, so this is + // unreachable for a well-typed posture; keep the fail-closed floor. return { admit: false, code: AUDIENCE_CONFIG_ERROR, diff --git a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts index e24ba968922..b9ffe4d58aa 100644 --- a/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-acceptance-verified-address.test.ts @@ -25,11 +25,15 @@ import { describe, it, expect, afterAll, afterEach, beforeEach, vi } from 'vites import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { AuthManager } from './auth-manager.js'; +// The SSO discovery egress guard the source loads with a dynamic import, paid +// here, during collection (check-test-source-alias, "The source reach"). +import '@objectstack/core/egress'; import { authIdentityObjects } from './manifest.js'; import { SIGN_UP_INVITATION_ID_FIELD } from './presented-invitation.js'; import { operatorProvisioningField } from './audience-gate-test-support'; import { ACCEPT_INVITATION_ONE_STEP_PATH } from './invitation-mailbox-proof.js'; import { SELF_REGISTRATION_CLOSED } from './audience-posture.js'; +import { GRANT_SET_NAME_FIELD } from './grant-set-name.js'; import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; @@ -100,7 +104,7 @@ const permissionSetObjects = [ fields: { id: { name: 'id', type: 'text', primaryKey: true }, user_id: { name: 'user_id', type: 'text' }, - permission_set_id: { name: 'permission_set_id', type: 'text' }, + [GRANT_SET_NAME_FIELD]: { name: GRANT_SET_NAME_FIELD, type: 'text' }, organization_id: { name: 'organization_id', type: 'text' }, }, }, @@ -229,11 +233,12 @@ async function verdict(res: Response): Promise<{ status: number; code?: unknown */ async function deployment( config: Record = {}, - { mail = 'live', into = PARTNER_ORG }: { mail?: MailState; into?: string } = {}, + { mail = 'live', into = PARTNER_ORG, grantTable = false }: { mail?: MailState; into?: string; grantTable?: boolean } = {}, ) { - // Both self-registration postures grant the declared set to a sign-up they admit uninvited. + // Both self-registration postures grant the declared set to a sign-up their own rule admits; + // `grantTable` declares the grant store for a posture that declares no set, so its absence can be read. const posture = (config as { audience?: { posture?: unknown } }).audience?.posture; - const engine = await bootEngine({ selfRegistrationSet: posture === 'email_domain' || posture === 'open' }); + const engine = await bootEngine({ selfRegistrationSet: grantTable || posture === 'email_domain' || posture === 'open' }); const sent: SentMail[] = []; const manager = makeManager(engine, sent, config, mail); const first = await send(manager, 'POST', '/sign-up/email', { email: OWNER, password: PASSWORD, name: 'Owner' }); @@ -385,6 +390,46 @@ async function expectDeclined(d: Deployment, cookie: string) { expect(await d.membershipsIn(d.into)).toEqual([]); } +/** The self-registration grants `email` holds, as `[organization, set]` pairs. */ +async function grantsOf(d: Deployment, email: string) { + const [user] = await rows(d.engine, 'sys_user', { email }); + return user + ? (await rows(d.engine, 'sys_user_permission_set', { user_id: user.id })).map((g) => [g.organization_id, g[GRANT_SET_NAME_FIELD]]) + : []; +} + +/** The memberships `email` holds, as `[organization, role]` pairs, sorted. */ +async function membershipsOf(d: Deployment, email: string) { + const [user] = await rows(d.engine, 'sys_user', { email }); + return user ? (await rows(d.engine, 'sys_member', { user_id: user.id })).map((m) => [m.organization_id, m.role]).sort() : []; +} + +/** A password sign-up the posture admits while email verification is in force, so it is not signed in. */ +async function signUpUnverified(d: Deployment, email: string, extra: Record = {}) { + const res = await send(d.manager, 'POST', '/sign-up/email', { email, password: PASSWORD, name: 'Person', ...extra }); + expect(res.status, await res.clone().text()).toBe(200); + expect(cookieFrom(res), 'no session before the mailbox answers').toBe(''); + const [user] = await rows(d.engine, 'sys_user', { email }); + expect(user, `${email} was created`).toBeDefined(); + expect(Boolean(user.email_verified)).toBe(false); +} + +/** Follow the verification mail the sign-up of `email` sent, then sign in with the password. */ +async function verifyAndSignIn(d: Deployment, email: string = INVITEE): Promise { + const mail = await vi.waitFor(() => { + const found = [...d.sent].reverse().find((m) => m.template === 'auth.verify_email' && JSON.stringify(m.to).includes(email)); + expect(found, 'the sign-up sent the verification mail').toBeDefined(); + return found!; + }); + const verified = await send(d.manager, 'GET', String(mail.data.verificationUrl)); + expect(verified.status, await verified.clone().text()).toBeLessThan(400); + const [user] = await rows(d.engine, 'sys_user', { email }); + expect(Boolean(user?.email_verified)).toBe(true); + const signIn = await send(d.manager, 'POST', '/sign-in/email', { email, password: PASSWORD }); + expect(signIn.status, await signIn.clone().text()).toBe(200); + return cookieFrom(signIn); +} + /** Complete the verification mail round trip for the signed-in invitee. */ async function verifyByMail(d: Deployment, cookie: string) { const asked = await send(d.manager, 'POST', '/send-verification-email', { email: INVITEE }, cookie); @@ -583,6 +628,16 @@ describe('under invite_only, a sign-up admitted by the invitation it presents jo expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'member']]); }); + it('CONTROL: the sign-up receives no self-registration permission set, before or after it accepts', async () => { + const d = await deployment({}, { into: DEFAULT_ORG, grantTable: true }); + const cookie = await unverifiedPasswordSession(d); + expect(await grantsOf(d, INVITEE)).toEqual([]); + await verifyByMail(d, cookie); + await expectAccepted(d, cookie); + expect(await membershipsOf(d, INVITEE)).toEqual([[DEFAULT_ORG, 'admin']]); + expect(await grantsOf(d, INVITEE)).toEqual([]); + }); + it('CONTROL: the first account of the deployment is still bound to the default organization', async () => { const d = await deployment({}, { into: DEFAULT_ORG }); const [owner] = await rows(d.engine, 'sys_user', { email: OWNER }); @@ -606,36 +661,6 @@ describe('under email_domain, a sign-up off the allowlist that an invitation adm }; const COLLEAGUE = 'colleague@corp.example'; - const membershipsOf = async (d: Deployment, email: string) => { - const [user] = await rows(d.engine, 'sys_user', { email }); - return user ? (await rows(d.engine, 'sys_member', { user_id: user.id })).map((m) => [m.organization_id, m.role]) : []; - }; - - /** A password sign-up the posture admits; verification is forced on here, so it is not signed in. */ - async function signUpUnverified(d: Deployment, email: string, extra: Record = {}) { - const res = await send(d.manager, 'POST', '/sign-up/email', { email, password: PASSWORD, name: 'Person', ...extra }); - expect(res.status, await res.clone().text()).toBe(200); - expect(cookieFrom(res), 'no session before the mailbox answers').toBe(''); - const [user] = await rows(d.engine, 'sys_user', { email }); - expect(user, `${email} was created`).toBeDefined(); - expect(Boolean(user.email_verified)).toBe(false); - } - - /** Follow the verification mail the sign-up sent, then sign in with the password. */ - async function verifyAndSignIn(d: Deployment): Promise { - const mail = await vi.waitFor(() => { - const found = [...d.sent].reverse().find((m) => m.template === 'auth.verify_email' && JSON.stringify(m.to).includes(INVITEE)); - expect(found, 'the sign-up sent the verification mail').toBeDefined(); - return found!; - }); - const verified = await send(d.manager, 'GET', String(mail.data.verificationUrl)); - expect(verified.status, await verified.clone().text()).toBeLessThan(400); - expect(Boolean((await d.inviteeRow())?.email_verified)).toBe(true); - const signIn = await send(d.manager, 'POST', '/sign-in/email', { email: INVITEE, password: PASSWORD }); - expect(signIn.status, await signIn.clone().text()).toBe(200); - return cookieFrom(signIn); - } - it('the unverified sign-up holds no membership, not even in the default organization', async () => { const d = await deployment(EMAIL_DOMAIN, { into: DEFAULT_ORG }); await signUpUnverified(d, INVITEE); @@ -665,10 +690,11 @@ describe('under email_domain, a sign-up off the allowlist that an invitation adm await expectAccepted(d, cookieFrom(res)); }); - it('CONTROL: an address on the allowlist is bound to the default organization at creation, uninvited or invited', async () => { + it('CONTROL: an address on the allowlist is bound to the default organization at creation and receives the declared permission set, uninvited or invited', async () => { const d = await deployment(EMAIL_DOMAIN, { into: DEFAULT_ORG }); await signUpUnverified(d, COLLEAGUE); expect(await membershipsOf(d, COLLEAGUE)).toEqual([[DEFAULT_ORG, 'member']]); + expect(await grantsOf(d, COLLEAGUE)).toEqual([[DEFAULT_ORG, SELF_REGISTRATION_SET]]); const invitedColleague = 'invited@corp.example'; const invited = await send( @@ -681,6 +707,23 @@ describe('under email_domain, a sign-up off the allowlist that an invitation adm expect(invited.status, await invited.clone().text()).toBe(200); await signUpUnverified(d, invitedColleague); expect(await membershipsOf(d, invitedColleague)).toEqual([[DEFAULT_ORG, 'member']]); + expect(await grantsOf(d, invitedColleague)).toEqual([[DEFAULT_ORG, SELF_REGISTRATION_SET]]); + + // The invitation still places it: once verified it accepts the invited role, and the grant stays the one row. + const cookie = await verifyAndSignIn(d, invitedColleague); + const accept = await send(d.manager, 'POST', '/organization/accept-invitation', { invitationId: String(((await invited.json()) as { id: unknown }).id) }, cookie); + expect(accept.status, await accept.clone().text()).toBe(200); + expect(await membershipsOf(d, invitedColleague)).toEqual([[DEFAULT_ORG, 'member'], [PARTNER_ORG, 'admin']]); + expect(await grantsOf(d, invitedColleague)).toEqual([[DEFAULT_ORG, SELF_REGISTRATION_SET]]); + }); + + it('CONTROL: a sign-up off the allowlist that an invitation admitted receives no self-registration permission set, before or after it accepts', async () => { + const d = await deployment(EMAIL_DOMAIN, { into: DEFAULT_ORG }); + await signUpUnverified(d, INVITEE); + expect(await grantsOf(d, INVITEE)).toEqual([]); + await expectAccepted(d, await verifyAndSignIn(d)); + expect(await membershipsOf(d, INVITEE)).toEqual([[DEFAULT_ORG, 'admin']]); + expect(await grantsOf(d, INVITEE)).toEqual([]); }); it('CONTROL: an address off the allowlist that an operator provisions is bound to the default organization while an invitation to it is pending', async () => { @@ -713,6 +756,27 @@ describe('under email_domain, a sign-up off the allowlist that an invitation adm }); }); +describe('under open, an invited sign-up is admitted by the posture and receives the declared permission set beside its invitation placement', () => { + it('the invited sign-up is bound to the default organization with the declared set at creation, and accepts the invited role', async () => { + const d = await deployment(OPEN, { into: PARTNER_ORG }); + expect((await d.invitation())?.status).toBe('pending'); + await signUpUnverified(d, INVITEE); + expect(await membershipsOf(d, INVITEE)).toEqual([[DEFAULT_ORG, 'member']]); + expect(await grantsOf(d, INVITEE)).toEqual([[DEFAULT_ORG, SELF_REGISTRATION_SET]]); + await expectAccepted(d, await verifyAndSignIn(d)); + expect(await membershipsOf(d, INVITEE)).toEqual([[DEFAULT_ORG, 'member'], [PARTNER_ORG, 'admin']]); + expect(await grantsOf(d, INVITEE)).toEqual([[DEFAULT_ORG, SELF_REGISTRATION_SET]]); + }); + + it('CONTROL: an uninvited sign-up receives the same set', async () => { + const d = await deployment(OPEN, { into: PARTNER_ORG }); + const stranger = 'stranger@anywhere.example'; + await signUpUnverified(d, stranger); + expect(await membershipsOf(d, stranger)).toEqual([[DEFAULT_ORG, 'member']]); + expect(await grantsOf(d, stranger)).toEqual([[DEFAULT_ORG, SELF_REGISTRATION_SET]]); + }); +}); + describe('under an address-based audience posture, a self-serve social creation is admitted only with a provider-verified address', () => { /** {@link ON_LIST} is on this list; {@link OWNER} and {@link ANYONE} are off it. */ const ALLOWLIST = { diff --git a/packages/plugins/plugin-auth/src/presented-invitation.test.ts b/packages/plugins/plugin-auth/src/presented-invitation.test.ts index 84f607abdfa..6625b0ef307 100644 --- a/packages/plugins/plugin-auth/src/presented-invitation.test.ts +++ b/packages/plugins/plugin-auth/src/presented-invitation.test.ts @@ -22,6 +22,9 @@ import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { signUpEmail } from 'better-auth/api'; import { AuthManager } from './auth-manager.js'; +// The SSO discovery egress guard the source loads with a dynamic import, paid +// here, during collection (check-test-source-alias, "The source reach"). +import '@objectstack/core/egress'; import { authIdentityObjects } from './manifest.js'; import { SELF_REGISTRATION_CLOSED } from './audience-posture.js'; import { createCopyInvitationLinkHandler } from './invitation-link-action.js'; @@ -345,7 +348,7 @@ describe('under invite_only, the other creation doors', () => { }); }); -describe('open and email_domain match an invitation by address, as before', () => { +describe('email_domain matches an invitation by address, as before', () => { const gate = (manager: AuthManager, email: string) => (manager as unknown as { validateAudienceAdmission(data: unknown, ctx?: unknown): Promise<{ error: string } | undefined>; @@ -354,20 +357,23 @@ describe('open and email_domain match an invitation by address, as before', () = { body: {} }, ); - // Under `open` an uninvited sign-up is admitted WITH the declared set, which - // this store cannot resolve (it would answer AUTH_CONFIG_ERROR), and under - // `email_domain` this address is off the list: so `undefined` below can only - // be the invitation carve-out, matched by address. - for (const audience of [ - { posture: 'open', selfRegistrationPermissionSet: 'member_default' }, - { posture: 'email_domain', allowedEmailDomains: ['elsewhere.example'], selfRegistrationPermissionSet: 'member_default' }, - ]) { - it(`${audience.posture}: an email-and-password sign-up holding an invitation is admitted with no id`, async () => { - const d = await deployment(); - await d.invite(INVITEE); - const manager = makeManager(d.engine, { audience }); - expect(await gate(manager, INVITEE)).toBeUndefined(); - expect((await gate(manager, OTHER))?.error).not.toBeUndefined(); - }); - } + // This address is off the list, and this store cannot resolve the declared + // set (a sign-up the posture's rule admits would answer AUTH_CONFIG_ERROR): + // so `undefined` below can only be the invitation carve-out, matched by + // address, which asks for no set. Under `open` the posture's rule admits + // every address, so an invitation decides nothing there: an invited sign-up + // asks for the declared set like an uninvited one, and an unresolvable set + // refuses both (`audience-posture.test.ts`, the end of the chain). + const audience = { + posture: 'email_domain', + allowedEmailDomains: ['elsewhere.example'], + selfRegistrationPermissionSet: 'member_default', + }; + it('email_domain: an email-and-password sign-up off the list holding an invitation is admitted with no id', async () => { + const d = await deployment(); + await d.invite(INVITEE); + const manager = makeManager(d.engine, { audience }); + expect(await gate(manager, INVITEE)).toBeUndefined(); + expect((await gate(manager, OTHER))?.error).not.toBeUndefined(); + }); }); diff --git a/packages/qa/dogfood/test/signup-organization-census-walled.dogfood.test.ts b/packages/qa/dogfood/test/signup-organization-census-walled.dogfood.test.ts index 7c7909481a0..c6134ede203 100644 --- a/packages/qa/dogfood/test/signup-organization-census-walled.dogfood.test.ts +++ b/packages/qa/dogfood/test/signup-organization-census-walled.dogfood.test.ts @@ -16,8 +16,9 @@ // - the self-registration grant (`sys_user_permission_set`) settles on the // self-registrant's FIRST MEMBERSHIP, owned by that membership's // organization (ADR-0131 D3) — never at sign-up, when there is no -// organization yet; the invitee is admitted by the invitation, not by the -// open posture, and is owed no declared set; +// organization yet; the invitee is admitted by the open posture, +// invitation or not, so its declared set settles on its first membership +// too, the organization whose invitation it accepted; // - the activity writer (`sys_activity`) stamps the organization of the // record it is about, and writes NO row about a record that has none // (ADR-0131 D9; ruling of record 6257510973 item 3, Q3 A); @@ -212,11 +213,13 @@ for (const posture of ['group', 'isolated'] as const) { // The creator's `organization_admin` (the auto org-admin grant) rides // the same membership; every grant names the organization. expect(grants.filter((g: Row) => g.organization_id !== orgId), 'grants outside the organization').toEqual([]); - // The invitee was admitted by the invitation, not by the open posture, so - // is owed no declared set (`decideAudienceAdmission`); whatever it holds - // names the organization too. + // The open posture admits the invitee by its own rule, invitation or not, + // so it is owed the declared set like the registrant + // (`decideAudienceAdmission`); the grant settles on its first membership, + // the organization whose invitation it accepted, and every grant it + // holds names that organization. const inviteeGrants = await ql.find('sys_user_permission_set', { where: { user_id: inviteeId }, ...SYS }); - expect(inviteeGrants.filter((g: Row) => g.permission_set === SET), 'the invitee holds no declared grant').toEqual([]); + expect(inviteeGrants.filter((g: Row) => g.permission_set === SET).map((g: Row) => g.organization_id), 'the invitee\'s declared grant').toEqual([orgId]); expect(inviteeGrants.filter((g: Row) => g.organization_id !== orgId), 'invitee grants outside the organization').toEqual([]); }); diff --git a/packages/spec/src/migrations/entries/semantic/18.self-registration-permission-set-reaches-invited-sign-ups.ts b/packages/spec/src/migrations/entries/semantic/18.self-registration-permission-set-reaches-invited-sign-ups.ts new file mode 100644 index 00000000000..4cb33f39de8 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.self-registration-permission-set-reaches-invited-sign-ups.ts @@ -0,0 +1,35 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the change of meaning the plugin-auth admission +// verdict landed (ruling record 7063136215, option A): one rule for an invited +// and an uninvited self-registration. No key of any schema is added, removed, +// renamed or re-shaped, so there is no tombstone and no D2 conversion: whether +// the declared set is the one an invited person should receive, and repairing +// a set that cannot be resolved, are the operator's to judge. +export const entry: SemanticMigration = { + id: 'self-registration-permission-set-reaches-invited-sign-ups', + surface: + 'system.AuthConfig.audience.selfRegistrationPermissionSet under the `open` posture, and under `email_domain` ' + + 'for an address on `allowedEmailDomains`: a self-serve sign-up that also holds a pending invitation', + replacement: + 'Keep `selfRegistrationPermissionSet` naming a permission set that exists and is switched on, and confirm it ' + + 'is the access an invited person the posture admits should hold beside the membership and role the ' + + 'invitation names. A person who must join without that set is created by an administrator instead', + reason: + 'The admission verdict read a pending invitation before the posture\'s own rule, so an invited sign-up the ' + + 'posture admits (any address under `open`, an address on the allowlist under `email_domain`) was admitted ' + + 'with no self-registration grant, whether or not the declared set could be resolved, while the membership ' + + 'settle already classified the same sign-up as admitted by the posture. It is now a self-registrant, ' + + 'invitation or not: it receives the declared set, and when the set cannot be resolved (not in the security ' + + 'catalog, or switched off in the activation ledger) it is refused 403 AUTH_CONFIG_ERROR like an uninvited ' + + 'sign-up; no account is created. Unchanged: under `invite_only`, and for an address off the allowlist under ' + + '`email_domain`, an invitation admits by itself and asks for no set. There is no mechanical rewrite: which ' + + 'set the operator meant is not in the stack', + acceptanceCriteria: + 'Under the deployment\'s posture, an invited sign-up whose address the posture admits completes sign-up and ' + + 'holds the declared set (a `sys_user_permission_set` row naming it) beside the membership its accepted ' + + 'invitation writes, and with the set name pointed at a set that does not exist the same sign-up answers ' + + '403 AUTH_CONFIG_ERROR naming the set', +};