diff --git a/.changeset/email-domain-invitation-sign-up-unbound-until-verified.md b/.changeset/email-domain-invitation-sign-up-unbound-until-verified.md new file mode 100644 index 00000000000..ffc7ece404d --- /dev/null +++ b/.changeset/email-domain-invitation-sign-up-unbound-until-verified.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: a sign-up the email_domain posture admits by an invitation is not bound before its address is verified + +Clause-②: no (narrowing) — narrowed: under the `email_domain` audience posture with `membershipPolicy: 'auto'`, a self-serve sign-up whose address is off the allowlist, admitted by a pending invitation addressed to it, is not bound to the Default Organization while its address is unverified; it joins by accepting the invitation. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the `email_domain` posture's invitation sign-up; `content/docs/deployment/self-hosting.mdx` gains the rule in this change. + + + +**BREAKING** for an `email_domain` deployment with `membershipPolicy: 'auto'` that relies on an invited address outside its allowlist joining the Default Organization when it signs up. + +- Under `email_domain` with `membershipPolicy: 'auto'`, an account that a sign-up off the allowlist created, admitted by a pending invitation addressed to it, is not bound to the Default Organization while its address is unverified. Its membership comes from accepting the invitation once the address is verified, with the role the invitation carries, or from a platform administrator. Verifying the address binds nothing by itself. +- This is the rule that already holds under `invite_only` for a sign-up admitted by the invitation it presents; both postures now read one decision, `isAdmittedByInvitationAlone` (`audience-posture.ts`). + +Unchanged: an address on the allowlist, invited or not, which the domain rule admits and the membership policy binds at creation; a sign-up the invitation mail's own link verifies as it accepts; the first account of a deployment, accounts an administrator creates and accounts a boot command provisions, which are bound as before; the `invite_only` and `open` postures. + +What to do: an invitee outside the allowlist completes the verification mail the sign-up sends, signs in and accepts the invitation, or opens the invitation mail's own link, which verifies the address and accepts in one step. A platform administrator can instead attach the account with the member list's **Add Member** action. diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index 0d2bd0d37d2..297eb500afb 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -97,7 +97,7 @@ Read by `@objectstack/service-print` when `PrintServicePlugin` is composed; see | `OS_AUTH_EMAIL_PASSWORD_ENABLED` | boolean | settings default | Settings env override for `auth.email_password_enabled`. Controls local email/password login. | | `OS_AUTH_SIGNUP_ENABLED` | boolean | settings default | Settings env override for `auth.signup_enabled`. Takes precedence over UI settings and is preferred over `OS_DISABLE_SIGNUP`. | | `OS_AUTH_REQUIRE_EMAIL_VERIFICATION` | boolean | settings default | Settings env override for `auth.require_email_verification`. Under the `open` audience posture, `false` is the deployment's opt-out from the forced verification (one boot warning; see [Email verification under each posture](/docs/deployment/self-hosting#email-verification-under-each-posture)); under `email_domain` it is refused, since verification is forced there. | -| `OS_AUTH_MEMBERSHIP_POLICY` | `auto` \| `invite-only` | `auto` | Settings env override for `auth.membership_policy` — what a newly created user joins (ADR-0093 D1). `auto` binds every new user to the deployment's default organization, except, under the `invite_only` audience posture, a sign-up admitted by the invitation it presents whose address is unverified, which joins by accepting. `invite-only` grants membership solely through an explicit act: creating a workspace, accepting an invitation, an admin adding them, or SSO just-in-time provisioning. Applies to sign-up **and** to the backfill of pre-existing member-less users. An unrecognized value is rejected with an `error` log and **ignored** — the deployment keeps its current policy rather than silently reverting to `auto`. | +| `OS_AUTH_MEMBERSHIP_POLICY` | `auto` \| `invite-only` | `auto` | Settings env override for `auth.membership_policy` — what a newly created user joins (ADR-0093 D1). `auto` binds every new user to the deployment's default organization, except a sign-up admitted by its invitation alone whose address is unverified, which joins by accepting: under the `invite_only` audience posture, one admitted by the invitation it presents; under `email_domain`, one whose address is off the allowlist and which an invitation addressed to it admitted. `invite-only` grants membership solely through an explicit act: creating a workspace, accepting an invitation, an admin adding them, or SSO just-in-time provisioning. Applies to sign-up **and** to the backfill of pre-existing member-less users. An unrecognized value is rejected with an `error` log and **ignored** — the deployment keeps its current policy rather than silently reverting to `auto`. | | `OS_ORG_INVITATION_LIMIT` | integer \| `off` | unset (100) | How many **pending** invitations one organization may hold at once. When the organization already holds that many, `POST /api/v1/auth/organization/invite-member` answers `403 INVITATION_LIMIT_REACHED` (`Invitation limit reached`) until an invitation is accepted, rejected, cancelled or expires. Unset keeps the auth library's own limit of 100, so a deployment that sets nothing behaves as before. A positive integer `N` allows `N`. `off`, `unlimited` or `none` (any case) removes the limit, for a host that invites people in bulk. `0`, or any value that is not plain digits (`-5`, `2.5`, `1e3`, `1_000`), reads as unset (100), so a typo never refuses every invitation. The count is per organization, not per inviter. Read when the auth plugin builds its organization plugin, so a change needs a process reload. | | `OS_AUTH_GOOGLE_ENABLED` | boolean | settings default | Settings env override for `auth.google_enabled`. Requires Google OAuth credentials from Settings or env. | | `GOOGLE_CLIENT_ID` | string | — | Deployment-level Google OAuth client id for the open-source Google login implementation. | diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 563c557f024..35b24e74d08 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -760,6 +760,15 @@ account of a new deployment needs no invitation. Admission is all the invitation's `id` grants: the account it admits joins no organization until it accepts the invitation, and accepting needs a verified address. +**Under `email_domain`, an invitation admits an address off the allowlist, and +grants nothing more.** A pending invitation addressed to an address outside +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. + **Accepting, declining and listing an invitation need a verified email address, on every deployment.** The invitation's `id`, which its link carries, proves nothing about the mailbox. From a session whose address is not diff --git a/content/docs/deployment/tenancy-modes.mdx b/content/docs/deployment/tenancy-modes.mdx index c63215515e6..1c2140f0cee 100644 --- a/content/docs/deployment/tenancy-modes.mdx +++ b/content/docs/deployment/tenancy-modes.mdx @@ -243,10 +243,14 @@ The reconciler: - **yields** to any membership that already exists (e.g. one created by an invitation, `add-member`, SSO provisioning, or a host hook) — it never creates a second membership; -- does **not** bind, under the `invite_only` audience posture, a sign-up - admitted by the invitation it presents while the account's email address is - unverified: that account joins by accepting the invitation, which needs a - verified address ([Self-hosting](/docs/deployment/self-hosting)); +- does **not** bind a sign-up admitted by its invitation alone while the + account's email address is unverified — under the `invite_only` audience + posture, a sign-up admitted by the invitation it presents; under + `email_domain`, a sign-up whose address is off the allowlist and which an + invitation addressed to it admitted: that account joins by accepting the + invitation, which needs a verified address + ([Self-hosting](/docs/deployment/self-hosting)). Under `email_domain` an + address on the allowlist is admitted by its domain and is bound; - binds only to an **unambiguous** target org — that is `tenancy.defaultOrgId()`, which returns the single-org default organization under `single` and `null` under any walled **request** (invitations, `add-member` and SSO provisioning diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 103710f043e..1302545ea7c 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -123,9 +123,11 @@ OS_AUTH_SIGNUP_ENABLED=false OS_AUTH_GOOGLE_ENABLED=true # Optional: what a new user joins (ADR-0093 D1). `auto` (default) binds every -# new user to the default organization (except, under the `invite_only` -# audience posture, a sign-up admitted by the invitation it presents whose -# address is unverified: it joins by accepting); `invite-only` grants membership only +# new user to the default organization (except a sign-up admitted by its +# invitation alone whose address is unverified: under the `invite_only` +# audience posture, one admitted by the invitation it presents; under +# `email_domain`, one off the allowlist that an invitation addressed to it +# admitted. It joins by accepting); `invite-only` grants membership only # through an explicit act — creating a workspace, accepting an invitation, an # admin adding them, or SSO just-in-time provisioning. # Also configurable in Setup → Authentication → Membership. diff --git a/packages/plugins/plugin-auth/src/audience-posture.test.ts b/packages/plugins/plugin-auth/src/audience-posture.test.ts index d4d666b8143..27c8e56cf09 100644 --- a/packages/plugins/plugin-auth/src/audience-posture.test.ts +++ b/packages/plugins/plugin-auth/src/audience-posture.test.ts @@ -32,6 +32,7 @@ import { emailDomainAllowed, extractEmailDomain, invitationProofFor, + isAdmittedByInvitationAlone, resolveAudience, resolveEmailVerificationRequirement, SELF_REGISTRATION_CLOSED, @@ -1086,3 +1087,44 @@ describe('the invitation a creation must show (invitationProofFor)', () => { expect(proof({ audience: audience({ posture: 'open' }), method: 'oauth', emailVerified: false })).toBe('address'); }); }); + +describe('a sign-up admitted by its invitation alone (isAdmittedByInvitationAlone)', () => { + const DOMAIN = audience({ posture: 'email_domain', allowedEmailDomains: ['acme.com'] }); + const alone = (over: Partial[0]> = {}) => + isAdmittedByInvitationAlone({ + audience: DOMAIN, + creationClass: 'self-serve', + email: 'contractor@partner.example', + proof: 'address', + hasPendingInvitation: true, + ...over, + }); + + it('under email_domain, an address off the allowlist admitted by an invitation addressed to it is admitted by its invitation alone', () => { + expect(alone()).toBe(true); + expect(alone({ email: 'Contractor@Mail.Acme.com' }), 'a subdomain is off the list').toBe(true); + expect(alone({ email: undefined }), 'no address is off the list').toBe(true); + }); + + it('under email_domain, an address on the allowlist is admitted by its domain, invitation or not', () => { + expect(alone({ email: 'colleague@acme.com' })).toBe(false); + expect(alone({ email: 'Colleague+tag@ACME.COM' })).toBe(false); + expect(alone({ email: 'colleague@acme.com', hasPendingInvitation: false })).toBe(false); + }); + + it('under invite_only, only a sign-up that presented its invitation is admitted by its invitation alone', () => { + const invite = audience(); + expect(alone({ audience: invite, proof: 'presented' })).toBe(true); + expect(alone({ audience: invite, proof: 'address' })).toBe(false); + expect(alone({ audience: invite, proof: 'none' })).toBe(false); + }); + + it('a creation no pending invitation admitted, a creation that is not self-serve, open and an off-vocabulary posture are never admitted by an invitation alone', () => { + expect(alone({ hasPendingInvitation: false })).toBe(false); + expect(alone({ audience: audience(), proof: 'presented', hasPendingInvitation: false })).toBe(false); + expect(alone({ creationClass: 'operator' })).toBe(false); + expect(alone({ creationClass: 'provider' })).toBe(false); + expect(alone({ audience: audience({ posture: 'open' }) })).toBe(false); + expect(alone({ audience: { ...DOMAIN, invalid: { raw: "'bogus'" } } })).toBe(false); + }); +}); diff --git a/packages/plugins/plugin-auth/src/audience-posture.ts b/packages/plugins/plugin-auth/src/audience-posture.ts index adc5b61f2f8..af38cf7f46e 100644 --- a/packages/plugins/plugin-auth/src/audience-posture.ts +++ b/packages/plugins/plugin-auth/src/audience-posture.ts @@ -72,6 +72,12 @@ * verified the address, is matched by address. `open` and `email_domain` * match every creation by address. * + * 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. + * * ## Pinned domain-matching rules (`email_domain`) * * An unpinned matcher is where this class of gate leaks, so the rules are @@ -525,6 +531,38 @@ export function invitationProofFor(input: { return 'address'; } +/** + * Whether an admitted self-serve sign-up was admitted by its invitation alone, + * so the membership settle does not bind it into the deployment's + * organization while its address is unverified (`settleMembership`, + * `auth-manager-membership-admission.ts`). It joins by accepting the + * invitation, which needs a verified address and writes the role the issuer + * chose. An invitation proves no mailbox: under `invite_only` its id is + * carried by the accept link and by a copied link, and under `email_domain` + * the address match reads only the address the sign-up typed. + * + * - `invite_only`: the sign-up presented the invitation, which is pending, + * 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. + * - `open`, an off-vocabulary posture, and every creation that is not + * self-serve: never. + */ +export function isAdmittedByInvitationAlone(input: { + audience: ResolvedAudience; + creationClass: AudienceCreationClass; + email: string | undefined; + proof: InvitationProof; + hasPendingInvitation: boolean; +}): boolean { + const { audience, creationClass, email, proof, hasPendingInvitation } = input; + if (!hasPendingInvitation || audience.invalid || creationClass !== 'self-serve') return false; + if (audience.posture === 'invite_only') return proof === 'presented'; + if (audience.posture === 'email_domain') return !emailDomainAllowed(email, audience.allowedEmailDomains); + return false; +} + /** The refusal message for an unknown user arriving through an SSO provider under `invite_only`. */ const SSO_JIT_CLOSED_MESSAGE = 'This single sign-on provider does not create accounts for people who were not invited ' + diff --git a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts index 382e50d959c..041b6ff566a 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts @@ -59,8 +59,10 @@ import { classifyCreationMethod, decideAudienceAdmission, invitationProofFor, + isAdmittedByInvitationAlone, AUDIENCE_CONFIG_ERROR, type AudienceCreationClass, + type InvitationProof, } from './audience-posture.js'; import { GRANT_SET_NAME_FIELD } from './grant-set-name.js'; import { presentedInvitationId } from './presented-invitation.js'; @@ -96,17 +98,22 @@ export interface MembershipAdmissionHost { } /** - * Under `invite_only`, a sign-up admitted by the invitation it PRESENTS is not - * bound into the deployment's organization while its address is unverified. + * A sign-up admitted by its invitation alone is not bound into the + * deployment's organization while its address is unverified: under + * `invite_only`, one admitted by the invitation it PRESENTS; under + * `email_domain`, one whose address is off the allowlist and which an + * invitation addressed to it admitted (`isAdmittedByInvitationAlone`, + * `audience-posture.ts`). * - * The presented id is the admission ticket, and nothing more: the accept link - * and a copied link both carry it, so it proves nothing about the invited + * The invitation is the admission ticket, and nothing more: the presented id + * is carried by the accept link and by a copied link, and the address match + * reads only the address the sign-up typed, so neither proves the invited * mailbox. Membership comes from accepting the invitation, which needs a * verified address (`invitation-accept-verified-email.ts`) and writes the role * the issuer chose, or from a platform administrator's Add Member. * * A policy-skip, not a bind deferred to the moment the address is verified: - * - the invitation is the instrument of admission under this posture, and its + * - the invitation is the instrument of admission for such a sign-up, and its * acceptance already writes the membership once the address is verified; a * second, role-less bind at verification would let a verified person who * never accepted (or who declined) join the organization by a route no @@ -122,7 +129,7 @@ export interface MembershipAdmissionHost { * when a seam hands none). The admission is staged on that request * (`stageInvitationAdmission`), so it never reaches another creation of the * same address in another request, and every creation this request did not - * admit by a presented invitation pays one in-memory lookup. A user row that + * admit by its invitation alone pays one in-memory lookup. A user row that * cannot be read while this request staged an admission answers yes: the * settle then binds nothing, the direction that keeps the rule. */ @@ -166,11 +173,11 @@ export async function settleMembership( ): Promise { try { const id = typeof userId === 'string' && userId ? userId : undefined; - // A sign-up admitted by a presented invitation is not bound while its + // A sign-up admitted by its invitation alone is not bound while its // address is unverified ({@link invitationSignUpAwaitsVerification}). if (id && (await invitationSignUpAwaitsVerification.call(this, id, await settleRequestContext(ctx)))) { this.config.logger?.info?.( - '[membership] not bound: a sign-up admitted by the invitation it presents joins by accepting the invitation once its address is verified', + '[membership] not bound: a sign-up admitted by its invitation alone joins by accepting the invitation once its address is verified', { userId: id }, ); return 'policy-skip'; @@ -248,7 +255,7 @@ export async function validateAudienceAdmission( : undefined; let isBootstrap = false; let hasPendingInvitation = false; - let admittedByPresentedInvitation = false; + let proof: InvitationProof = 'none'; if (creationClass === 'self-serve' || (ssoProvider !== undefined && !ssoProvider.allowJit)) { // Only the gated creations pay for the probes. isBootstrap = await this.isBootstrapCreation(); @@ -256,7 +263,7 @@ export async function validateAudienceAdmission( // Under `invite_only` a self-serve sign-up is admitted only by the // invitation it presents (`invitationProofFor`): its id, read off the // same parsed body the operator ticket above is read from. - const proof = invitationProofFor({ + proof = invitationProofFor({ audience, creationClass, method: data?.source?.method, @@ -264,7 +271,6 @@ export async function validateAudienceAdmission( }); if (proof === 'presented') { hasPendingInvitation = await this.hasPresentedPendingInvitation(presentedInvitationId(ctx), email); - admittedByPresentedInvitation = hasPendingInvitation; } else if (proof === 'address') { hasPendingInvitation = await this.hasPendingInvitationFor(email); } @@ -313,9 +319,10 @@ export async function validateAudienceAdmission( ) { this.stageOwnerVerifiedStamp(email); } - // Admitted by the invitation it presents: the membership settle does not - // bind this sign-up while its address is unverified (`settleMembership`). - if (email && admittedByPresentedInvitation) { + // Admitted by its invitation alone (`isAdmittedByInvitationAlone`): the + // membership settle does not bind this sign-up while its address is + // unverified (`settleMembership`). + if (email && isAdmittedByInvitationAlone({ audience, creationClass, email, proof, hasPendingInvitation })) { this.stageInvitationAdmission(ctx, email); } if (verdict.grantPermissionSet) { diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 8c145edf8af..d37ed3ff366 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -3416,7 +3416,7 @@ export class AuthManager { /** * The addresses the admission gate admitted in each in-flight better-auth - * request by the invitation they PRESENT (under `invite_only`), keyed by + * request by their invitation alone (`isAdmittedByInvitationAlone`), keyed by * that request's endpoint context — the object better-auth hands the * admission gate and every database hook of the same endpoint call, as * {@link usersCreatedInRequest} is. `settleMembership` @@ -3430,7 +3430,7 @@ export class AuthManager { */ private invitationAdmissionsInRequest = new WeakMap>(); - /** Record that the current request's admission gate admitted `email` by the invitation it presents. */ + /** Record that the current request's admission gate admitted `email` by its invitation alone. */ private stageInvitationAdmission(ctx: unknown, email: string): void { if (!ctx || typeof ctx !== 'object') return; let staged = this.invitationAdmissionsInRequest.get(ctx); @@ -3441,13 +3441,13 @@ export class AuthManager { staged.add(email.trim().toLowerCase()); } - /** Did this request admit any address by the invitation it presents? In-memory only. */ + /** Did this request admit any address by its invitation alone? In-memory only. */ private hasInvitationAdmissionInRequest(ctx: unknown): boolean { if (!ctx || typeof ctx !== 'object') return false; return (this.invitationAdmissionsInRequest.get(ctx)?.size ?? 0) > 0; } - /** Did this request admit `email` by the invitation it presents? In-memory only. */ + /** Did this request admit `email` by its invitation alone? In-memory only. */ private isInvitationAdmissionInRequest(ctx: unknown, email: string): boolean { if (!ctx || typeof ctx !== 'object') return false; return this.invitationAdmissionsInRequest.get(ctx)?.has(email.trim().toLowerCase()) === true; 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 d2c0483aeb1..d77da48eb7c 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 @@ -9,7 +9,8 @@ * the invitation's id, which its accept link and its copied link carry, * proves nothing about the mailbox — and, under `invite_only`, a sign-up * admitted by the id it presents is not bound into the deployment's - * organization while its address is unverified. + * organization while its address is unverified, nor, under `email_domain`, a + * sign-up off the allowlist that an invitation addressed to it admitted. * * The real `AuthManager` over a real driver (`@objectstack/driver-sql` on * better-sqlite3 `:memory:`, plugin-auth's own identity objects), driven @@ -29,6 +30,8 @@ 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 { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; +import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; +import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; const BASE = 'http://localhost:3000'; const AUTH = `${BASE}/api/v1/auth`; @@ -73,7 +76,36 @@ interface SentMail { /** What the social provider asserts about the person signing in. */ let providerProfile: { sub: string; email: string; email_verified: boolean } | null = null; -async function bootEngine(): Promise { +/** + * The self-registration permission set a domain-admitted sign-up is granted, + * declared with only the columns the audience gate reads + * (`signup-existing-address-success-shape.test.ts`'s precedent). + */ +const SELF_REGISTRATION_SET = 'member_default'; +const permissionSetObjects = [ + { + name: 'sys_permission_set', + label: 'Permission Set', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + label: { name: 'label', type: 'text' }, + active: { name: 'active', type: 'boolean' }, + }, + }, + { + name: 'sys_user_permission_set', + label: 'User Permission Set', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + user_id: { name: 'user_id', type: 'text' }, + permission_set_id: { name: 'permission_set_id', type: 'text' }, + organization_id: { name: 'organization_id', type: 'text' }, + }, + }, +]; + +async function bootEngine({ selfRegistrationSet = false }: { selfRegistrationSet?: boolean } = {}): Promise { const engine = new ObjectQL(); engines.push(engine); engine.registerDriver( @@ -84,7 +116,18 @@ async function bootEngine(): Promise { for (const object of authIdentityObjects) { engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); } + if (selfRegistrationSet) { + for (const object of permissionSetObjects) engine.registry.registerObject(object as never, '@objectstack/plugin-security'); + } await engine.syncSchemas(); + if (selfRegistrationSet) { + // The organization-less catalogue row exists only on a store built before 18.x. + await relaxTenantColumns(engine, ['sys_permission_set']); + bindTestSecurityCatalog(engine, { permissions: [{ name: SELF_REGISTRATION_SET }] }); + await (engine as unknown as { getDriver(o: string): { create(o: string, row: unknown): Promise } }) + .getDriver('sys_permission_set') + .create('sys_permission_set', { id: 'ps_member_default', name: SELF_REGISTRATION_SET, label: SELF_REGISTRATION_SET, active: true }); + } await engine.insert('sys_organization', { id: DEFAULT_ORG, name: 'Default', slug: 'default' }, SYSTEM); await engine.insert('sys_organization', { id: PARTNER_ORG, name: 'Partner', slug: 'partner' }, SYSTEM); return engine; @@ -187,7 +230,9 @@ async function deployment( config: Record = {}, { mail = 'live', into = PARTNER_ORG }: { mail?: MailState; into?: string } = {}, ) { - const engine = await bootEngine(); + const engine = await bootEngine({ + selfRegistrationSet: (config as { audience?: { posture?: unknown } }).audience?.posture === 'email_domain', + }); 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' }); @@ -224,7 +269,7 @@ async function deployment( return user ? rows(engine, 'sys_member', { user_id: user.id }) : []; }; const inviteeRow = async () => (await rows(engine, 'sys_user', { email: INVITEE }))[0]; - return { engine, manager, sent, into, invitationId, invitation, membershipsIn, allMemberships, inviteeRow }; + return { engine, manager, sent, into, invitationId, invitation, membershipsIn, allMemberships, inviteeRow, ownerCookie }; } type Deployment = Awaited>; @@ -515,3 +560,113 @@ function proofFromMail(d: Deployment): string { expect(match, `the invitation mail's link carries the proof: ${link}`).not.toBeNull(); return decodeURIComponent(match![1]!); } + +describe('under email_domain, a sign-up off the allowlist that an invitation admitted joins only by accepting it once verified', () => { + /** {@link INVITEE} and {@link OWNER} are off this list; {@link COLLEAGUE} is on it. */ + const EMAIL_DOMAIN = { + audience: { posture: 'email_domain', allowedEmailDomains: ['corp.example'], selfRegistrationPermissionSet: SELF_REGISTRATION_SET }, + }; + 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); + expect(await d.allMemberships()).toEqual([]); + expect((await d.invitation())?.status).toBe('pending'); + }); + + it('verifying the address binds nothing by itself; accepting the invitation then writes its membership with the invited role', async () => { + const d = await deployment(EMAIL_DOMAIN, { into: DEFAULT_ORG }); + await signUpUnverified(d, INVITEE); + const cookie = await verifyAndSignIn(d); + expect(await d.allMemberships()).toEqual([]); + await expectAccepted(d, cookie); + expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'admin']]); + }); + + it('an account a social provider made for that address, unverified, holds no membership and is refused at accept', async () => { + const d = await deployment(EMAIL_DOMAIN, { into: DEFAULT_ORG }); + const cookie = await socialSession(d, false); + expect(await d.allMemberships()).toEqual([]); + await expectAnswerRefusedReadOpen(d, cookie); + expect(await d.allMemberships()).toEqual([]); + }); + + it('CONTROL: an address on the allowlist is bound to the default organization at creation, 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']]); + + const invitedColleague = 'invited@corp.example'; + const invited = await send( + d.manager, + 'POST', + '/organization/invite-member', + { email: invitedColleague, role: 'admin', organizationId: PARTNER_ORG }, + d.ownerCookie, + ); + expect(invited.status, await invited.clone().text()).toBe(200); + await signUpUnverified(d, invitedColleague); + expect(await membershipsOf(d, invitedColleague)).toEqual([[DEFAULT_ORG, 'member']]); + }); + + 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 () => { + const d = await deployment(EMAIL_DOMAIN, { into: PARTNER_ORG }); + const res = await send(d.manager, 'POST', '/sign-up/email', { + email: INVITEE, password: PASSWORD, name: 'Invitee', ...operatorProvisioningField(d.manager, INVITEE), + }); + expect(res.status, await res.clone().text()).toBe(200); + expect((await d.invitation())?.status).toBe('pending'); + expect((await d.allMemberships()).map((m) => [m.organization_id, m.role])).toEqual([[DEFAULT_ORG, 'member']]); + }); + + it('CONTROL: a sign-up the invitation mail proof verifies is bound to the default organization at creation, and accepts the invited role', async () => { + const d = await deployment(EMAIL_DOMAIN, { into: PARTNER_ORG }); + const res = await send(d.manager, 'POST', ACCEPT_INVITATION_ONE_STEP_PATH, { + invitationId: d.invitationId, + proof: proofFromMail(d), + name: 'Invitee', + password: PASSWORD, + }); + expect(res.status, await res.clone().text()).toBe(200); + const held = (await d.allMemberships()).map((m) => [m.organization_id, m.role]).sort(); + expect(held).toEqual([[DEFAULT_ORG, 'member'], [PARTNER_ORG, 'admin']].sort()); + }); + + it('CONTROL: the first account of the deployment, off the allowlist, is bound to the default organization', async () => { + const d = await deployment(EMAIL_DOMAIN, { into: DEFAULT_ORG }); + const [owner] = await rows(d.engine, 'sys_user', { email: OWNER }); + expect((await rows(d.engine, 'sys_member', { user_id: owner.id, organization_id: DEFAULT_ORG })).length).toBe(1); + }); +}); +