Skip to content

Commit babd5d4

Browse files
fix(plugin-auth): create-user reports the membership the store holds for the new account (#33587)
Fixes #33339 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:管理员创建用户接口(`POST /api/v1/auth/admin/create-user`)的返回值与审计行里的 `membershipCreated`,现在按"新账号在调用结束时是否已有组织成员关系"来回答,不再只看是不是本接口自己插入的那一行。 - 为什么改:单组织部署下,用户创建钩子(默认组织自动加入)先一步写入了 `sys_member`,接口自己的补绑看到已有行就让路,于是回答 `false`;数据库里明明有成员关系,管理员却被告知"创建了一个无组织的账号"。 - 风险与回滚:只改一个布尔字段在两种已有分支下的取值(让路 / 多组织下已存在的行),不改写入、不改权限;回滚即还原 `admin-user-endpoints.ts` 两行。仅邀请制(invite-only)仍回答 `false`、不写成员行,测试钉住未变。 - 先看:`packages/plugins/plugin-auth/src/admin-user-endpoints.ts`(`bindUserToSoleOrganization` 的返回行与 `joinCurrentOrganization` 的已存在分支);`packages/plugins/plugin-auth/src/admin-user-endpoints.test.ts`(两条改写的钉子)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/admin-user-endpoints.test.ts`,预期 100 条全绿,其中 "the bootstrap join already bound the new user" 一条断言返回与审计行都是 `true`。 - 需要你做的:无,席位落地。 ## What changes `membershipCreated`, in the create-user answer and in the `user.admin_created` audit row, now reports that the store holds a membership for the new account after the call, whichever writer made the row. The account did not exist before this call, so any membership it holds was created by this creation. - **Single-org posture** (`bindUserToSoleOrganization`): `membershipCreated` is `outcome === 'bound' || outcome === 'yielded'`. A `yielded` outcome is the reconciler reading an existing `sys_member` row for the user; on create-user that row is the `user.create.after` bootstrap join's, written moments earlier inside the same `createUser`. This is the same reading the sign-up hook already makes (`auth-manager-database-hooks.ts` treats `bound` and `yielded` alike as "the user holds a membership"). - **Multi-org posture** (`joinCurrentOrganization`): the card asked whether the same reasoning applies to the "membership already there" branch. It does: the user is brand-new, so a row in the administrator's current organization can only have been written during this creation (a host's `user.create.after` hook). It is still respected (no second `addMember`) and is now reported as `membershipCreated: true`. - **Unchanged, pinned as the control**: `invite-only` on the single-org posture answers `policy-skip`, no `organizationId`, `membershipCreated: false`, no `sys_member` insert (the existing pin, unedited). `failed`, `no-target-org` and `agent-account` still answer `false`. - The jsdoc that stated the old rule (`bindUserToSoleOrganization`, `AdminAuditDecisions.membershipCreated`, `joinCurrentOrganization`) now states the new one. **Why two existing pins were rewritten.** Both pinned `yielded`/already-there as `false` by seeding a `sys_member` row for `user-9` before the call. For a brand-new account that seed can only stand for a row written during the creation, which is exactly the reported defect, so the old expectation pinned the bug. - `is idempotent when a membership already exists` becomes `the bootstrap join already bound the new user: …`: the row is now written by the `createUser` double itself (the hook's bind, during the creation), and the pin asserts `true` in the answer AND the audit row, plus no second `sys_member` insert. - `a membership already there is respected: … membershipCreated false` becomes `a membership written during the creation is respected: … membershipCreated true …`, and gains the audit-row assertion. **Item 2 of the card (business-unit member rows "not stamped"): premise does not hold on `main` (4bba8b8), so nothing is changed for it.** - create-user writes no `sys_business_unit_member` row. `git grep "'sys_business_unit_member'" -- 'packages/**/src/**/*.ts' ':!**/*.test.ts'` at 4bba8b8 answers four hits: the object definition, the `sys_user` page's related list, the CLI ownership inventory and the platform-object name list. No runtime code inserts that object; plugin-auth only reads it (`external-membership.ts`). - The warning in the QA record is plugin-sharing's boot-time `warnOnEmptyUnitExpansion` (`sharing-rule-service.ts`): "active business-unit rule expands to NO recipients … membership rows written by seed replay or by an elevated system write are not organization-stamped". It names two causes worth checking first; it does not say rows were written. The rule it named, `showcase_share_new_inquiries_with_field_ops` (organization null), points at `bu_field_ops`, and the showcase seed writes the unit tree but, by design, no user-to-unit membership (`examples/app-showcase/src/data/seed/index.ts`: "Users can't be seeded … so user↔unit membership … stay runtime admin actions"). An empty expansion on a fresh showcase boot is the true answer, and the warning reports it correctly. ## Tests Run on the branch head before the PR opened (see Verification for the sha). - `pnpm --filter @objectstack/plugin-auth test`: Test Files 274 passed (274), Tests 5303 passed, 10 skipped (5313). - `pnpm --filter @objectstack/plugin-auth typecheck` (after building the plugin-auth closure): the first run went red only on `check:test-typecheck` reporting the debt SHRANK (`admin-user-endpoints.test.ts`: 6 errors, ledger 7, because the rewritten pin reads calls through `callsOf`); re-recorded with `gen:test-typecheck-debt` and committed. - `eslint --no-inline-config` on both changed source files: exit 0. Ablation (the fix committed first, each mutation through `scripts/ablation-replace.mjs`, which verified the anchor 1 to 0 on disk and restored to the HEAD blob `ee8f0ff9d8c6` with `git diff HEAD` empty; the test imports `./admin-user-endpoints.js` from `src`, so no build sits between): - `membershipCreated: result.outcome === 'bound',` (the old rule): `× the bootstrap join already bound the new user …`, Tests 1 failed, 99 passed. - `existing.length > 0) return { organizationId, membershipCreated: false };` (the old multi-org rule): `× a membership written during the creation is respected …`, Tests 1 failed, 99 passed. ## Acceptance notes - Pins per behaviour: bootstrap join then endpoint (answer and audit `true`), this call bound (`binds the created user to the sole organization`, unchanged, `true` in both), invite-only control (unchanged, `false`, no insert, no org lookup), multi-org already-there (`true` in both). - A `failed` outcome after a unique-key race (another writer landed the pair between the reconciler's re-check and its insert) still answers `false` although the store then holds the row. Reading the store back after every create would close it at the cost of one more read per create; not done here, noted only. ## Verification Local derived gate subset (`node scripts/pm/dispatch-gates.mjs --commands`, reconciled with `--ran`) and every CI family: see the report comment on #33339 for the readings and the head they were taken against. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d1NJYFGVi2FRztyBNo)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6446935 commit babd5d4

4 files changed

Lines changed: 63 additions & 21 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): `POST /api/v1/auth/admin/create-user` reports the membership the store holds for the new account
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`membershipCreated`, in the answer and in the `user.admin_created` audit row, now says the new account holds a membership after the call, whichever writer made the row during this creation. The account did not exist before the call, so any membership it holds was made by this creation.
11+
12+
- Single-org posture: the `user.create.after` membership reconciler (the default-organization join) binds the new user while the account is being created, so the endpoint's own reconcile finds the row and yields. That used to answer `membershipCreated: false` next to the `organizationId` while `sys_member` held the row; it now answers `true`. When the endpoint inserts the row itself it answers `true`, as before.
13+
- Multi-org (walled) posture: a row already in the administrator's current organization is still respected (no second add-member), and is now reported as `membershipCreated: true` for the same reason.
14+
- Unchanged: under `membershipPolicy: 'invite-only'` on the single-org posture the answer and audit row carry no `organizationId` and `membershipCreated: false`, and no `sys_member` row is written. A bind that fails, finds no target organization, or meets an AI service account still answers `false`.

‎packages/plugins/plugin-auth/src/admin-user-endpoints.test.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -451,21 +451,35 @@ describe('runAdminCreateUser', () => {
451451
expect(m.engineInsert.mock.calls.some((c) => c[0] === 'sys_member')).toBe(false);
452452
});
453453

454-
it('is idempotent when a membership already exists', async () => {
455-
const m = makeDepsWithOrgs({
456-
orgs: [{ id: 'org_only' }],
457-
members: [{ organization_id: 'org_only', user_id: 'user-9' }],
454+
// The `user.create.after` reconciler (the bootstrap join) binds the new user
455+
// DURING `createUser`, so the endpoint's own reconcile finds the row and
456+
// yields. The account did not exist before this call, so that row is this
457+
// creation's membership: the answer and the audit row both say `true`. It
458+
// used to answer `false` here while `sys_member` held the row, which read as
459+
// "a member-less account was created".
460+
it('the bootstrap join already bound the new user: no second insert, membershipCreated true in the answer and the audit row', async () => {
461+
const members: Array<{ organization_id: string; user_id: string }> = [];
462+
const m = makeDepsWithOrgs({ orgs: [{ id: 'org_only' }], members });
463+
const createUser = vi.fn(async ({ body }: any) => {
464+
members.push({ organization_id: 'org_only', user_id: 'user-9' }); // the hook's bind
465+
return { user: { id: 'user-9', email: body.email, name: body.name } };
458466
});
467+
m.deps.getAuthApi = async () => ({ createUser }) as any;
459468
const res = await runAdminCreateUser(
460469
m.deps,
461470
makeRequest({ email: 'a@b.co', generatePassword: true }),
462471
ACTOR,
463472
);
464473
expect(res.status).toBe(200);
474+
expect(createUser).toHaveBeenCalledTimes(1);
465475
const data = res.body.data as any;
466476
expect(data.organizationId).toBe('org_only');
467-
expect(data.membershipCreated).toBe(false);
468-
expect(m.engineInsert.mock.calls.some((c) => c[0] === 'sys_member')).toBe(false);
477+
expect(data.membershipCreated).toBe(true);
478+
// The endpoint wrote no second row: one membership, the hook's.
479+
expect(callsOf(m.engineInsert).some((c) => c[0] === 'sys_member')).toBe(false);
480+
const auditRow = callsOf(m.engineInsert).find((c) => c[0] === 'sys_audit_log')?.[1];
481+
expect(auditRow).toBeTruthy();
482+
expect(JSON.parse(auditRow.metadata)).toMatchObject({ organizationId: 'org_only', membershipCreated: true });
469483
});
470484

471485
it('does not fail account creation when the membership bind throws', async () => {
@@ -1521,15 +1535,20 @@ describe('create-user in multi-org mode: the new user joins the administrator\'s
15211535
expect(j.addMember).not.toHaveBeenCalled();
15221536
});
15231537

1524-
it('a membership already there is respected: no second addMember, membershipCreated false', async () => {
1538+
// The account is brand-new, so a row in the current organization was written
1539+
// during this creation (a host's `user.create.after` hook): it is reported as
1540+
// this creation's membership, the same rule the single-org bind answers by.
1541+
it('a membership written during the creation is respected: no second addMember, membershipCreated true in the answer and the audit row', async () => {
15251542
const j = makeJoinDeps({
15261543
callerActiveOrg: 'org_current',
15271544
members: [{ organization_id: 'org_current', user_id: 'user-9' }],
15281545
});
15291546
const res = await runAdminCreateUser(j.deps, makeRequest({ email: 'e@b.co', password: 'Explicit1!' }), ACTOR);
15301547
expect(res.status).toBe(200);
15311548
expect(j.addMember).not.toHaveBeenCalled();
1532-
expect(res.body.data).toMatchObject({ organizationId: 'org_current', membershipCreated: false });
1549+
expect(res.body.data).toMatchObject({ organizationId: 'org_current', membershipCreated: true });
1550+
const audit = callsOf(j.engineInsert).find(([object]) => object === 'sys_audit_log')![1];
1551+
expect(JSON.parse(audit.metadata)).toMatchObject({ organizationId: 'org_current', membershipCreated: true });
15331552
});
15341553

15351554
it('refused by the vendor: its status and code, the account rolls back, nothing is audited', async () => {

‎packages/plugins/plugin-auth/src/admin-user-endpoints.ts‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -466,13 +466,18 @@ async function stampMustChangePassword(
466466
* endpoint created the user" as a determinant — an admin-created account is
467467
* not an implicit invitation.
468468
*
469-
* Returns the shape the response/audit consumed pre-ADR-0093:
470-
* `membershipCreated` is true only when THIS call inserted the row (a `bound`
471-
* outcome); a `yielded` outcome (the hook or a race already bound it) reports
472-
* the org with `membershipCreated: false`. Under `invite-only` the reconciler
473-
* answers `policy-skip` before it looks at any org, so the caller reports no
474-
* organization and `membershipCreated: false` — the account is created, the
475-
* membership is not.
469+
* Returns what the response and the audit row report: `membershipCreated`
470+
* says the store holds a membership for the new account after this call,
471+
* whichever writer made the row. The account did not exist before this call,
472+
* so any membership it holds was created by this creation — a `bound` outcome
473+
* (this call inserted it) and a `yielded` outcome (the `user.create.after`
474+
* reconciler or a host hook bound it moments earlier, during the same
475+
* `createUser`) both answer `true`. Reporting `yielded` as `false` told the
476+
* administrator a member-less account had been made while `sys_member` held
477+
* the row. Under `invite-only` the reconciler answers `policy-skip` before it
478+
* looks at any org, so the caller reports no organization and
479+
* `membershipCreated: false` — the account is created, the membership is not.
480+
* A `failed` / `no-target-org` / `agent-account` outcome reports `false`.
476481
*/
477482
async function bindUserToSoleOrganization(
478483
deps: AdminUserEndpointDeps,
@@ -497,7 +502,7 @@ async function bindUserToSoleOrganization(
497502
});
498503
return {
499504
organizationId: result.organizationId ?? null,
500-
membershipCreated: result.outcome === 'bound',
505+
membershipCreated: result.outcome === 'bound' || result.outcome === 'yielded',
501506
};
502507
}
503508

@@ -512,7 +517,8 @@ async function bindUserToSoleOrganization(
512517
* - `placeholderEmail` — the admin created a phone-only identity, so the
513518
* address on the account is a generated placeholder. The decision, never
514519
* the address.
515-
* - `membershipCreated` — this call bound the membership (ADR-0093 D2).
520+
* - `membershipCreated` — the new account holds a membership after this call
521+
* (ADR-0093 D2), whichever writer made the row during this creation.
516522
* - `organizationId` — a reference to the organization bound to, a record of
517523
* its own; present only when one was resolved.
518524
*
@@ -967,8 +973,11 @@ class CreationRefused extends Error {
967973
* `membershipPolicy: 'invite-only'` admits (D1). The role is `member`, the D1
968974
* default: elevation stays the separate, audited `update-member-role`.
969975
*
970-
* A membership already there is respected and reported as
971-
* `membershipCreated: false`, exactly as the reconciler reports it.
976+
* A membership already there is respected (no second `addMember`) and
977+
* reported as `membershipCreated: true`: the account was created by this call,
978+
* so a row in the current organization was written during this creation (a
979+
* host's `user.create.after` hook, say) — the same rule the single-org bind
980+
* answers by.
972981
*/
973982
async function joinCurrentOrganization(
974983
deps: AdminUserEndpointDeps,
@@ -983,7 +992,7 @@ async function joinCurrentOrganization(
983992
{ where: { organization_id: organizationId, user_id: userId }, limit: 1 },
984993
{ context: SYSTEM_CTX },
985994
);
986-
if (Array.isArray(existing) && existing.length > 0) return { organizationId, membershipCreated: false };
995+
if (Array.isArray(existing) && existing.length > 0) return { organizationId, membershipCreated: true };
987996
}
988997
try {
989998
await addMember({ body: { userId, role: 'member', organizationId } });

‎packages/plugins/plugin-auth/test-typecheck-debt.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"TS18048: 'auditRow' is possibly 'undefined'.": 5,
1212
"TS2345: Argument of type 'null' is not assignable to parameter of type '…'.": 1,
1313
"TS2345: Argument of type '…' is not assignable to parameter of type '…'.": 1,
14-
"TS2493: Tuple type '…' of length '0' has no element at index '0'.": 7,
14+
"TS2493: Tuple type '…' of length '0' has no element at index '0'.": 6,
1515
"TS2493: Tuple type '…' of length '0' has no element at index '1'.": 4
1616
},
1717
"src/auth-manager.jwt-eddsa-fallback.test.ts": {

0 commit comments

Comments
 (0)