Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/34535-import-users-current-organization.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. The moved answers are refusals of an admin HTTP request in multi-org mode: no stored row, layer, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->

**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.
13 changes: 13 additions & 0 deletions content/docs/permissions/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<string, Row[]> = {
sys_user: (opts.seedUsers ?? []).map((u) => ({ manager_id: null, source: 'env_native', ...u })),
Expand Down Expand Up @@ -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' },
Expand All @@ -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 <T,>(work: () => Promise<T>): Promise<T> => {
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,
Expand All @@ -208,19 +259,30 @@ function makeHarness(opts: {
sendInviteSms,
noteMustChangePasswordIssued,
logger: { warn },
...(opts.grant
...(opts.grant || multiOrgSeam
? {
createGrant: {
resolveActorContext: async () => (opts.grant === 'no-context' ? undefined : ADMIN_CONTEXT),
runAtomically: async <T>(work: () => Promise<T>) => work(),
runAtomically: multiOrgSeam
? (runAtomically as unknown as <T>(work: () => Promise<T>) => Promise<T>)
: async <T>(work: () => Promise<T>) => 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),
};
Expand Down Expand Up @@ -904,3 +966,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();
});
});
Loading
Loading