From a7970da68d642d0db4986d60915fd61cf4b56c7e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:33:28 +0000 Subject: [PATCH 1/8] feat(plugin-auth): import-users assigns positions in a second pass The positions column (position machine names, ;-separated, the spelling import-sso-users reads) is stripped before the write and assigned after runImport, each as a sys_user_position insert under the importing administrator's own execution context. An unresolved or refused position is a per-row outcome; the user is still created. Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- .../plugin-auth/src/admin-import-users.ts | 205 +++++++++++++++++- .../plugins/plugin-auth/src/auth-plugin.ts | 1 + .../plugins/plugin-auth/src/name-list-cell.ts | 29 +++ .../plugin-auth/src/pending-sso-users.ts | 15 +- 4 files changed, 235 insertions(+), 15 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/name-list-cell.ts diff --git a/packages/plugins/plugin-auth/src/admin-import-users.ts b/packages/plugins/plugin-auth/src/admin-import-users.ts index abff5e1c698..980fdb49c95 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users.ts @@ -104,6 +104,41 @@ * refusals cannot be evaluated against rows that do not exist. A dry run * reports `manager: { linked: 0, unresolved: 0, refused: 0 }` and says * nothing about the links — ⛔ rather than half-answering. + * + * ## `positions` — admitted, assigned in a SECOND pass (#33113) + * + * Maintainer ruling 6920428750: the import gains one column, the position, + * resolved in a second pass like `manager_id` and through the same checks as + * assigning a position in Setup; an unresolved or refused position is a + * per-row error and the user is still created. No permission-set column: under + * ADR-0090 a position carries its sets (`PositionSchema.permissionSets`). + * + * - **The cell.** `positions` holds position machine names, `;`-separated + * (or an array on a JSON row) — the spelling `admin/import-sso-users` + * already reads, through the one reader both doors import + * (`name-list-cell.ts`), so one CSV shape serves both doors. + * - **Same checks as Setup.** Each assignment is a `sys_user_position` + * insert through the data engine under the CALLING administrator's own + * execution context (`createGrant`, the seam create-user and the pending + * doors use) — ⛔ never `SYSTEM_CTX`, which every one of those checks + * stands down for. The position catalog refusal, the ADR-0090 D12 + * delegated-administration gate and the grant-holder membership refusal + * judge it exactly as they judge Setup's form. + * - **Settled before anything is written.** A request whose rows name a + * position on a host that cannot judge grants (no seam, no engine), or + * whose caller's own access cannot be resolved, is refused whole with + * nothing created — on a dry run too, so the preview does not promise what + * the write would refuse. + * - **Per row, per position.** `rows[].positions` lists each named position + * with its outcome: `assigned`, `already_assigned` (an upserted user who + * already holds it — a re-run batch is idempotent), `unresolved` (the + * catalog holds no position by that name: the refusal's + * `fields[].field === 'position'`, `reference_not_found`) or `refused` + * (any other refusal, its `code` carried). A cell that is not a list + * reads `'unreadable'`. The sentence rides `rows[].error` when it is free; + * ⛔ 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. */ import type { @@ -112,6 +147,7 @@ import type { ImportRowResult, } from '@objectstack/rest'; import { prepareImportRequest, runImport } from '@objectstack/rest'; +import { resolveThrownHttpError, validationFailureDetails } from '@objectstack/types'; import { generatePlaceholderEmail, isPlaceholderEmail } from './placeholder-email.js'; import { generateTemporaryPassword, @@ -119,9 +155,11 @@ import { isLikelyEmail, mapAuthApiError, type AdminActor, + type AdminCreateGrantSeam, type AuthContextLike, type EndpointResult, } from './admin-user-endpoints.js'; +import { readNameList } from './name-list-cell.js'; import { temporaryPasswordLength } from './temporary-password-length.js'; import { SYS_USER_IMPORT_UPDATE_FIELDS } from './sys-user-writable-fields.js'; import { readJsonRequestBody } from './request-json-body.js'; @@ -149,6 +187,13 @@ export const IMPORT_USERS_MAX_ROWS = 500; */ const MANAGER_COLUMN = 'manager_id'; +/** + * [#33113] The column a row names its positions in: position machine names, + * `;`-separated — the same column, spelled the same way, that + * `admin/import-sso-users` reads. + */ +const POSITIONS_COLUMN = 'positions'; + /** * Profile fields an upsert row may modify on an EXISTING user — shared with * the identity write guard's Tier-1 whitelist via sys-user-writable-fields.ts @@ -215,6 +260,14 @@ export interface IdentityImportDeps { */ consoleResetPasswordUrl?(): string; noteMustChangePasswordIssued(): void; + /** + * [#33113] What the `positions` column needs: the CALLING administrator's + * execution context, under which each `sys_user_position` insert is judged + * as Setup's form is (see {@link AdminCreateGrantSeam}). Absent ⇒ a request + * whose rows name a position is refused 501 with nothing created; a request + * that names none never reads it. + */ + createGrant?: AdminCreateGrantSeam; /** `error` receives, once, a failure answered with the generic message (`mapAuthApiError`). */ logger?: { warn(msg: string): void; error?(message: string, error?: Error): void }; } @@ -355,9 +408,26 @@ function identityKey(email?: string, phone?: string): string { */ export type ImportManagerOutcome = 'linked' | 'unresolved' | SetUserManagerRefusalReason; +/** + * [#33113] One named position's outcome on a row. + * + * - `assigned` — the `sys_user_position` row was written; + * - `already_assigned` — the user already held it (an upserted row), so + * nothing was written; + * - `unresolved` — the catalog holds no position by that name; + * - `refused` — any other refusal of the assignment; `code` is the refusal's + * own error code (e.g. `PERMISSION_DENIED`, or `VALIDATION_FAILED` for a + * user who is not a member of the assignment's organization). + */ +export interface ImportPositionOutcome { + position: string; + outcome: 'assigned' | 'already_assigned' | 'unresolved' | 'refused'; + code?: string; +} + /** * One row of the endpoint's `data.rows[]` — the generic import row plus the - * three things this identity surface adds to it. Named because callers read + * things this identity surface adds to it. Named because callers read * `manager` and `delivery` to decide what to show an operator, and an inline * type on one `const` is not something a Console can import. */ @@ -375,6 +445,12 @@ export interface IdentityImportRowResult extends ImportRowResult { * {@link MANAGER_COLUMN} cell was empty — ⛔ never "the link silently failed". */ manager?: ImportManagerOutcome; + /** + * [#33113] Present only on rows that named a position: one entry per named + * position, or `'unreadable'` when the {@link POSITIONS_COLUMN} cell was not + * a list of names. Absent means the cell was empty. + */ + positions?: ImportPositionOutcome[] | 'unreadable'; } /** @@ -503,6 +579,51 @@ async function resolveImportInviter( return { name, email }; } +/** + * [#33113] Assign one landed row's positions, each through the data engine + * under the administrator's own context, and answer one outcome per position. + * + * ⛔ The checks are NOT re-derived here: the catalog refusal, the delegated + * administration gate and the membership refusal run on the insert, and their + * answer is classified, never re-worded. Only an UPDATED row is read for an + * existing hold first — a row this batch just created holds nothing — so a + * re-run batch reports `already_assigned` rather than a duplicate refusal. + */ +async function assignRowPositions( + grant: { engine: IdentityImportEngine; context: Record }, + userId: string, + positions: string[], + existingUser: boolean, +): Promise { + const outcomes: ImportPositionOutcome[] = []; + for (const position of positions) { + if (existingUser) { + const held = await grant.engine.find('sys_user_position', { + where: { user_id: userId, position }, fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(held) && held.length > 0) { + outcomes.push({ position, outcome: 'already_assigned' }); + continue; + } + } + try { + await grant.engine.insert('sys_user_position', { user_id: userId, position }, { context: grant.context }); + outcomes.push({ position, outcome: 'assigned' }); + } catch (error) { + const fields = validationFailureDetails(error)?.fields ?? []; + const namesNoPosition = fields.some( + (f: any) => f?.field === 'position' && f?.code === 'reference_not_found', + ); + outcomes.push( + namesNoPosition + ? { position, outcome: 'unresolved' } + : { position, outcome: 'refused', code: resolveThrownHttpError(error, 500).code }, + ); + } + } + return outcomes; +} + export async function runAdminImportUsers( deps: IdentityImportDeps, request: Request, @@ -598,6 +719,9 @@ export async function runAdminImportUsers( // `undefined` in `managerWanted` means the row named nobody. const managerWanted: Array = new Array(prepared.rows.length); const rowIdentities: Array = new Array(prepared.rows.length); + // [#33113] The positions each row named, by ORIGINAL row number. `undefined` + // means the row named none; `'unreadable'` that the cell was not a list. + const positionsWanted: Array = new Array(prepared.rows.length); for (let i = 0; i < prepared.rows.length; i++) { const row = { ...prepared.rows[i] }; // [#18028] Read the manager cell and STRIP it before anything else sees the @@ -605,6 +729,10 @@ export async function runAdminImportUsers( // column an email address. The second pass owns it from here. const wanted = resolveManagerKey(row[MANAGER_COLUMN], phoneEnabled); delete row[MANAGER_COLUMN]; + // [#33113] The positions cell likewise: it is no `sys_user` field, and the + // second pass owns it. + const positionList = readNameList(row[POSITIONS_COLUMN], POSITIONS_COLUMN); + delete row[POSITIONS_COLUMN]; const identity = resolveRowIdentity(row, { policy, phoneEnabled, emailInviteOk, smsInviteOk }); if (identity.invalid) { results[i] = { row: i + 1, ok: false, action: 'failed', code: identity.invalid.code, error: identity.invalid.error }; @@ -616,6 +744,8 @@ export async function runAdminImportUsers( if (identity.phone) row.phone_number = identity.phone; else delete row.phone_number; if (identity.plan) planByKey.set(identityKey(identity.email, identity.phone), identity.plan); if (wanted !== 'absent') managerWanted[i] = wanted; + if (typeof positionList === 'string') positionsWanted[i] = 'unreadable'; + else if (positionList.length > 0) positionsWanted[i] = positionList; rowIdentities[i] = identity; validRows.push(row); validIndex.push(i); @@ -637,6 +767,33 @@ export async function runAdminImportUsers( return mapAuthApiError(error, 'import-users failed', deps.logger); } + // [#33113] Everything the position assignments need is settled BEFORE any + // row is written — create-user's order — so a host that cannot judge a + // grant, or a caller whose own access does not resolve, is refused with + // nothing created. On a dry run too: its preview must not promise a write + // the real run would refuse whole. + let grant: { engine: IdentityImportEngine; context: Record } | undefined; + if (positionsWanted.some((w) => Array.isArray(w))) { + const seam = deps.createGrant; + if (!seam) { + return fail( + 501, + 'NOT_IMPLEMENTED', + `This server cannot assign positions while importing users, so no one was imported. Import the file ` + + `without the ${POSITIONS_COLUMN} column, then assign positions on each user's record.`, + ); + } + const context = await seam.resolveActorContext(); + if (!context) { + return fail( + 403, + 'PERMISSION_DENIED', + 'Your own access could not be resolved, so the positions could not be judged and no one was imported.', + ); + } + grant = { engine, context }; + } + const protocol: ImportProtocolLike = { // [#22800] The declaration reader the parser was handed above. With it, // a lookup cell's target is asked its exposure for `list` before any @@ -790,6 +947,9 @@ export async function runAdminImportUsers( // reports the same three keys on a dry run — where the pass does not run — // as it does on a real one. const managerLinks = { linked: 0, unresolved: 0, refused: 0 }; + // [#33113] The position pass's split, counted per named position — reported + // on a dry run too, as zeros, like the manager split. + const positionLinks = { assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 0 }; if (!prepared.dryRun) { // [#23343] Resolved once, on the first email invitation, for the whole batch. let inviter: AccountInvitationMarker['inviter'] | undefined | null = null; @@ -1000,6 +1160,44 @@ export async function runAdminImportUsers( } } + // ── Second pass — the position assignments (#33113, ruling 6920428750) ── + // After `runImport`, beside the manager pass: every row of the batch exists, + // so each assignment names a real user id. + for (let i = 0; i < results.length; i++) { + const wanted = positionsWanted[i]; + if (wanted === undefined) continue; + const r = results[i]; + // A row that failed its own write has nothing to assign to; its failure + // is already reported. + if (!r || !r.id || (r.action !== 'created' && r.action !== 'updated')) continue; + if (wanted === 'unreadable') { + r.positions = 'unreadable'; + if (r.error === undefined) { + r.error = `The ${POSITIONS_COLUMN} cell is not a list of position names, so no position was assigned. ` + + 'This row landed; only its positions did not.'; + } + positionLinks.unresolved++; + continue; + } + // `grant` is set whenever any row names a position (settled above). + const outcomes = await assignRowPositions(grant!, r.id, wanted, r.action === 'updated'); + r.positions = outcomes; + const failed: string[] = []; + for (const o of outcomes) { + if (o.outcome === 'assigned') positionLinks.assigned++; + else if (o.outcome === 'already_assigned') positionLinks.alreadyAssigned++; + else { + if (o.outcome === 'unresolved') positionLinks.unresolved++; + else positionLinks.refused++; + failed.push(o.position); + } + } + if (failed.length > 0 && r.error === undefined) { + r.error = `${failed.length === 1 ? 'Position' : 'Positions'} ${failed.join(', ')} could not be assigned ` + + '(see rows[].positions for each reason). This row landed; only those assignments did not.'; + } + } + // Run-level audit. Best-effort; NO password material. // // Corrected rationale (#4940): this used to read "better-auth writes @@ -1045,6 +1243,8 @@ export async function runAdminImportUsers( // that linked nobody because every key was unresolved is the shape // an operator most needs to find later. manager: managerLinks, + // [#33113] And the position assignments. + positions: positionLinks, }), }, { context: SYSTEM_CTX } as any); } catch (e) { @@ -1105,6 +1305,9 @@ export async function runAdminImportUsers( // invitation IS folded in: the invitation was the row's ask, so the // row is not `ok` — see `errors` above. A manager link is not.) manager: managerLinks, + // [#33113] Per named position; like `manager`, failures on rows that + // landed are reported here and on the row, not folded into `errors`. + positions: positionLinks, mode, matchBy, }, diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index a85496e5671..76589f8819c 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -5180,6 +5180,7 @@ export class AuthPlugin implements Plugin { sendInviteSms: (phone: string) => this.authManager!.sendPhoneInviteSms(phone), consoleResetPasswordUrl: () => this.authManager!.getConsoleUrl('/reset-password'), noteMustChangePasswordIssued: () => this.authManager!.noteMustChangePasswordIssued(), + createGrant: createGrantFor(c), logger: ctx.logger, }, c.req.raw, diff --git a/packages/plugins/plugin-auth/src/name-list-cell.ts b/packages/plugins/plugin-auth/src/name-list-cell.ts new file mode 100644 index 00000000000..f2255fd5630 --- /dev/null +++ b/packages/plugins/plugin-auth/src/name-list-cell.ts @@ -0,0 +1,29 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * One reader for a list-of-machine-names cell, shared by the two identity + * import doors that take one: `admin/import-sso-users` (`positions`, + * `permission_sets`) and `admin/import-users` (`positions`). One reader, so a + * CSV that names positions reads the same through either door. + * + * Deliberately not re-exported from the package index: it is a parsing detail + * of those doors, not a public helper. + */ + +/** + * A list cell: an array of names, or one `;`-separated string. Empty entries + * and repeats are dropped. A string answer is the refusal sentence, naming + * the cell by `label`. + */ +export function readNameList(raw: unknown, label: string): string[] | string { + if (raw === undefined || raw === null || raw === '') return []; + const parts = typeof raw === 'string' ? raw.split(';') : Array.isArray(raw) ? raw : undefined; + if (!parts) return `${label} must be a list of machine names`; + const out: string[] = []; + for (const part of parts) { + if (typeof part !== 'string') return `${label} must be a list of machine names`; + const name = part.trim(); + if (name && !out.includes(name)) out.push(name); + } + return out; +} diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.ts b/packages/plugins/plugin-auth/src/pending-sso-users.ts index d2608bc280f..09363b7f12d 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-users.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-users.ts @@ -100,6 +100,7 @@ import { import { applyUserManagerLink, type SetUserManagerEngine } from './admin-set-user-manager.js'; import type { AddMemberCapableApi } from './organization-add-member.js'; import { readJsonRequestBody } from './request-json-body.js'; +import { readNameList } from './name-list-cell.js'; import { authSystemWriteContext } from './auth-actor-attribution.js'; import { isPendingSsoSource, @@ -187,20 +188,6 @@ const ADD_KEYS = new Set(['email', 'name', 'positions', 'permissionSets', 'manag const ADD_FIELD_NAMES = { positions: 'positions', permissionSets: 'permissionSets', manager: 'manager' } as const; const IMPORT_FIELD_NAMES = { positions: 'positions', permissionSets: 'permission_sets', manager: 'manager_id' } as const; -/** A list cell: an array of names, or one `;`-separated string. Empty entries are dropped. */ -function readNameList(raw: unknown, label: string): string[] | string { - if (raw === undefined || raw === null || raw === '') return []; - const parts = typeof raw === 'string' ? raw.split(';') : Array.isArray(raw) ? raw : undefined; - if (!parts) return `${label} must be a list of machine names`; - const out: string[] = []; - for (const part of parts) { - if (typeof part !== 'string') return `${label} must be a list of machine names`; - const name = part.trim(); - if (name && !out.includes(name)) out.push(name); - } - return out; -} - /** Read one person from the add body or an import row. A string answer is the refusal sentence. */ function readPerson( raw: Record, From 126848b37158e3a983e33cec7035740eb7ead8ee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:36:25 +0000 Subject: [PATCH 2/8] feat(plugin-auth): positions column help, docs and changeset The Users import wizard offers the positions target column with a hint in every locale pack; the authentication guide documents the column and its per-row outcomes. Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- .../33113-import-users-positions-column.md | 19 ++ content/docs/permissions/authentication.mdx | 14 + .../admin-import-users-manager-pass.test.ts | 245 +++++++++++++++++- .../src/views/IdentityImportPanels.tsx | 15 ++ ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + 15 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 .changeset/33113-import-users-positions-column.md diff --git a/.changeset/33113-import-users-positions-column.md b/.changeset/33113-import-users-positions-column.md new file mode 100644 index 00000000000..5dea1f4f0f3 --- /dev/null +++ b/.changeset/33113-import-users-positions-column.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-auth': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(plugin-auth): `POST /api/v1/auth/admin/import-users` takes a `positions` column, assigned in a second pass as Setup assigns a position + +Clause-②: yes (widening) +Metadata-protocol: none + +The user import gains one column, `positions`: position machine names, several separated by `;` (or an array on a JSON row) — the same column `admin/import-sso-users` reads. Nothing that worked before is refused: a file with no `positions` column imports exactly as before. + +- Each named position is assigned after every row of the batch has landed, as a `sys_user_position` grant written under the importing administrator's own execution context, so it passes the same checks as assigning a position in Setup (the position catalog, delegated administration, the holder's organization membership). +- A position that does not exist (`unresolved`) or whose assignment is refused (`refused`, with the refusal's `code`) is reported on its row, and the user is still created. `rows[].positions` lists each named position's outcome (`assigned`, `already_assigned`, `unresolved`, `refused`), a cell that is not a list reads `'unreadable'`, and `summary.positions` counts them. The import only adds positions; it never removes one. +- A file that names a position on a server that cannot judge the grant answers `501 NOT_IMPLEMENTED`, and one whose caller's own access does not resolve answers `403 PERMISSION_DENIED`, with nothing created, dry runs included. Dry runs do not assign. +- There is no permission-set column: a position carries its permission sets. + +`@object-ui/app-shell`: the Users import wizard offers a `positions` target column, and its options panel explains the column (`console.identityImport.positionsHint`, in every `@object-ui/i18n` pack). diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 92d4043c282..c44054fbdc5 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1269,6 +1269,20 @@ every row through better-auth so the accounts are login-capable: updates only touch profile fields (`name`, `image`, `phone_number`, `role`) — a re-imported file can never modify an existing user's email or reset their password. +- A `positions` column assigns positions: position machine names, several + separated by `;` (an array on a JSON row) — the same column + `import-sso-users` reads. Each is assigned after every row has landed, as a + `sys_user_position` grant written under the importing admin's own access, + so it passes the checks Setup applies when you assign a position there (the + position must exist, and you must be allowed to assign it). A position that does not exist or is refused is reported on + its row and the user is still created: `rows[].positions` lists each named + position with its outcome (`assigned`, `already_assigned`, `unresolved`, or + `refused` with the refusal's `code`), and `summary.positions` counts them. + The import only adds positions; it never removes one a user holds. Permission + sets come with the position (a position carries its sets); a direct grant + stays a Setup step. A file that names positions on a server that cannot + judge the grant is refused with nothing created (`501`), and dry runs do + not assign. - Synchronous only, at most 500 rows per request (password hashing is CPU-bound); split larger files into batches. Imports are not undoable. 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 1f2ed9d3605..85912c6b5a3 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 @@ -41,12 +41,15 @@ import { readFileSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { assertEngineUpdateDispatch } from '@objectstack/objectql'; +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'; const ACTOR: AdminActor = { id: 'usr_admin', email: 'admin@example.com' }; +/** [#33113] The administrator's own execution context, as the grant seam resolves it. */ +const ADMIN_CONTEXT = { userId: 'usr_admin', isSystem: false, positions: ['platform_admin'], permissions: [] }; const HERE = dirname(fileURLToPath(import.meta.url)); const IMPORT_USERS_SOURCE = readFileSync(resolve(HERE, 'admin-import-users.ts'), 'utf8'); @@ -103,11 +106,21 @@ function makeHarness(opts: { resetFails?: boolean; /** Make every `sys_user` READ throw, to drive the failed-lookup branch. */ failUserReads?: boolean; + /** + * [#33113] The grant seam for the `positions` column. An object wires it: + * `catalog` is the positions the security catalog holds (any other name is + * refused as the catalog refusal refuses it), `denied` the ones the caller + * may not assign. `'no-context'` wires a seam whose caller does not resolve. + * Absent ⇒ no seam. + */ + grant?: { catalog: string[]; denied?: string[] } | 'no-context'; + seedUserPositions?: Row[]; } = {}) { const tables: Record = { sys_user: (opts.seedUsers ?? []).map((u) => ({ manager_id: null, source: 'env_native', ...u })), sys_member: [...(opts.seedMembers ?? [])], sys_scim_subject: [...(opts.seedScimSubjects ?? [])], + sys_user_position: [...(opts.seedUserPositions ?? [])], sys_audit_log: [], }; @@ -163,7 +176,20 @@ function makeHarness(opts: { if (row) Object.assign(row, data); return row ?? null; }); - const insert = vi.fn(async (object: string, data: any) => { + const insert = vi.fn(async (object: string, data: any, options?: any) => { + // [#33113] A position assignment is judged as the security plugin judges + // 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') { + 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' }, + ]); + } + if (opts.grant.denied?.includes(String(data.position))) { + throw Object.assign(new Error(`You may not assign '${data.position}'`), { code: 'PERMISSION_DENIED', status: 403 }); + } + } (tables[object] ??= []).push({ ...data }); return {}; }); @@ -182,6 +208,14 @@ function makeHarness(opts: { sendInviteSms, noteMustChangePasswordIssued, logger: { warn }, + ...(opts.grant + ? { + createGrant: { + resolveActorContext: async () => (opts.grant === 'no-context' ? undefined : ADMIN_CONTEXT), + runAtomically: async (work: () => Promise) => work(), + }, + } + : {}), }; return { @@ -606,3 +640,212 @@ describe('import-users manager pass — the fences (#18028)', () => { expect(data.rows.every((r: Row) => r.manager === undefined)).toBe(true); }); }); + +/** [#33113] The `sys_user_position` inserts, in call order, with the context each was written under. */ +function positionInserts(insert: ReturnType): Array<{ data: Row; context: any; order: number }> { + const out: Array<{ data: Row; context: any; order: number }> = []; + insert.mock.calls.forEach(([object, data, options]: any[], i: number) => { + if (object === 'sys_user_position') out.push({ data, context: options?.context, order: insert.mock.invocationCallOrder[i] }); + }); + return out; +} + +describe('import-users positions column — assigned in a second pass, as Setup assigns (#33113)', () => { + const CATALOG = { catalog: ['sales_rep', 'area_manager', 'finance'], denied: ['finance'] }; + + it('assigns every named position, under the ADMINISTRATOR\'s context, after the last row is created', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + rows: [ + { email: 'rep@x.co', name: 'Rep', positions: 'sales_rep; area_manager' }, + { 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); + expect(data.summary.positions).toEqual({ assigned: 3, alreadyAssigned: 0, unresolved: 0, refused: 0 }); + expect(data.rows[0].positions).toEqual([ + { position: 'sales_rep', outcome: 'assigned' }, + { position: 'area_manager', outcome: 'assigned' }, + ]); + expect(data.rows[1].positions).toEqual([{ position: 'area_manager', outcome: 'assigned' }]); + expect(data.rows[0].error).toBeUndefined(); + + const rep = h.userBy('rep@x.co')!; + expect(h.tables.sys_user_position.filter((r) => r.user_id === rep.id).map((r) => r.position)) + .toEqual(['sales_rep', 'area_manager']); + + const writes = positionInserts(h.insert); + expect(writes).toHaveLength(3); + // ⛔ never SYSTEM_CTX: every check Setup's form passes through stands down for it. + for (const w of writes) expect(w.context).toBe(ADMIN_CONTEXT); + const createOrders = h.createUser.mock.invocationCallOrder; + for (const w of writes) expect(w.order).toBeGreaterThan(createOrders[createOrders.length - 1]); + }); + + it('reads the column from a CSV file, `;`-separated', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'csv', + csv: 'email,name,positions\nrep@x.co,Rep,sales_rep;area_manager\n', + }), ACTOR); + + expect(res.status).toBe(200); + expect(payload(res).rows[0].positions).toEqual([ + { position: 'sales_rep', outcome: 'assigned' }, + { position: 'area_manager', outcome: 'assigned' }, + ]); + }); + + it('an unresolved position is PER-ROW: the user lands, every other row lands', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + rows: [ + { email: 'typo@x.co', name: 'Typo', positions: 'sales_rpe;area_manager' }, + { email: 'ok@x.co', name: 'Ok', positions: 'sales_rep' }, + ], + }), ACTOR); + + expect(res.status).toBe(200); + const data = payload(res); + expect(data.summary.created).toBe(2); + expect(data.summary.errors).toBe(0); + expect(data.summary.positions).toEqual({ assigned: 2, alreadyAssigned: 0, unresolved: 1, refused: 0 }); + expect(data.rows[0].ok).toBe(true); + expect(data.rows[0].action).toBe('created'); + expect(data.rows[0].positions).toEqual([ + { position: 'sales_rpe', outcome: 'unresolved' }, + { position: 'area_manager', outcome: 'assigned' }, + ]); + expect(data.rows[0].error).toContain('sales_rpe'); + expect(data.rows[0].code).toBeUndefined(); + expect(h.userBy('typo@x.co')).toBeDefined(); + expect(data.rows[1].positions).toEqual([{ position: 'sales_rep', outcome: 'assigned' }]); + }); + + it('a REFUSED assignment carries the refusal\'s own code, and the user still lands', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + rows: [{ email: 'cfo@x.co', name: 'Cfo', positions: 'finance' }], + }), ACTOR); + + const data = payload(res); + expect(data.summary.created).toBe(1); + expect(data.summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 1 }); + expect(data.rows[0].positions).toEqual([{ position: 'finance', outcome: 'refused', code: 'PERMISSION_DENIED' }]); + expect(h.userBy('cfo@x.co')).toBeDefined(); + expect(h.tables.sys_user_position).toHaveLength(0); + }); + + it('an upserted user who already holds a position reports already_assigned and is not written twice', async () => { + const h = makeHarness({ + grant: CATALOG, + seedUsers: [{ id: 'u-old', email: 'rep@x.co', name: 'Rep' }], + seedUserPositions: [{ user_id: 'u-old', position: 'sales_rep' }], + }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + mode: 'upsert', + format: 'json', + rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep;area_manager' }], + }), ACTOR); + + const data = payload(res); + expect(data.rows[0].action).toBe('updated'); + expect(data.rows[0].positions).toEqual([ + { position: 'sales_rep', outcome: 'already_assigned' }, + { position: 'area_manager', outcome: 'assigned' }, + ]); + expect(data.summary.positions).toEqual({ assigned: 1, alreadyAssigned: 1, unresolved: 0, refused: 0 }); + expect(positionInserts(h.insert).map((w) => w.data.position)).toEqual(['area_manager']); + }); + + it('a cell that is not a list reads unreadable, and the user still lands', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + rows: [{ email: 'odd@x.co', name: 'Odd', positions: 42 }], + }), ACTOR); + + const data = payload(res); + expect(data.summary.created).toBe(1); + expect(data.rows[0].positions).toBe('unreadable'); + expect(data.rows[0].error).toContain('positions'); + expect(data.summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 1, refused: 0 }); + expect(positionInserts(h.insert)).toHaveLength(0); + }); + + it('the cell never reaches the identity write, and an empty cell is not a finding', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', + format: 'json', + rows: [{ email: 'rep@x.co', name: 'Rep', positions: '' }], + }), ACTOR); + + const body = h.createUser.mock.calls[0][0].body; + expect(Object.hasOwn(body, 'positions')).toBe(false); + expect(JSON.stringify(body)).not.toContain('positions'); + expect(payload(res).rows[0].positions).toBeUndefined(); + expect(payload(res).rows[0].error).toBeUndefined(); + }); + + it('a file naming no position needs no grant seam at all', async () => { + const h = makeHarness(); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', rows: [{ email: 'rep@x.co', name: 'Rep' }], + }), ACTOR); + + expect(res.status).toBe(200); + expect(payload(res).summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 0 }); + }); + + it('a host with no grant seam refuses a file that names positions, with nothing created — dry run too', async () => { + for (const dryRun of [false, true]) { + const h = makeHarness(); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', dryRun, + rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep' }], + }), ACTOR); + + expect(res.status).toBe(501); + expect((res.body as any).error.code).toBe('NOT_IMPLEMENTED'); + expect(h.createUser).not.toHaveBeenCalled(); + } + }); + + it('a caller whose own access does not resolve is refused 403, with nothing created', async () => { + const h = makeHarness({ grant: 'no-context' }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', + rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep' }], + }), ACTOR); + + expect(res.status).toBe(403); + expect((res.body as any).error.code).toBe('PERMISSION_DENIED'); + expect(h.createUser).not.toHaveBeenCalled(); + }); + + it('dryRun does not run the pass, and reports zeros', async () => { + const h = makeHarness({ grant: CATALOG }); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', dryRun: true, + rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep' }], + }), ACTOR); + + expect(res.status).toBe(200); + expect(payload(res).summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 0 }); + expect(positionInserts(h.insert)).toHaveLength(0); + }); +}); diff --git a/ui/packages/app-shell/src/views/IdentityImportPanels.tsx b/ui/packages/app-shell/src/views/IdentityImportPanels.tsx index 731fd830cb9..849f247b71e 100644 --- a/ui/packages/app-shell/src/views/IdentityImportPanels.tsx +++ b/ui/packages/app-shell/src/views/IdentityImportPanels.tsx @@ -39,6 +39,10 @@ const POLICY_FALLBACKS: Record {t(`console.identityImport.policyHint.${policy}`, POLICY_FALLBACKS[policy].hint)}

+ {/* objectstack#33113 — the `positions` column's help: what the cell + holds, and that a bad name costs its row the position, not the user. */} +

+ {t('console.identityImport.positionsHint', POSITIONS_HINT_FALLBACK)} +

); } @@ -135,6 +144,11 @@ export function IdentityImportResultExtra({ serverResult }: { serverResult?: Imp * or placeholder address is marked, as the endpoint refuses it with * `INVALID_EMAIL` (objectui#11913). * + * `positions` (objectstack#33113) is no `sys_user` field: the endpoint reads + * it — position machine names, `;`-separated — and assigns each one after + * the row lands, as Setup assigns a position. Its help is the options + * panel's `positionsHint`. + * * The flag is typed where it is written, against the wizard's own field type, * and the return type does not name it. `ObjectView` passes this list or * `importTargetFields`' list into the wizard's `fields` through one @@ -152,5 +166,6 @@ export function identityImportFields( { name: 'phone_number', label: label('phone_number', 'Phone Number'), type: 'text' }, { name: 'name', label: label('name', 'Name'), type: 'text' }, { name: 'role', label: label('role', 'Platform Role'), type: 'text' }, + { name: 'positions', label: 'Positions', type: 'text' }, ]; } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 007da4e9800..3ee5b701b90 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2132,6 +2132,7 @@ const ar = { }, passwordsNote: "كلمات مرور مؤقتة — تُعرض مرة واحدة ولا تُخزَّن أبدًا. احفظها الآن؛ وعلى كل مستخدم تغيير كلمته عند أول تسجيل دخول.", passwordsMore: "تم حذف إدخالات إضافية — استخدم التنزيل.", + positionsHint: "المناصب: اربط عمودًا بأسماء المناصب الآلية، ويُفصل بين عدة أسماء بـ \";\". يُسند كل منصب كما في Setup؛ والاسم غير الموجود أو الذي لا يحق لك إسناده يُبلَّغ عنه في صفه، ويُنشأ المستخدم رغم ذلك.", passwordsDownload: "تنزيل ملف CSV", }, ai: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 0da3d2d7d85..27ad0136360 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1917,6 +1917,7 @@ const de = { }, passwordsNote: "Temporäre Passwörter — einmalig angezeigt, nie gespeichert. Speichern Sie sie jetzt; jeder Benutzer muss seines bei der ersten Anmeldung ändern.", passwordsMore: "Weitere Einträge ausgelassen — bitte den Download verwenden.", + positionsHint: "Positionen: Ordnen Sie eine Spalte mit Maschinennamen von Positionen zu, mehrere getrennt durch „;“. Jede wird wie in Setup zugewiesen; ein Name, den es nicht gibt oder den Sie nicht zuweisen dürfen, wird in seiner Zeile gemeldet, und der Benutzer wird trotzdem angelegt.", passwordsDownload: "CSV herunterladen", }, ai: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 15daec999e1..68202500248 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3049,6 +3049,7 @@ const en = { }, passwordsNote: 'Temporary passwords — shown once, never stored. Save them now; each user must change theirs at first sign-in.', passwordsMore: 'More entries omitted — use the download.', + positionsHint: 'Positions: map a column of position machine names, several separated by ";". Each is assigned as in Setup; a name that does not exist, or that you may not assign, is reported on its row, and the user is still created.', passwordsDownload: 'Download CSV', }, // objectstack#30205 — the ban dialog's account of a user's open work (app-shell UserAssignedWorkPanel). diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ff476a2c8ec..dec33023015 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1973,6 +1973,7 @@ const es = { }, passwordsNote: "Contraseñas temporales — se muestran una sola vez y nunca se almacenan. Guárdelas ahora; cada usuario debe cambiar la suya en el primer inicio de sesión.", passwordsMore: "Se han omitido más entradas — use la descarga.", + positionsHint: "Puestos: asigne una columna con nombres de máquina de puestos, varios separados por «;». Cada uno se asigna como en Setup; un nombre que no existe o que usted no puede asignar se informa en su fila, y el usuario se crea igualmente.", passwordsDownload: "Descargar CSV", }, ai: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 003d8b53719..5b50460a140 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1969,6 +1969,7 @@ const fr = { }, passwordsNote: "Mots de passe temporaires — affichés une seule fois, jamais stockés. Enregistrez-les maintenant ; chaque utilisateur doit changer le sien à la première connexion.", passwordsMore: "Autres entrées omises — utilisez le téléchargement.", + positionsHint: "Postes : associez une colonne de noms machine de postes, plusieurs séparés par « ; ». Chacun est attribué comme dans Setup ; un nom inexistant, ou que vous ne pouvez pas attribuer, est signalé sur sa ligne, et l’utilisateur est tout de même créé.", passwordsDownload: "Télécharger le CSV", }, ai: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index aad6fb25401..bea7440fa63 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1917,6 +1917,7 @@ const ja = { }, passwordsNote: "仮パスワード — 一度だけ表示され、保存されません。今すぐ保存してください。各ユーザーは初回サインイン時に変更する必要があります。", passwordsMore: "以降のエントリは省略されました — ダウンロードをご利用ください。", + positionsHint: "役職:役職のマシン名の列をマッピングできます(複数は「;」で区切ります)。各役職は Setup と同じルールで割り当てられます。存在しない役職や割り当て権限のない役職はその行にエラーとして表示され、ユーザーは作成されます。", passwordsDownload: "CSV をダウンロード", }, ai: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index e504e89df1c..28563c8c244 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1917,6 +1917,7 @@ const ko = { }, passwordsNote: "임시 비밀번호 — 한 번만 표시되며 저장되지 않습니다. 지금 저장하세요. 각 사용자는 첫 로그인 시 변경해야 합니다.", passwordsMore: "이후 항목은 생략되었습니다 — 다운로드를 이용하세요.", + positionsHint: "직위: 직위 머신 이름 열을 매핑할 수 있습니다(여러 개는 \";\"로 구분). 각 직위는 Setup과 같은 규칙으로 할당됩니다. 존재하지 않거나 할당 권한이 없는 직위는 해당 행에 오류로 표시되며, 사용자는 그대로 생성됩니다.", passwordsDownload: "CSV 다운로드", }, ai: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index b61b56adde2..bad14deec97 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1968,6 +1968,7 @@ const pt = { }, passwordsNote: "Senhas temporárias — exibidas uma única vez, nunca armazenadas. Salve-as agora; cada usuário deve trocar a sua no primeiro acesso.", passwordsMore: "Demais entradas omitidas — use o download.", + positionsHint: "Cargos: mapeie uma coluna com nomes de máquina de cargos, vários separados por \";\". Cada um é atribuído como no Setup; um nome que não existe, ou que você não pode atribuir, é informado na linha, e o usuário é criado mesmo assim.", passwordsDownload: "Baixar CSV", }, ai: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index aeb2009d763..bd3bc0fb53a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2029,6 +2029,7 @@ const ru = { }, passwordsNote: "Временные пароли — показываются один раз и нигде не сохраняются. Сохраните их сейчас; каждый пользователь должен сменить свой при первом входе.", passwordsMore: "Остальные записи опущены — воспользуйтесь загрузкой файла.", + positionsHint: "Должности: сопоставьте столбец с машинными именами должностей, несколько — через «;». Каждая назначается так же, как в Setup; имя, которого нет или которое вы не можете назначить, указывается в его строке, а пользователь всё равно создаётся.", passwordsDownload: "Скачать CSV", }, ai: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index cda63c6907c..fc0996628de 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2559,6 +2559,7 @@ const zh = { }, passwordsNote: '临时密码——仅显示一次,不会被保存。请立即保存;用户首次登录时必须修改。', passwordsMore: '更多条目已省略——请使用下载。', + positionsHint: '岗位:可映射一列岗位机器名,多个用“;”分隔。每个岗位按 Setup 中指派岗位的同样规则分配;不存在或你无权指派的岗位会在该行报错,用户照常创建。', passwordsDownload: '下载 CSV', }, // objectstack#30205 — the ban dialog's account of a user's open work (app-shell UserAssignedWorkPanel). diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 8d8b94df912..63cedb75103 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2559,6 +2559,7 @@ const zhHant = { }, passwordsNote: '臨時密碼——僅顯示一次,不會被儲存。請立即儲存;使用者首次登入時必須修改。', passwordsMore: '更多條目已省略——請使用下載。', + positionsHint: '崗位:可映射一欄崗位機器名,多個用「;」分隔。每個崗位按 Setup 中指派崗位的同樣規則分配;不存在或你無權指派的崗位會在該列報錯,使用者照常建立。', passwordsDownload: '下載 CSV', }, // objectstack#30205 — the ban dialog's account of a user's open work (app-shell UserAssignedWorkPanel). From e1657e42132e6fc9406514fa627b96ebec0c8d31 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:42:49 +0000 Subject: [PATCH 3/8] test(app-shell): the positions column and its hint in the user import Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- .../identityImportFields.emailRule-11913.test.tsx | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/__tests__/identityImportFields.emailRule-11913.test.tsx b/ui/packages/app-shell/src/views/__tests__/identityImportFields.emailRule-11913.test.tsx index f2419347dc2..7179c9b15fc 100644 --- a/ui/packages/app-shell/src/views/__tests__/identityImportFields.emailRule-11913.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/identityImportFields.emailRule-11913.test.tsx @@ -27,7 +27,7 @@ import '@testing-library/jest-dom'; import React from 'react'; import { ImportWizard } from '@object-ui/plugin-grid'; -import { identityImportFields } from '../IdentityImportPanels'; +import { identityImportFields, IdentityImportOptions } from '../IdentityImportPanels'; /** Paste TSV into the upload step via the wizard's window-level handler. */ function pasteRows(text: string) { @@ -69,3 +69,15 @@ describe('identityImportFields: the email column is checked by the identity rule expect(button).toHaveTextContent('Import 1 Row'); }); }); + +describe('identityImportFields: the positions column (objectstack#33113)', () => { + it('offers `positions`, the column the endpoint assigns positions from', () => { + const positions = identityImportFields(undefined).find((f) => f.name === 'positions'); + expect(positions).toMatchObject({ type: 'text' }); + }); + + it('the options panel explains the column', () => { + render( {}} />); + expect(screen.getByTestId('identity-import-positions-hint')).toHaveTextContent(/position machine names.*";"/); + }); +}); From c371730ca8a4ed3c5d16a760562c57dbdbd80666 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:57:05 +0000 Subject: [PATCH 4/8] docs(audit): re-measure the tenant-audit census for the import's position grant The new sys_user_position insert in admin-import-users is one more engine write call site; the generated tables and the prose figures move by one. Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- .../docs/permissions/tenant-audit-census.mdx | 38 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 19 +++++----- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 793cd0dfda7..26ca0364604 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -93,7 +93,7 @@ what moved this page's population from 225 to 227; nothing about the two sites changed, only whether this instrument could see them. **The expensive failure direction is a keyword.** Sites whose receiver the author -typed `any` have no type to read, and there are 66 of them — just over a fifth +typed `any` have no type to read, and there are 67 of them — just over a fifth of the population, concentrated in exactly the seed and bootstrap paths this control exists for. Scoring an unreadable receiver as "not an engine" would have dropped every one of them silently, with a clean exit and a smaller number that @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **59 of the 321 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 322 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **321** | +| 175 write call sites | quoted in the merged changeset | **322** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **226 of 321** decidable, **95** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 181 decidably elevated, 0 decidably not, 128 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **227 of 322** decidable, **95** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 181 decidably elevated, 0 decidably not, 129 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -210,18 +210,18 @@ be stated is what this instrument counts, which is written above and re-runnable at any commit. Two structural facts do plausibly widen this reading against any hand or regex -one, and both are counted in the generated tables below: the 66 sites reached +one, and both are counted in the generated tables below: the 67 sites reached through an erased (`any`) receiver, and the 86 that name their object through a `const` rather than inline. An instrument that read either the way a person does would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -181 of 321 (56%) as decidably elevated, with 128 more whose elevation is a +181 of 322 (56%) as decidably elevated, with 129 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 321`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 322`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **32 further sites** have an options argument this @@ -233,28 +233,28 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **321** | -| …whose object name is statically decidable | 226 | +| write call sites on the application surface | **322** | +| …whose object name is statically decidable | 227 | | …whose object name is chosen at run time | 95 | -| …against an object with tenancy ENABLED | 219 | +| …against an object with tenancy ENABLED | 220 | | …against an object that declares tenancy off | 7 | -| threading a tenant context | 250 | +| threading a tenant context | 251 | | PROVABLY carrying none (options read, no context key) | **12** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | | threading a decidably ELEVATED (`isSystem`) context | 181 | | threading a context that is decidably NOT elevated | 0 | -| threading a context whose elevation is a run-time fact | 128 | +| threading a context whose elevation is a run-time fact | 129 | | how the instrument reached the site | count | | :--- | ---: | | receiver carried a readable engine type | 255 | -| receiver erased, placed by the object NAME | 56 | +| receiver erased, placed by the object NAME | 57 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | -| object name spelled inline | 140 | +| object name spelled inline | 141 | | object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | | object name is some other run-time expression | 85 | @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-15 at `2ab05f460`. +Measured on 2026-11-16 at `94cb58c3d`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1176 | -| engine-shaped types recognised | 141 | +| tracked non-test sources scanned | 1186 | +| engine-shaped types recognised | 142 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 311 | +| same-named calls subtracted as non-engine | 323 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index d9225ca889b..f70dc7b1180 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,19 +33,19 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 321 | -| Object name statically decidable | 226 | +| Write call sites | 322 | +| Object name statically decidable | 227 | | Object name chosen at run time | 95 | -| Against a tenancy-enabled object | 219 | +| Against a tenancy-enabled object | 220 | | Against an object declaring tenancy off | 7 | -| Threading a tenant context | 250 | +| Threading a tenant context | 251 | | Provably carrying none | 12 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | | Threading a decidably elevated context | 181 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 128 | +| Threading a context of undecidable elevation | 129 | ## Subtractions the census could NOT defend — enforced @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-15 at `2ab05f460`. +Measured on 2026-11-16 at `94cb58c3d`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1176 | -| engine-shaped types recognised | 141 | +| tracked non-test sources scanned | 1186 | +| engine-shaped types recognised | 142 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 311 | +| same-named calls subtracted as non-engine | 323 | ## Every site @@ -138,6 +138,7 @@ Measured on 2026-11-15 at `2ab05f460`. | `packages/plugins/plugin-audit/src/stored-metadata-body-migration.ts` | `update` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/admin-import-users.ts` | `insert` | `sys_audit_log` | enabled | options unreadable | 1 | | `packages/plugins/plugin-auth/src/admin-import-users.ts` | `update` | `sys_user` | enabled | options unreadable | 2 | +| `packages/plugins/plugin-auth/src/admin-import-users.ts` | `insert` | `sys_user_position` | enabled | context, elevation undecidable | 1 | | `packages/plugins/plugin-auth/src/admin-set-user-manager.ts` | `update` | `sys_user` | enabled | context, elevation undecidable | 1 | | `packages/plugins/plugin-auth/src/admin-user-endpoints.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/admin-user-endpoints.ts` | `update` | `sys_user` | enabled | elevated | 1 | From d3c32ee1cc975ea3ffa747f22a32deace0a95208 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:38:34 +0000 Subject: [PATCH 5/8] fix(i18n): generate the zh-Hant positions hint, and spell the de one without a quote pair Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- ui/packages/i18n/src/locales/de.ts | 2 +- ui/packages/i18n/src/locales/zh-Hant.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 27ad0136360..5d8fbc048c0 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1917,7 +1917,7 @@ const de = { }, passwordsNote: "Temporäre Passwörter — einmalig angezeigt, nie gespeichert. Speichern Sie sie jetzt; jeder Benutzer muss seines bei der ersten Anmeldung ändern.", passwordsMore: "Weitere Einträge ausgelassen — bitte den Download verwenden.", - positionsHint: "Positionen: Ordnen Sie eine Spalte mit Maschinennamen von Positionen zu, mehrere getrennt durch „;“. Jede wird wie in Setup zugewiesen; ein Name, den es nicht gibt oder den Sie nicht zuweisen dürfen, wird in seiner Zeile gemeldet, und der Benutzer wird trotzdem angelegt.", + positionsHint: "Positionen: Ordnen Sie eine Spalte mit Maschinennamen von Positionen zu, mehrere durch Semikolon (;) getrennt. Jede wird wie in Setup zugewiesen; ein Name, den es nicht gibt oder den Sie nicht zuweisen dürfen, wird in seiner Zeile gemeldet, und der Benutzer wird trotzdem angelegt.", passwordsDownload: "CSV herunterladen", }, ai: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 63cedb75103..ded4c1a2405 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2559,7 +2559,7 @@ const zhHant = { }, passwordsNote: '臨時密碼——僅顯示一次,不會被儲存。請立即儲存;使用者首次登入時必須修改。', passwordsMore: '更多條目已省略——請使用下載。', - positionsHint: '崗位:可映射一欄崗位機器名,多個用「;」分隔。每個崗位按 Setup 中指派崗位的同樣規則分配;不存在或你無權指派的崗位會在該列報錯,使用者照常建立。', + positionsHint: '崗位:可對映一列崗位機器名,多個用“;”分隔。每個崗位按 Setup 中指派崗位的同樣規則分配;不存在或你無權指派的崗位會在該行報錯,使用者照常建立。', passwordsDownload: '下載 CSV', }, // objectstack#30205 — the ban dialog's account of a user's open work (app-shell UserAssignedWorkPanel). From 5185e099d04d7e6e1a8dddf3e3491063477a8b52 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:51:47 +0000 Subject: [PATCH 6/8] docs(auth): the unreadable positions outcome is a string, and the 403 whole-file refusal Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- content/docs/permissions/authentication.mdx | 27 ++++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index c44054fbdc5..b1275018fb3 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1274,15 +1274,24 @@ every row through better-auth so the accounts are login-capable: `import-sso-users` reads. Each is assigned after every row has landed, as a `sys_user_position` grant written under the importing admin's own access, so it passes the checks Setup applies when you assign a position there (the - position must exist, and you must be allowed to assign it). A position that does not exist or is refused is reported on - its row and the user is still created: `rows[].positions` lists each named - position with its outcome (`assigned`, `already_assigned`, `unresolved`, or - `refused` with the refusal's `code`), and `summary.positions` counts them. - The import only adds positions; it never removes one a user holds. Permission - sets come with the position (a position carries its sets); a direct grant - stays a Setup step. A file that names positions on a server that cannot - judge the grant is refused with nothing created (`501`), and dry runs do - not assign. + position must exist, and you must be allowed to assign it). A position that + does not exist or is refused is reported on its row and the user is still + created: `rows[].positions` is an array with one entry per named position + and its outcome (`assigned`, `already_assigned`, `unresolved`, or `refused` + with the refusal's `code`), and `summary.positions` counts them. A cell that + is not a list of names (a number or an object on a JSON row) assigns + nothing, and that row's `rows[].positions` is the **string** + `'unreadable'`, not an array — check for it before reading the entries. It + counts once under `summary.positions.unresolved`, and the user is still + created. The import only adds positions; it never removes one a user holds. + Permission sets come with the position (a position carries its sets); a + direct grant stays a Setup step. +- A file that names positions is refused whole, with nothing created, when + its positions cannot be judged: `501 NOT_IMPLEMENTED` when the server + cannot assign positions during an import, and `403 PERMISSION_DENIED` when + your own access cannot be resolved. Both are decided before any row is + written, on a dry run too. A dry run never assigns positions, and reports + `summary.positions` as zeros. - Synchronous only, at most 500 rows per request (password hashing is CPU-bound); split larger files into batches. Imports are not undoable. From 4ed4e51c2541b9f4747daddc595d5f4b088ed3a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:35:49 +0000 Subject: [PATCH 7/8] fix(plugin-auth): a host that cannot judge the grant refuses the positions per row, not the import Before the positions column the same file answered 200 and created every user, so a whole-request 501 or 403 narrowed the door. Every named position is now reported refused on its row (NOT_IMPLEMENTED, PERMISSION_DENIED) and the users land as before. Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- .../admin-import-users-manager-pass.test.ts | 85 +++++++++++++++---- .../plugin-auth/src/admin-import-users.ts | 77 ++++++++++------- 2 files changed, 116 insertions(+), 46 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 85912c6b5a3..67221871964 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 @@ -811,30 +811,85 @@ describe('import-users positions column — assigned in a second pass, as Setup expect(payload(res).summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 0 }); }); - it('a host with no grant seam refuses a file that names positions, with nothing created — dry run too', async () => { - for (const dryRun of [false, true]) { - const h = makeHarness(); - const res = await runAdminImportUsers(h.deps, makeRequest({ - passwordPolicy: 'none', format: 'json', dryRun, - rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep' }], - }), ACTOR); - - expect(res.status).toBe(501); - expect((res.body as any).error.code).toBe('NOT_IMPLEMENTED'); - expect(h.createUser).not.toHaveBeenCalled(); - } + it('FROM control — a file naming positions on a host with no grant seam still answers 200 and creates every user', async () => { + // Measured on main before this column existed (PR #34531, Acceptance notes): the same file answered + // 200, created both users and dropped the cell. Anything less here would NARROW the door, so the + // users land exactly as they did, and only the positions are reported. + const h = makeHarness(); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', + rows: [ + { email: 'a@x.co', name: 'A', positions: 'sales_rep' }, + { email: 'b@x.co', name: 'B', positions: 'sales_rep;area_manager' }, + ], + }), ACTOR); + + expect(res.status).toBe(200); + const data = payload(res); + expect(data.summary.created).toBe(2); + expect(data.summary.errors).toBe(0); + expect(h.createUser).toHaveBeenCalledTimes(2); + expect(data.rows.map((r: any) => [r.ok, r.action])).toEqual([[true, 'created'], [true, 'created']]); }); - it('a caller whose own access does not resolve is refused 403, with nothing created', async () => { + it('a host with no grant seam reports every named position refused / NOT_IMPLEMENTED on its row', async () => { + const h = makeHarness(); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', + rows: [ + { email: 'a@x.co', name: 'A', positions: 'sales_rep' }, + { email: 'b@x.co', name: 'B', positions: 'sales_rep;area_manager' }, + { email: 'c@x.co', name: 'C' }, + ], + }), ACTOR); + + const data = payload(res); + expect(data.rows[0].positions).toEqual([{ position: 'sales_rep', outcome: 'refused', code: 'NOT_IMPLEMENTED' }]); + expect(data.rows[1].positions).toEqual([ + { position: 'sales_rep', outcome: 'refused', code: 'NOT_IMPLEMENTED' }, + { position: 'area_manager', outcome: 'refused', code: 'NOT_IMPLEMENTED' }, + ]); + expect(data.rows[0].error).toContain('cannot assign positions'); + expect(data.rows[0].code).toBeUndefined(); + expect(data.rows[2].positions).toBeUndefined(); + expect(data.rows[2].error).toBeUndefined(); + expect(data.summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 3 }); + expect(positionInserts(h.insert)).toHaveLength(0); + }); + + it('a caller whose own access does not resolve: every position refused / PERMISSION_DENIED, every user created', async () => { const h = makeHarness({ grant: 'no-context' }); const res = await runAdminImportUsers(h.deps, makeRequest({ passwordPolicy: 'none', format: 'json', + rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep;area_manager' }], + }), ACTOR); + + expect(res.status).toBe(200); + const data = payload(res); + expect(data.summary.created).toBe(1); + expect(data.summary.errors).toBe(0); + expect(h.userBy('rep@x.co')).toBeDefined(); + expect(data.rows[0].ok).toBe(true); + expect(data.rows[0].positions).toEqual([ + { position: 'sales_rep', outcome: 'refused', code: 'PERMISSION_DENIED' }, + { position: 'area_manager', outcome: 'refused', code: 'PERMISSION_DENIED' }, + ]); + expect(data.rows[0].error).toContain('could not be resolved'); + expect(data.summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 2 }); + expect(positionInserts(h.insert)).toHaveLength(0); + }); + + it('a dry run on a host with no grant seam answers as main did: 200, nothing written, no refusal', async () => { + const h = makeHarness(); + const res = await runAdminImportUsers(h.deps, makeRequest({ + passwordPolicy: 'none', format: 'json', dryRun: true, rows: [{ email: 'rep@x.co', name: 'Rep', positions: 'sales_rep' }], }), ACTOR); - expect(res.status).toBe(403); - expect((res.body as any).error.code).toBe('PERMISSION_DENIED'); + expect(res.status).toBe(200); expect(h.createUser).not.toHaveBeenCalled(); + expect(payload(res).rows[0].positions).toBeUndefined(); + expect(payload(res).summary.positions).toEqual({ assigned: 0, alreadyAssigned: 0, unresolved: 0, refused: 0 }); }); it('dryRun does not run the pass, and reports zeros', async () => { diff --git a/packages/plugins/plugin-auth/src/admin-import-users.ts b/packages/plugins/plugin-auth/src/admin-import-users.ts index 980fdb49c95..14e1ed54e29 100644 --- a/packages/plugins/plugin-auth/src/admin-import-users.ts +++ b/packages/plugins/plugin-auth/src/admin-import-users.ts @@ -124,11 +124,15 @@ * stands down for. The position catalog refusal, the ADR-0090 D12 * delegated-administration gate and the grant-holder membership refusal * judge it exactly as they judge Setup's form. - * - **Settled before anything is written.** A request whose rows name a - * position on a host that cannot judge grants (no seam, no engine), or - * whose caller's own access cannot be resolved, is refused whole with - * nothing created — on a dry run too, so the preview does not promise what - * the write would refuse. + * - **A host that cannot judge the grant costs the positions, never the + * users.** On a host with no `createGrant` seam, or for a caller whose own + * execution context does not resolve, every named position is reported + * `refused` on its row — code `NOT_IMPLEMENTED` or `PERMISSION_DENIED` + * respectively — and the users are created exactly as before this column + * existed. ⛔ Not a whole-request refusal: before this column, the same + * file answered `200` and created every user (the cell was dropped), so + * refusing it whole would NARROW what this door accepts; the ruling's own + * direction is "per-row error, the user is still created". * - **Per row, per position.** `rows[].positions` lists each named position * with its outcome: `assigned`, `already_assigned` (an upserted user who * already holds it — a re-run batch is idempotent), `unresolved` (the @@ -263,9 +267,9 @@ export interface IdentityImportDeps { /** * [#33113] What the `positions` column needs: the CALLING administrator's * execution context, under which each `sys_user_position` insert is judged - * as Setup's form is (see {@link AdminCreateGrantSeam}). Absent ⇒ a request - * whose rows name a position is refused 501 with nothing created; a request - * that names none never reads it. + * as Setup's form is (see {@link AdminCreateGrantSeam}). Absent ⇒ every + * named position is reported `refused` / `NOT_IMPLEMENTED` on its row and + * the users are still created; a request that names none never reads it. */ createGrant?: AdminCreateGrantSeam; /** `error` receives, once, a failure answered with the generic message (`mapAuthApiError`). */ @@ -417,7 +421,10 @@ export type ImportManagerOutcome = 'linked' | 'unresolved' | SetUserManagerRefus * - `unresolved` — the catalog holds no position by that name; * - `refused` — any other refusal of the assignment; `code` is the refusal's * own error code (e.g. `PERMISSION_DENIED`, or `VALIDATION_FAILED` for a - * user who is not a member of the assignment's organization). + * user who is not a member of the assignment's organization). Also every + * position of a request whose grants cannot be judged at all: + * `NOT_IMPLEMENTED` (the host wires no grant seam) or `PERMISSION_DENIED` + * (the caller's own access does not resolve). */ export interface ImportPositionOutcome { position: string; @@ -767,31 +774,32 @@ export async function runAdminImportUsers( return mapAuthApiError(error, 'import-users failed', deps.logger); } - // [#33113] Everything the position assignments need is settled BEFORE any - // row is written — create-user's order — so a host that cannot judge a - // grant, or a caller whose own access does not resolve, is refused with - // nothing created. On a dry run too: its preview must not promise a write - // the real run would refuse whole. + // [#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 + // before this column existed, and each named position is reported refused + // on its row with the reason's code (see the second pass). Not read on a + // dry run, which assigns nothing. let grant: { engine: IdentityImportEngine; context: Record } | undefined; - if (positionsWanted.some((w) => Array.isArray(w))) { + let grantBlocked: { code: 'NOT_IMPLEMENTED' | 'PERMISSION_DENIED'; message: string } | undefined; + if (!prepared.dryRun && positionsWanted.some((w) => Array.isArray(w))) { const seam = deps.createGrant; + const context = seam ? await seam.resolveActorContext() : undefined; if (!seam) { - return fail( - 501, - 'NOT_IMPLEMENTED', - `This server cannot assign positions while importing users, so no one was imported. Import the file ` - + `without the ${POSITIONS_COLUMN} column, then assign positions on each user's record.`, - ); - } - const context = await seam.resolveActorContext(); - if (!context) { - return fail( - 403, - 'PERMISSION_DENIED', - 'Your own access could not be resolved, so the positions could not be judged and no one was imported.', - ); + grantBlocked = { + code: 'NOT_IMPLEMENTED', + message: 'This server cannot assign positions while importing users, so this row\'s positions were not ' + + 'assigned. The user landed; assign the positions on their record.', + }; + } else if (!context) { + grantBlocked = { + code: 'PERMISSION_DENIED', + message: 'Your own access could not be resolved, so this row\'s positions could not be judged and were ' + + 'not assigned. The user landed; assign the positions on their record.', + }; + } else { + grant = { engine, context }; } - grant = { engine, context }; } const protocol: ImportProtocolLike = { @@ -1179,7 +1187,14 @@ export async function runAdminImportUsers( positionLinks.unresolved++; continue; } - // `grant` is set whenever any row names a position (settled above). + // Exactly one of `grant` / `grantBlocked` is set here (read above). + if (grantBlocked) { + const blocked = grantBlocked; + r.positions = wanted.map((position) => ({ position, outcome: 'refused' as const, code: blocked.code })); + positionLinks.refused += wanted.length; + if (r.error === undefined) r.error = blocked.message; + continue; + } const outcomes = await assignRowPositions(grant!, r.id, wanted, r.action === 'updated'); r.positions = outcomes; const failed: string[] = []; From e9211280b3c9c2c503fc0ccbd13969152a2a2fcd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:37:51 +0000 Subject: [PATCH 8/8] docs(plugin-auth): import-users positions that cannot be judged are refused per row, users still created Claude-Session: https://claude.ai/code/session_01ADHkmRNTuoSXYcZLxRV232 Co-authored-by: Claude --- .changeset/33113-import-users-positions-column.md | 2 +- content/docs/permissions/authentication.mdx | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.changeset/33113-import-users-positions-column.md b/.changeset/33113-import-users-positions-column.md index 5dea1f4f0f3..bda685dcf84 100644 --- a/.changeset/33113-import-users-positions-column.md +++ b/.changeset/33113-import-users-positions-column.md @@ -13,7 +13,7 @@ The user import gains one column, `positions`: position machine names, several s - Each named position is assigned after every row of the batch has landed, as a `sys_user_position` grant written under the importing administrator's own execution context, so it passes the same checks as assigning a position in Setup (the position catalog, delegated administration, the holder's organization membership). - A position that does not exist (`unresolved`) or whose assignment is refused (`refused`, with the refusal's `code`) is reported on its row, and the user is still created. `rows[].positions` lists each named position's outcome (`assigned`, `already_assigned`, `unresolved`, `refused`), a cell that is not a list reads `'unreadable'`, and `summary.positions` counts them. The import only adds positions; it never removes one. -- A file that names a position on a server that cannot judge the grant answers `501 NOT_IMPLEMENTED`, and one whose caller's own access does not resolve answers `403 PERMISSION_DENIED`, with nothing created, dry runs included. Dry runs do not assign. +- When the positions cannot be judged at all, the users are still created and every named position is reported `refused` on its row: `NOT_IMPLEMENTED` on a server that cannot assign positions during an import, `PERMISSION_DENIED` when the caller's own access does not resolve. Dry runs do not assign. - There is no permission-set column: a position carries its permission sets. `@object-ui/app-shell`: the Users import wizard offers a `positions` target column, and its options panel explains the column (`console.identityImport.positionsHint`, in every `@object-ui/i18n` pack). diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index b1275018fb3..255c4228308 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1286,12 +1286,12 @@ every row through better-auth so the accounts are login-capable: created. The import only adds positions; it never removes one a user holds. Permission sets come with the position (a position carries its sets); a direct grant stays a Setup step. -- A file that names positions is refused whole, with nothing created, when - its positions cannot be judged: `501 NOT_IMPLEMENTED` when the server - cannot assign positions during an import, and `403 PERMISSION_DENIED` when - your own access cannot be resolved. Both are decided before any row is - written, on a dry run too. A dry run never assigns positions, and reports - `summary.positions` as zeros. +- When a file's positions cannot be judged at all, the users are still + created and only the positions are refused: every named position is + reported `refused` on its row, with code `NOT_IMPLEMENTED` when the server + 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. - Synchronous only, at most 500 rows per request (password hashing is CPU-bound); split larger files into batches. Imports are not undoable.