From c65a5f45d7535d9bda090bc68bb532d5ed7f4f33 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:54:53 +0000 Subject: [PATCH 1/5] fix(plugin-auth): import-users joins each row to the administrator's current organization in multi-org mode Claude-Session: https://claude.ai/code/session_01ADHkmQ6fcQhYhhjvBoSuKn Co-authored-by: Claude --- .../admin-import-users-manager-pass.test.ts | 255 +++++++++++++++++- .../plugin-auth/src/admin-import-users.ts | 126 ++++++++- .../plugin-auth/src/admin-user-endpoints.ts | 116 +++++--- .../plugins/plugin-auth/src/auth-plugin.ts | 11 + 4 files changed, 450 insertions(+), 58 deletions(-) diff --git a/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts b/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts index 67221871964..834d7b238a0 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts @@ -45,7 +45,7 @@ import { validationFailure } from '@objectstack/types'; import { runAdminImportUsers, type IdentityImportDeps } from './admin-import-users.js'; import { settleImportResetDelivery } from './account-invitation-marker.js'; import { SYS_USER_PROFILE_EDIT_FIELDS, SYS_USER_IMPORT_UPDATE_FIELDS } from './sys-user-writable-fields.js'; -import type { AdminActor } from './admin-user-endpoints.js'; +import { settleCurrentOrganizationJoin, type AdminActor } from './admin-user-endpoints.js'; const ACTOR: AdminActor = { id: 'usr_admin', email: 'admin@example.com' }; /** [#33113] The administrator's own execution context, as the grant seam resolves it. */ @@ -115,6 +115,16 @@ function makeHarness(opts: { */ grant?: { catalog: string[]; denied?: string[] } | 'no-context'; seedUserPositions?: Row[]; + /** + * [#34535] Multi-org mode: the organization wall is in force and the + * administrator's current organization is `callerActiveOrg` (`null` ⇒ none). + * `memberCap` is the organization's member limit, refused as better-auth + * refuses it; `withSeam: false` wires no unit of work, `addMember: false` no + * organization plugin. In this mode a position assignment is refused for a + * user who is not a member of the current organization (the grant-holder + * membership refusal), and the unit of work really rolls the tables back. + */ + multiOrg?: { callerActiveOrg: string | null; memberCap?: number; withSeam?: boolean; addMember?: boolean }; } = {}) { const tables: Record = { sys_user: (opts.seedUsers ?? []).map((u) => ({ manager_id: null, source: 'env_native', ...u })), @@ -181,6 +191,15 @@ function makeHarness(opts: { // it — and only for a non-system write, which is exactly why the importer // must hand it the administrator's own context. if (object === 'sys_user_position' && !options?.context?.isSystem && typeof opts.grant === 'object') { + // [#34535] The grant-holder membership refusal: in multi-org mode a + // position is assigned only to a member of the current organization. + if (opts.multiOrg && !tables.sys_member.some( + (m) => m.user_id === data.user_id && m.organization_id === opts.multiOrg!.callerActiveOrg, + )) { + throw validationFailure(`User '${data.user_id}' is not a member of this organization`, [ + { field: 'user_id', code: 'reference_not_found', message: 'names no member of this organization' }, + ]); + } if (!opts.grant.catalog.includes(String(data.position))) { throw validationFailure(`No position named '${data.position}'`, [ { field: 'position', code: 'reference_not_found', message: 'names no position' }, @@ -198,8 +217,40 @@ function makeHarness(opts: { const sendInviteSms = vi.fn(async () => {}); const noteMustChangePasswordIssued = vi.fn(); + // [#34535] better-auth's `addMember`: refuses past the organization's member + // cap with the vendor's code, else writes the membership. + const addMember = vi.fn(async ({ body }: any) => { + const cap = opts.multiOrg?.memberCap; + const count = tables.sys_member.filter((m) => m.organization_id === body.organizationId).length; + if (cap !== undefined && count >= cap) { + throw { statusCode: 403, body: { code: 'ORGANIZATION_MEMBERSHIP_LIMIT_REACHED', message: 'Organization membership limit reached' } }; + } + tables.sys_member.push({ organization_id: body.organizationId, user_id: body.userId, role: body.role }); + return { id: `mem-${tables.sys_member.length}`, ...body }; + }); + // [#34535] A unit of work that really undoes: a throw restores every table. + const outcomes: string[] = []; + const runAtomically = vi.fn(async (work: () => Promise): Promise => { + const before = Object.fromEntries(Object.entries(tables).map(([k, rows]) => [k, rows.map((r) => ({ ...r }))])); + try { + const result = await work(); + outcomes.push('committed'); + return result; + } catch (error) { + for (const k of Object.keys(tables)) tables[k] = before[k] ?? []; + outcomes.push('rolled back'); + throw error; + } + }); + const callerActiveOrganizationId = vi.fn(async () => opts.multiOrg?.callerActiveOrg ?? null); + const multiOrgSeam = opts.multiOrg && opts.multiOrg.withSeam !== false; + const deps: IdentityImportDeps = { - getAuthApi: async () => ({ createUser, requestPasswordReset }), + getAuthApi: async () => ({ + createUser, + requestPasswordReset, + ...(opts.multiOrg && opts.multiOrg.addMember !== false ? { addMember } : {}), + }), getAuthContext: async () => ({ password: { config: { minPasswordLength: 8, maxPasswordLength: 128 } } }), getDataEngine: () => ({ find, update, insert }), phoneNumberEnabled: () => opts.phoneEnabled ?? false, @@ -208,19 +259,28 @@ function makeHarness(opts: { sendInviteSms, noteMustChangePasswordIssued, logger: { warn }, - ...(opts.grant + ...(opts.grant || multiOrgSeam ? { createGrant: { resolveActorContext: async () => (opts.grant === 'no-context' ? undefined : ADMIN_CONTEXT), - runAtomically: async (work: () => Promise) => work(), + runAtomically: multiOrgSeam ? runAtomically : async (work: () => Promise) => work(), }, } : {}), + ...(opts.multiOrg + ? { + getTenancy: () => ({ defaultOrgId: async () => null, isolationActive: true }), + getCallerActiveOrganizationId: callerActiveOrganizationId, + } + : {}), }; return { deps, tables, snapshotsAtCreate, createUser, requestPasswordReset, find, update, insert, warn, + addMember, runAtomically, outcomes, callerActiveOrganizationId, sendInviteSms, + membersOf: (organizationId: string) => + tables.sys_member.filter((m) => m.organization_id === organizationId).map((m) => m.user_id), failUserReadsFrom: () => { readsFail = true; }, userBy: (email: string) => tables.sys_user.find((u) => u.email === email), }; @@ -904,3 +964,190 @@ describe('import-users positions column — assigned in a second pass, as Setup expect(positionInserts(h.insert)).toHaveLength(0); }); }); + +describe("import-users in multi-org mode: each row joins the administrator's current organization (#34535)", () => { + const ORG = 'org_current'; + const CATALOG = { catalog: ['sales_rep', 'area_manager'] }; + /** The administrator, already a member of the current organization. */ + const ADMIN_MEMBER = { organization_id: ORG, user_id: 'usr_admin', role: 'owner' }; + + it('every created row joins the current organization as member, in its own unit of work, and its positions then validate', async () => { + const h = makeHarness({ grant: CATALOG, seedMembers: [ADMIN_MEMBER], multiOrg: { callerActiveOrg: ORG } }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + rows: [ + { email: 'rep@x.co', name: 'Rep', positions: 'sales_rep' }, + { email: 'boss@x.co', name: 'Boss', positions: 'area_manager' }, + ], + }), ACTOR); + + expect(res.status).toBe(200); + const data = payload(res); + expect(data.summary.created).toBe(2); + expect(data.summary.errors).toBe(0); + const rep = h.userBy('rep@x.co')!; + const boss = h.userBy('boss@x.co')!; + expect(h.addMember.mock.calls.map(([arg]: any[]) => arg)).toEqual([ + { body: { userId: rep.id, role: 'member', organizationId: ORG } }, + { body: { userId: boss.id, role: 'member', organizationId: ORG } }, + ]); + expect(h.outcomes).toEqual(['committed', 'committed']); + expect(h.membersOf(ORG)).toEqual(['usr_admin', rep.id, boss.id]); + // The positions pass judges membership: a member-less user is refused there. + expect(data.summary.positions).toEqual({ assigned: 2, alreadyAssigned: 0, unresolved: 0, refused: 0 }); + expect(data.rows[0].positions).toEqual([{ position: 'sales_rep', outcome: 'assigned' }]); + expect(data.rows[0].error).toBeUndefined(); + const audit = h.tables.sys_audit_log.find((r) => r.action === 'import')!; + expect(JSON.parse(audit.metadata)).toMatchObject({ organizationId: ORG }); + }); + + it('a row whose join is refused creates no account and gets no invitation; the other rows go on', async () => { + const h = makeHarness({ seedMembers: [ADMIN_MEMBER], multiOrg: { callerActiveOrg: ORG, memberCap: 3 } }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'invite', + format: 'json', + rows: [ + { email: 'one@x.co', name: 'One' }, + { email: 'two@x.co', name: 'Two' }, + { email: 'three@x.co', name: 'Three' }, + ], + }), ACTOR); + + expect(res.status).toBe(200); + const data = payload(res); + expect(data.summary.created).toBe(2); + expect(data.summary.errors).toBe(1); + expect(data.rows[2]).toMatchObject({ row: 3, ok: false, action: 'failed', code: 'ORGANIZATION_MEMBERSHIP_LIMIT_REACHED' }); + expect(data.rows[2].error).toContain('could not be added to the organization, so no user was created'); + expect(data.rows[2].id).toBeUndefined(); + // Rolled back: the account the refused row wrote is gone, and no membership was left for it. + expect(h.outcomes).toEqual(['committed', 'committed', 'rolled back']); + expect(h.createUser).toHaveBeenCalledTimes(3); + expect(h.userBy('three@x.co')).toBeUndefined(); + expect(h.membersOf(ORG)).toEqual(['usr_admin', h.userBy('one@x.co')!.id, h.userBy('two@x.co')!.id]); + // Invitations only for the rows that landed. + expect(h.requestPasswordReset.mock.calls.map(([arg]: any[]) => arg.body.email)).toEqual(['one@x.co', 'two@x.co']); + expect(data.summary.delivery).toEqual({ emailInvite: 2, smsInvite: 0, temporary: 0 }); + }); + + it('a refused row under the temporary policy is handed no password', async () => { + const h = makeHarness({ seedMembers: [ADMIN_MEMBER], multiOrg: { callerActiveOrg: ORG, memberCap: 2 } }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'temporary', + format: 'json', + rows: [{ email: 'in@x.co', name: 'In' }, { email: 'out@x.co', name: 'Out' }], + }), ACTOR); + + const data = payload(res); + expect(data.rows[0]).toMatchObject({ ok: true, action: 'created' }); + expect(typeof data.rows[0].temporaryPassword).toBe('string'); + expect(data.rows[1]).toMatchObject({ ok: false, action: 'failed', code: 'ORGANIZATION_MEMBERSHIP_LIMIT_REACHED' }); + expect(data.rows[1].temporaryPassword).toBeUndefined(); + expect(data.summary.delivery).toEqual({ emailInvite: 0, smsInvite: 0, temporary: 1 }); + expect(h.userBy('out@x.co')).toBeUndefined(); + }); + + for (const dryRun of [false, true]) { + it(`no current organization: the whole import is refused 400 NO_ACTIVE_ORGANIZATION, create-user's code and sentence${dryRun ? ' (dry run too)' : ''}`, async () => { + const h = makeHarness({ multiOrg: { callerActiveOrg: null } }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + dryRun, + rows: [{ email: 'a@x.co', name: 'A' }], + }), ACTOR); + + expect(res.status).toBe(400); + expect(res.body.error?.code).toBe('NO_ACTIVE_ORGANIZATION'); + const single = await settleCurrentOrganizationJoin({ ...h.deps, createGrant: h.deps.createGrant } as any); + expect(single && 'status' in single ? single.body.error : undefined).toEqual(res.body.error); + expect(h.createUser).not.toHaveBeenCalled(); + expect(h.tables.sys_user).toHaveLength(0); + }); + } + + it('a host with no unit of work, or no organization plugin, is refused 501 before any account exists', async () => { + for (const multiOrg of [ + { callerActiveOrg: ORG, withSeam: false }, + { callerActiveOrg: ORG, addMember: false }, + ]) { + const h = makeHarness({ multiOrg }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', rows: [{ email: 'a@x.co', name: 'A' }], + }), ACTOR); + expect(res.status).toBe(501); + expect(res.body.error?.code).toBe('NOT_IMPLEMENTED'); + expect(h.createUser).not.toHaveBeenCalled(); + } + }); + + it('a dry run with a current organization joins nothing', async () => { + const h = makeHarness({ multiOrg: { callerActiveOrg: ORG } }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', dryRun: true, rows: [{ email: 'a@x.co', name: 'A' }], + }), ACTOR); + expect(res.status).toBe(200); + expect(h.addMember).not.toHaveBeenCalled(); + expect(h.createUser).not.toHaveBeenCalled(); + }); + + it('upsert: a matched existing user joins too; one already a member is not added twice', async () => { + const h = makeHarness({ + seedUsers: [{ id: 'u-out', email: 'out@x.co', name: 'Out' }, { id: 'u-in', email: 'in@x.co', name: 'In' }], + seedMembers: [ADMIN_MEMBER, { organization_id: ORG, user_id: 'u-in', role: 'member' }], + multiOrg: { callerActiveOrg: ORG }, + }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + mode: 'upsert', + format: 'json', + rows: [{ email: 'out@x.co', name: 'Out Renamed' }, { email: 'in@x.co', name: 'In' }], + }), ACTOR); + + expect(res.status).toBe(200); + const data = payload(res); + expect(data.summary.updated).toBe(2); + expect(data.summary.errors).toBe(0); + expect(h.addMember.mock.calls.map(([arg]: any[]) => arg.body.userId)).toEqual(['u-out']); + expect(h.membersOf(ORG)).toEqual(['usr_admin', 'u-in', 'u-out']); + expect(h.userBy('out@x.co')!.name).toBe('Out Renamed'); + }); + + it('upsert: a matched user whose join is refused fails its row, and its profile update rolls back with it', async () => { + const h = makeHarness({ + seedUsers: [{ id: 'u-out', email: 'out@x.co', name: 'Out' }], + seedMembers: [ADMIN_MEMBER], + multiOrg: { callerActiveOrg: ORG, memberCap: 1 }, + }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + mode: 'upsert', + format: 'json', + rows: [{ email: 'out@x.co', name: 'Out Renamed' }], + }), ACTOR); + + const data = payload(res); + expect(data.summary.updated).toBe(0); + expect(data.summary.errors).toBe(1); + expect(data.rows[0]).toMatchObject({ ok: false, action: 'failed', code: 'ORGANIZATION_MEMBERSHIP_LIMIT_REACHED' }); + // An existing user: the sentence names the join only, never "no user was created". + expect(data.rows[0].error).toContain('could not be added to the organization'); + expect(data.rows[0].error).not.toContain('no user was created'); + expect(h.outcomes).toEqual(['rolled back']); + expect(h.userBy('out@x.co')!.name).toBe('Out'); + }); + + it('CONTROL single-org (or a degraded wall): the current organization is never read, nothing joins, the import is unchanged', async () => { + const h = makeHarness({ multiOrg: { callerActiveOrg: ORG } }); + h.deps.getTenancy = () => ({ defaultOrgId: async () => 'org_default', isolationActive: false }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', rows: [{ email: 'a@x.co', name: 'A' }], + }), ACTOR); + expect(res.status).toBe(200); + expect(payload(res).summary.created).toBe(1); + expect(h.callerActiveOrganizationId).not.toHaveBeenCalled(); + expect(h.addMember).not.toHaveBeenCalled(); + expect(h.runAtomically).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugins/plugin-auth/src/admin-import-users.ts b/packages/plugins/plugin-auth/src/admin-import-users.ts index 14e1ed54e29..134eb7f0c69 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users.ts @@ -143,6 +143,33 @@ * ⛔ no `rows[].code`, for {@link noteManagerFailure}'s reason. The import * only ADDS assignments: ⛔ it never removes a position a user holds. * - **The pass does not run on `dryRun`**, for the manager pass's reason. + * + * ## Current organization — each row joins it, as create-user's user does + * + * Maintainer ruling on #34535 (option B): in multi-org mode every row's user + * joins the importing administrator's CURRENT organization under create-user's + * own rule (ADR-0093 D3 amendment), read through the one settlement and the one + * join both doors import (`settleCurrentOrganizationJoin`, + * `joinCurrentOrganization`) — ⛔ never a copy. + * + * - **Settled before any row is written**, dry run included: an administrator + * with no current organization is refused whole, `400 + * NO_ACTIVE_ORGANIZATION`, and a host that cannot run the join inside an + * account's unit of work `501 NOT_IMPLEMENTED` — create-user's codes and + * sentences, with nothing created. + * - **One unit of work per row.** A created row's account and its membership + * are written in one `runAtomically`, so a refused join (the organization's + * member cap, say) rolls that row's account back: the row fails with the + * vendor's code, carries no temporary password and is sent no invitation + * (both are recorded only once the unit committed, and the invitations go + * out after `runImport`). The other rows go on. + * - **A matched existing user joins too** (upsert): its profile update and its + * join are one unit of work, so a refused join fails the row and leaves the + * profile as it was. A user already in the organization is not added twice. + * - **Single-org mode is unchanged**: no join here, the reconciler binds the + * default organization as before. + * - **The join does not run on `dryRun`**: nothing is written, so the vendor's + * refusals cannot be asked. */ import type { @@ -158,9 +185,14 @@ import { normalizePhoneNumber, isLikelyEmail, mapAuthApiError, + joinCurrentOrganization, + settleCurrentOrganizationJoin, + CreationRefused, type AdminActor, type AdminCreateGrantSeam, + type AdminUserEndpointDeps, type AuthContextLike, + type CurrentOrganizationJoin, type EndpointResult, } from './admin-user-endpoints.js'; import { readNameList } from './name-list-cell.js'; @@ -272,6 +304,20 @@ export interface IdentityImportDeps { * the users are still created; a request that names none never reads it. */ createGrant?: AdminCreateGrantSeam; + /** + * ADR-0093 D3 amendment — the tenancy service, read for its + * `isolationActive` (the predicate behind `features.multiOrgEnabled`): in + * multi-org mode each row's user joins the administrator's current + * organization (see "Current organization" in the header). Absent ⇒ not + * multi-org ⇒ no join, as for create-user. + */ + getTenancy?: AdminUserEndpointDeps['getTenancy']; + /** + * The CALLING administrator's current (active) organization, read from their + * session, or `null` when they have none — create-user's reader. Absent ⇒ no + * join. + */ + getCallerActiveOrganizationId?(): Promise; /** `error` receives, once, a failure answered with the generic message (`mapAuthApiError`). */ logger?: { warn(msg: string): void; error?(message: string, error?: Error): void }; } @@ -774,6 +820,42 @@ export async function runAdminImportUsers( return mapAuthApiError(error, 'import-users failed', deps.logger); } + // ADR-0093 D3 amendment (ruling on #34535, option B) — the multi-org join of + // the administrator's current organization, settled before any row is + // written, by create-user's own settlement: no current organization ⇒ the + // whole import is refused, as one creation is. + const settled = await settleCurrentOrganizationJoin({ ...deps, getAuthApi: async () => authApi }); + if (settled && 'status' in settled) return settled; + const join: CurrentOrganizationJoin | undefined = settled; + const joinDeps = { getDataEngine: () => engine, ...(deps.logger ? { logger: deps.logger } : {}) }; + /** + * Run one row's write and, in multi-org mode, its join as ONE unit of work. + * A refused join throws out of the unit, which rolls the row's write back, + * and is rethrown as the row's error: the vendor's code, the sentence that + * says what did not happen. + */ + const inRowUnit = async ( + account: 'created' | 'existing', + write: () => Promise, + userIdOf: (written: T) => string, + ): Promise => { + if (!join) return write(); + try { + return await join.seam.runAtomically(async () => { + const written = await write(); + await joinCurrentOrganization(joinDeps, join.addMember, userIdOf(written), join.organizationId, account); + return written; + }); + } catch (error) { + if (!(error instanceof CreationRefused)) throw error; + const refusal = error.result.body.error; + throw Object.assign(new Error(refusal?.message ?? error.message), { + code: refusal?.code ?? 'INTERNAL_ERROR', + status: error.result.status, + }); + } + }; + // [#33113] What the position assignments need, read once per request. A // host that cannot judge a grant, or a caller whose own access does not // resolve, does NOT refuse the import: the users land exactly as they did @@ -880,18 +962,25 @@ export async function runAdminImportUsers( // set-initial-password / the reset flow, which creates it on demand. const password = plan.kind === 'temporary' ? generateTemporaryPassword(temporaryLength) : undefined; - const created = await authApi.createUser({ - body: { - email, - name, - ...(password ? { password } : {}), - ...(role ? { role } : {}), - ...(phone ? { data: { phoneNumber: phone } } : {}), - }, - }); - const id = created?.user?.id != null ? String(created.user.id) : undefined; - if (!id) throw Object.assign(new Error('better-auth returned no user id'), { code: 'CREATE_FAILED' }); + // The account and, in multi-org mode, its membership: one unit of work, + // so a refused join leaves no account behind (see "Current organization"). + const id = await inRowUnit('created', async () => { + const created = await authApi.createUser({ + body: { + email, + name, + ...(password ? { password } : {}), + ...(role ? { role } : {}), + ...(phone ? { data: { phoneNumber: phone } } : {}), + }, + }); + const userId = created?.user?.id != null ? String(created.user.id) : undefined; + if (!userId) throw Object.assign(new Error('better-auth returned no user id'), { code: 'CREATE_FAILED' }); + return userId; + }, (userId) => userId); + // Recorded only once the row's unit committed: a row whose join was + // refused carries no temporary password and is sent no invitation. if (plan.kind === 'temporary') { temporaryPasswords.set(id, password as string); try { @@ -908,14 +997,21 @@ export async function runAdminImportUsers( }, // Upsert updates touch PROFILE fields only — never email, never anything - // credential- or system-managed. An empty filtered patch is a no-op. + // credential- or system-managed. An empty filtered patch writes nothing. + // In multi-org mode the matched user joins the current organization in the + // same unit of work as its update (see "Current organization"). async updateData(args) { const patch: Record = {}; for (const [k, v] of Object.entries(args?.data ?? {})) { if (UPDATE_ALLOWED_FIELDS.has(k) && v !== undefined && v !== null && v !== '') patch[k] = v; } - if (Object.keys(patch).length === 0) return { id: args.id }; - await engine.update('sys_user', { id: args.id, ...patch }, { context: SYSTEM_CTX } as any); + const id = String(args.id); + await inRowUnit('existing', async () => { + if (Object.keys(patch).length > 0) { + await engine.update('sys_user', { id: args.id, ...patch }, { context: SYSTEM_CTX } as any); + } + return id; + }, (userId) => userId); return { id: args.id }; }, }; @@ -1260,6 +1356,8 @@ export async function runAdminImportUsers( manager: managerLinks, // [#33113] And the position assignments. positions: positionLinks, + // [#34535] The organization a multi-org run joined its rows to. + ...(join ? { organizationId: join.organizationId } : {}), }), }, { context: SYSTEM_CTX } as any); } catch (e) { diff --git a/packages/plugins/plugin-auth/src/admin-user-endpoints.ts b/packages/plugins/plugin-auth/src/admin-user-endpoints.ts index 56c2f76fe13..2f58f3b8cd8 100644 --- a/packages/plugins/plugin-auth/src/admin-user-endpoints.ts +++ b/packages/plugins/plugin-auth/src/admin-user-endpoints.ts @@ -790,42 +790,8 @@ export async function runAdminCreateUser( // the join runs in the account's own unit of work, so an administrator with // no current organization, or a host that cannot run the join, is refused // with nothing created — never handed a member-less account. - let join: - | { seam: AdminCreateGrantSeam; addMember: AddMemberCapableApi['addMember']; organizationId: string } - | undefined; - if (multiOrgCreationJoinsCurrentOrganization(deps)) { - const organizationId = await deps.getCallerActiveOrganizationId!(); - if (typeof organizationId !== 'string' || organizationId.length === 0) { - return { - status: 400, - body: { - success: false, - error: { - code: 'NO_ACTIVE_ORGANIZATION', - message: - 'You are not working in an organization, so no user was created. ' - + 'Switch to the organization the new user belongs to, then create them there.', - }, - }, - }; - } - const seam = deps.createGrant; - const authApi = (await deps.getAuthApi()) as Partial; - if (!seam || typeof authApi.addMember !== 'function') { - return { - status: 501, - body: { - success: false, - error: { - code: 'NOT_IMPLEMENTED', - message: - 'This server cannot add a new user to your organization while creating them, so no user was created.', - }, - }, - }; - } - join = { seam, addMember: authApi.addMember.bind(authApi), organizationId }; - } + const join = await settleCurrentOrganizationJoin(deps); + if (join && 'status' in join) return join; // [#25338] Everything the grant needs is settled BEFORE the account exists, // so a host that cannot judge the grant refuses with nothing created. @@ -1024,6 +990,15 @@ export async function joinCurrentOrganization( addMember: AddMemberCapableApi['addMember'], userId: string, organizationId: string, + /** + * Whose membership this is. `'created'` (the default): an account this unit + * of work just created, so the refusal says no user was created and a + * membership found already there was written during the creation. + * `'existing'`: an account that was there before — `import-users` matching a + * CSV row to a user — so the refusal names only the join, and a membership + * already there is reported as not created by this call. + */ + account: 'created' | 'existing' = 'created', ): Promise<{ organizationId: string; membershipCreated: boolean }> { const engine = deps.getDataEngine(); if (engine?.find) { @@ -1032,21 +1007,24 @@ export async function joinCurrentOrganization( { where: { organization_id: organizationId, user_id: userId }, limit: 1 }, { context: SYSTEM_CTX }, ); - if (Array.isArray(existing) && existing.length > 0) return { organizationId, membershipCreated: true }; + if (Array.isArray(existing) && existing.length > 0) { + return { organizationId, membershipCreated: account === 'created' }; + } } try { await addMember({ body: { userId, role: 'member', organizationId } }); } catch (error) { const refused = mapAuthApiError(error, 'organization/add-member failed', deps.logger); + const lead = account === 'created' + ? 'The user could not be added to the organization, so no user was created' + : 'The user could not be added to the organization'; throw new CreationRefused({ status: refused.status, body: { success: false, error: { code: refused.body.error?.code ?? 'INTERNAL_ERROR', - message: `The user could not be added to the organization, so no user was created: ${ - refused.body.error?.message ?? 'organization/add-member failed' - }`, + message: `${lead}: ${refused.body.error?.message ?? 'organization/add-member failed'}`, }, }, }); @@ -1054,6 +1032,64 @@ export async function joinCurrentOrganization( return { organizationId, membershipCreated: true }; } +/** What a multi-org creation settled before any account exists: its unit of work, the vendor's add, the organization. */ +export interface CurrentOrganizationJoin { + seam: AdminCreateGrantSeam; + addMember: AddMemberCapableApi['addMember']; + organizationId: string; +} + +/** + * Settle, before any account exists, the multi-org join of the administrator's + * current organization (ADR-0093 D3 amendment) — the one settlement both doors + * that create local accounts read: `create-user` for one user and + * `import-users` for each row of a file. + * + * Answers `undefined` when this creation joins nothing (single-org, a degraded + * wall, or a host that wires no way to read the caller's current + * organization — see {@link multiOrgCreationJoinsCurrentOrganization}); the + * refusal to answer when the administrator has no current organization + * (`400 NO_ACTIVE_ORGANIZATION`) or the host cannot run the join inside the + * account's unit of work (`501 NOT_IMPLEMENTED`), so nothing is created; or + * the join to run. + */ +export async function settleCurrentOrganizationJoin( + deps: Pick, +): Promise { + if (!multiOrgCreationJoinsCurrentOrganization(deps)) return undefined; + const organizationId = await deps.getCallerActiveOrganizationId!(); + if (typeof organizationId !== 'string' || organizationId.length === 0) { + return { + status: 400, + body: { + success: false, + error: { + code: 'NO_ACTIVE_ORGANIZATION', + message: + 'You are not working in an organization, so no user was created. ' + + 'Switch to the organization the new user belongs to, then create them there.', + }, + }, + }; + } + const seam = deps.createGrant; + const authApi = (await deps.getAuthApi()) as Partial; + if (!seam || typeof authApi.addMember !== 'function') { + return { + status: 501, + body: { + success: false, + error: { + code: 'NOT_IMPLEMENTED', + message: + 'This server cannot add a new user to your organization while creating them, so no user was created.', + }, + }, + }; + } + return { seam, addMember: authApi.addMember.bind(authApi), organizationId }; +} + /** * Whether this creation joins the administrator's current organization: multi-org * mode only (ADR-0093 D3 amendment), judged by `tenancy.isolationActive` — the diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 72c5bcfb5d0..8c5c687722f 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -5183,6 +5183,17 @@ export class AuthPlugin implements Plugin { consoleResetPasswordUrl: () => this.authManager!.getConsoleUrl('/reset-password'), noteMustChangePasswordIssued: () => this.authManager!.noteMustChangePasswordIssued(), createGrant: createGrantFor(c), + // ADR-0093 D3 amendment (ruling on #34535) — in multi-org mode each + // imported row joins the administrator's current organization, read + // as create-user reads it. + getTenancy: () => this.tenancy ?? undefined, + getCallerActiveOrganizationId: async () => { + const authApi: any = await this.authManager!.getApi(); + const session = (await authApi.getSession(inProcessSessionReadInput(c.req.raw.headers))) as + | { session?: { activeOrganizationId?: string | null } } + | null; + return session?.session?.activeOrganizationId ?? null; + }, logger: ctx.logger, }, c.req.raw, From d63d6b7672c44fa571f27fc44b26f65fa6fee3dd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:00:40 +0000 Subject: [PATCH 2/5] test(dogfood): import-users joins the current organization and rolls a refused row back on the real engine Claude-Session: https://claude.ai/code/session_01ADHkmQ6fcQhYhhjvBoSuKn Co-authored-by: Claude --- ...ate-user-organization-join.dogfood.test.ts | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/packages/qa/dogfood/test/create-user-organization-join.dogfood.test.ts b/packages/qa/dogfood/test/create-user-organization-join.dogfood.test.ts index 0f60f1b3a3b..7284d4faaa5 100644 --- a/packages/qa/dogfood/test/create-user-organization-join.dogfood.test.ts +++ b/packages/qa/dogfood/test/create-user-organization-join.dogfood.test.ts @@ -18,6 +18,18 @@ * J2 no current organization: refused, and no user is created — never a * member-less account. * + * Import Users follows the same rule, row by row (ruling on #34535, option B): + * + * I1 every imported row joins the administrator's current organization; + * a row the organization's member cap refuses is rolled back in the real + * engine transaction — no account, no temporary password — and the other + * rows land. + * I2 no current organization: the whole import is refused, and no user is + * created. + * + * The member cap is `OS_ORG_MEMBERSHIP_LIMIT`, read when better-auth's + * organization plugin is built, so it is set before the boot. + * * Harness: the admin identity routes 501 unless better-auth's `admin` plugin * is on; `OS_SCIM_ENABLED` is the one env knob that reaches it (see * `admin-identity-audit-trail.dogfood.test.ts`). The posture is a real, @@ -44,10 +56,16 @@ describe("Create User in multi-org mode joins the administrator's current organi /** The administrator's own current organization. */ let adminOrgId: string; let priorScim: string | undefined; + let priorMemberCap: string | undefined; + /** I1's organization: the administrator (owner) plus two imported members fill its cap. */ + let importOrgId: string; + const MEMBER_CAP = 3; beforeAll(async () => { priorScim = process.env.OS_SCIM_ENABLED; process.env.OS_SCIM_ENABLED = 'true'; + priorMemberCap = process.env.OS_ORG_MEMBERSHIP_LIMIT; + process.env.OS_ORG_MEMBERSHIP_LIMIT = String(MEMBER_CAP); stack = await bootStack(crmStack as never, { multiTenant: 'posture-only' }); adminToken = await stack.signIn(); // the seeded dev admin (platform admin) ql = await stack.kernel.getServiceAsync('objectql'); @@ -64,12 +82,20 @@ describe("Create User in multi-org mode joins the administrator's current organi }); expect(home.status, `admin org create: ${await home.clone().text()}`).toBe(200); adminOrgId = ((await home.json()) as { id: string }).id; + + const importHome = await stack.apiAs(adminToken, 'POST', '/auth/organization/create', { + name: 'Import Home', slug: 'import-home-create-user', + }); + expect(importHome.status, `import org create: ${await importHome.clone().text()}`).toBe(200); + importOrgId = ((await importHome.json()) as { id: string }).id; }, 180_000); afterAll(async () => { await stack?.stop?.(); if (priorScim === undefined) delete process.env.OS_SCIM_ENABLED; else process.env.OS_SCIM_ENABLED = priorScim; + if (priorMemberCap === undefined) delete process.env.OS_ORG_MEMBERSHIP_LIMIT; + else process.env.OS_ORG_MEMBERSHIP_LIMIT = priorMemberCap; }); async function setActive(organizationId: string | null): Promise { @@ -119,4 +145,44 @@ describe("Create User in multi-org mode joins the administrator's current organi expect((await res.json()).error.code).toBe('NO_ACTIVE_ORGANIZATION'); expect(await findRows(ql, 'sys_user', { email })).toHaveLength(0); }, 120_000); + + it("I1 import: each row joins the administrator's current organization; a row the member cap refuses is rolled back", async () => { + await setActive(importOrgId); + const emails = ['one.import-org@example.com', 'two.import-org@example.com', 'three.import-org@example.com']; + const res = await stack.apiAs(adminToken, 'POST', '/auth/admin/import-users', { + format: 'json', + passwordPolicy: 'temporary', + rows: emails.map((email, i) => ({ email, name: `Import ${i + 1}` })), + }); + expect(res.status, await res.clone().text()).toBe(200); + const { summary, rows } = (await res.json()).data; + expect(summary.created).toBe(2); + expect(summary.errors).toBe(1); + + for (const [i, email] of emails.slice(0, 2).entries()) { + expect(rows[i]).toMatchObject({ ok: true, action: 'created' }); + const members = await findRows(ql, 'sys_member', { user_id: String(rows[i].id) }); + expect(members.map((m) => [m.organization_id, m.role]), email).toEqual([[importOrgId, 'member']]); + } + // The third row would exceed the cap: refused, and the real transaction took its account back. + expect(rows[2]).toMatchObject({ ok: false, action: 'failed' }); + expect(rows[2].error).toContain('no user was created'); + expect(rows[2].temporaryPassword).toBeUndefined(); + expect(await findRows(ql, 'sys_user', { email: emails[2] })).toHaveLength(0); + expect(await findRows(ql, 'sys_member', { organization_id: importOrgId })).toHaveLength(MEMBER_CAP); + }, 120_000); + + it('I2 import with no current organization: the whole import is refused, and no user is created', async () => { + await setActive(null); + const email = 'orphan.import-org@example.com'; + const res = await stack.apiAs(adminToken, 'POST', '/auth/admin/import-users', { + format: 'json', + passwordPolicy: 'temporary', + rows: [{ email, name: 'Orphan' }], + }); + const text = await res.clone().text(); + expect(res.status, text).toBe(400); + expect((await res.json()).error.code).toBe('NO_ACTIVE_ORGANIZATION'); + expect(await findRows(ql, 'sys_user', { email })).toHaveLength(0); + }, 120_000); }); From 69deee9c83cfb746d0032c7fbf5539bd92b81ca6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:07:58 +0000 Subject: [PATCH 3/5] docs(auth): import-users joins the current organization; changeset Claude-Session: https://claude.ai/code/session_01ADHkmQ6fcQhYhhjvBoSuKn Co-authored-by: Claude --- ...34535-import-users-current-organization.md | 21 +++++++++++++++++++ content/docs/permissions/authentication.mdx | 13 ++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 .changeset/34535-import-users-current-organization.md diff --git a/.changeset/34535-import-users-current-organization.md b/.changeset/34535-import-users-current-organization.md new file mode 100644 index 00000000000..7d0baba468a --- /dev/null +++ b/.changeset/34535-import-users-current-organization.md @@ -0,0 +1,21 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: in multi-org mode `POST /api/v1/auth/admin/import-users` joins each row's user to the importing administrator's current organization, under create-user's rule + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for an administrator importing users under a walled posture (`group` / `isolated`, `features.multiOrgEnabled`). Single-org deployments, and a degraded wall, do not move. The import now follows create-user's rule (ADR-0093 D3 amendment): every row's user joins the administrator's current organization as `member`, in the same unit of work as its account. Four answers move: + +- FROM: an administrator with no current organization got `200` and every row's user was created, in no organization. TO: the whole import is refused `400 NO_ACTIVE_ORGANIZATION` (create-user's code and sentence) and no user is created. A `dryRun` is refused the same way. +- FROM: a server that cannot run the join inside the account's unit of work (no unit of work wired, or better-auth's organization plugin off) imported every row. TO: the whole import is refused `501 NOT_IMPLEMENTED`, as create-user is, and no user is created. +- FROM: a row whose organization would refuse the member (its membership limit) was created anyway, in no organization. TO: that row fails with the refusal's code (for example `ORGANIZATION_MEMBERSHIP_LIMIT_REACHED`), its account is rolled back, and it gets no temporary password and no invitation. The other rows still land. +- FROM: on `mode: 'upsert'`, a row matching an existing user updated its profile and touched no membership. TO: the matched user joins the current organization too, and a refused join fails the row with its profile update rolled back. A user already in the organization is not added twice. + +The fix for a caller: switch to the organization the people belong to before importing them. A row refused for the membership limit imports once the limit is raised (`OS_ORG_MEMBERSHIP_LIMIT`). + +Because the imported users are now members of the current organization, a `positions` column on a multi-org import is judged against that organization's membership and assigns, where it was refused on every row before. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 255c4228308..4f53325aee6 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1292,6 +1292,19 @@ every row through better-auth so the accounts are login-capable: cannot assign positions during an import, or `PERMISSION_DENIED` when your own access cannot be resolved. A dry run never assigns positions, and reports `summary.positions` as zeros. +- **Which organization the rows join** follows [Create a User](#create-a-user): + under a walled posture (`group` / `isolated`) every imported user joins your + **current** organization as `member`, each row in the same step as its + account, so the `positions` column validates against that organization. A row + the organization refuses (its membership limit, say) is failed on its row + with that refusal's code, and **that user is not created**: no account, no + temporary password, no invitation. The other rows still land. A row that + matches an existing user on `upsert` joins too; if the join is refused, the + row fails and its profile update is not applied. With no current + organization the whole import is refused with `400 NO_ACTIVE_ORGANIZATION` + and no user is created — a dry run included, so the preview tells you before + you import. Switch to the organization the people belong to first. Under the + `single` posture nothing changes: users join the default organization. - Synchronous only, at most 500 rows per request (password hashing is CPU-bound); split larger files into batches. Imports are not undoable. From 870ce22737a89ed3c0d7ddc1262da824819f6eba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:35:51 +0000 Subject: [PATCH 4/5] test(plugin-auth): type the multi-org harness's unit of work as the seam declares it Claude-Session: https://claude.ai/code/session_01ADHkmQ6fcQhYhhjvBoSuKn Co-authored-by: Claude --- .../plugin-auth/src/admin-import-users-manager-pass.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts b/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts index 834d7b238a0..9aa5e74cd81 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users-manager-pass.test.ts @@ -263,7 +263,9 @@ function makeHarness(opts: { ? { createGrant: { resolveActorContext: async () => (opts.grant === 'no-context' ? undefined : ADMIN_CONTEXT), - runAtomically: multiOrgSeam ? runAtomically : async (work: () => Promise) => work(), + runAtomically: multiOrgSeam + ? (runAtomically as unknown as (work: () => Promise) => Promise) + : async (work: () => Promise) => work(), }, } : {}), From 6bfc975899a1ed10282cfe967eb01ed3ad7e8ea8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:02:34 +0000 Subject: [PATCH 5/5] docs(auth): link the import's organization rule to the Create a User Directly heading Claude-Session: https://claude.ai/code/session_01ADHkmQ6fcQhYhhjvBoSuKn Co-authored-by: Claude --- content/docs/permissions/authentication.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 4f53325aee6..efab859b7ab 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1292,7 +1292,7 @@ every row through better-auth so the accounts are login-capable: cannot assign positions during an import, or `PERMISSION_DENIED` when your own access cannot be resolved. A dry run never assigns positions, and reports `summary.positions` as zeros. -- **Which organization the rows join** follows [Create a User](#create-a-user): +- **Which organization the rows join** follows [Create a User Directly](#create-a-user-directly): under a walled posture (`group` / `isolated`) every imported user joins your **current** organization as `member`, each row in the same step as its account, so the `positions` column validates against that organization. A row