diff --git a/.changeset/34912-sso-door-org-stamp.md b/.changeset/34912-sso-door-org-stamp.md new file mode 100644 index 00000000000..e0a7b735ff3 --- /dev/null +++ b/.changeset/34912-sso-door-org-stamp.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(auth): the console's Import Users and Add User work on a cloud-managed environment again + +Clause-②: yes (widening) — added: `organizationId` in the bodies of `POST /api/v1/auth/admin/add-sso-user`, `/admin/import-sso-users` and `/admin/remove-sso-user`, admitted only when it equals the organization the caller's session is working in. Nothing that was accepted is refused. +Metadata-protocol: none + +A `type: 'api'` action forwarded to the auth mount carries the caller's active organization as `body.organizationId`. The three SSO-user doors refused every key outside their own set, so the console's Import Users (`sys_user.import_sso_users`) and Add User (`sys_user.add_sso_user`) always answered `400 INVALID_REQUEST` "Unknown field(s): organizationId". + +Each door now admits that one key under a constraint: + +- absent: unchanged; +- equal to the session's active organization: admitted, and ignored. The organization a person joins is still read from the session, never from the body; +- a different organization: `400 INVALID_REQUEST`, naming the organization sent and the one the session holds; +- a value that is not a non-empty string: `400 INVALID_REQUEST`, saying the key must be the id of the organization you are working in. This is checked before the session is read, so it is the answer whether or not the session has an organization; +- a string organization sent by a caller whose session works in no organization: `400 NO_ACTIVE_ORGANIZATION`, naming the organization sent. + +On every refusal nothing is read or written and the host is not told. + +The stamp itself (`buildApiActionRequest` in `@objectstack/runtime`) is unchanged: every identity-route forward still carries it. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 1302545ea7c..9413b44b9a9 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -1346,6 +1346,20 @@ admin plugin, and both are platform-admin gated: with its own message and the good rows land. The answer carries a `summary` and one result per row. +Both doors, and `remove-sso-user` below, also take an optional +`organizationId`. A console action forwarded to the auth mount carries the +caller's active organization there, so the key is admitted only when it +equals the organization the caller's session is working in. A different +organization gets `400 INVALID_REQUEST` naming both organizations; a +non-string or empty value gets `400 INVALID_REQUEST` saying the key must be +the id of the organization you are working in (a non-string value is checked +before the session, so this is the answer even when the session has no +organization); a string organization from a caller whose session works in no +organization gets `400 NO_ACTIVE_ORGANIZATION` naming the organization sent. Every refusal +comes before anything is written or any host is told. The value never +widens or chooses scope: the organization a person joins is always read from +the session. + The person is stored **pending** (`sys_user.source` reads `idp_pending`): no password, and no session until they sign in through the hosting organisation's identity provider. Every password door refuses a pending @@ -1414,9 +1428,10 @@ it are listed on the answer as `notApplied`; set them on the person's record. A pending person who never signs in, for example one added with a mistyped address, can be removed: `POST /api/v1/auth/admin/remove-sso-user` takes -`{ userId }`, removes the person with their positions, permission sets and -membership, and cancels their invitation at the host. The host is asked -first, through its `userRemoved` member; a host without that member is asked +`{ userId }` (and the optional `organizationId` described above), removes +the person with their positions, permission sets and membership, and cancels +their invitation at the host. The host is asked first, through its +`userRemoved` member; a host without that member is asked through `userDeactivated` for the pending person instead, which means the same thing, but a host should implement `userRemoved`. A host's refusal leaves the person as they are. A host that cannot be reached refuses the removal too, diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 4dbc4878ca0..d586a105431 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -260,9 +260,9 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ { route: 'POST /api/v1/auth/admin/import-users', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — objectui app-shell\'s identity-import wizard (views/identityImport.ts) posts it directly from the Users list; platform-admin gated (ADR-0068). A dedicated identity-import door rather than the generic sys_user import, because a direct ObjectQL write would bypass better-auth\'s password hashing and mint no sys_account credential' }, // #33181 — the tracker id stays HERE and never in the `note` string, per the // #16678 note below. - { route: 'POST /api/v1/auth/admin/add-sso-user', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; adds one person who signs in only through the hosting organisation identity provider: a sys_user row marked idp_pending (no password, refused a session) with optional positions, permission sets and manager, joined to the organization; 201, or 200 alreadyPending for a person already pending (the host is told again, unless the person is deactivated: then host reads deactivated and nothing is sent); 409 RESOURCE_CONFLICT off a managed environment or for an address already in use; closed body key set; the environment-user host is told after the write commits, and its answer rides host; platform-admin gated (ADR-0068)' }, - { route: 'POST /api/v1/auth/admin/import-sso-users', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; the CSV or JSON twin of admin/add-sso-user (columns email, name, positions, permission_sets, manager_id), at most 500 rows, each judged and written on its own so a bad row fails alone; answers a summary and one result per row; 409 RESOURCE_CONFLICT off a managed environment; platform-admin gated (ADR-0068)' }, - { route: 'POST /api/v1/auth/admin/remove-sso-user', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; removes a person who is still pending (sys_user.source idp_pending: the email-typo case) with their positions, permission sets and membership, and cancels their invitation at the environment-user host (userRemoved, else userDeactivated), which is asked first so its typed refusal leaves the person as they are; a host that cannot be reached refuses it with 503 SERVICE_UNAVAILABLE and nothing is removed (the door calls the host once and keeps no record to retry from); the person is re-checked inside the unit of work and the row delete carries source idp_pending, so a person who signs in while the host is asked is kept with 409 (on an object with cascading lookups the engine re-deletes by id, so a first sign-in committing in that narrow window is not yet refused); a removal that fails after the host took the cancellation sends the invitation again once through userAdded and says so; body { userId }; 404 RESOURCE_NOT_FOUND for an unknown id; 409 RESOURCE_CONFLICT off a managed environment or for a person who is not pending; a lookup that restricts the delete refuses it with the engine answer; platform-admin gated (ADR-0068)' }, + { route: 'POST /api/v1/auth/admin/add-sso-user', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; adds one person who signs in only through the hosting organisation identity provider: a sys_user row marked idp_pending (no password, refused a session) with optional positions, permission sets and manager, joined to the organization; 201, or 200 alreadyPending for a person already pending (the host is told again, unless the person is deactivated: then host reads deactivated and nothing is sent); 409 RESOURCE_CONFLICT off a managed environment or for an address already in use; closed body key set (email, name, positions, permissionSets, manager) plus an optional organizationId, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope (the joined organization is the session one); the environment-user host is told after the write commits, and its answer rides host; platform-admin gated (ADR-0068)' }, + { route: 'POST /api/v1/auth/admin/import-sso-users', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; the CSV or JSON twin of admin/add-sso-user (columns email, name, positions, permission_sets, manager_id), at most 500 rows, each judged and written on its own so a bad row fails alone; answers a summary and one result per row; body { csv } or { rows } plus the same optional organizationId as admin/add-sso-user, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope; 409 RESOURCE_CONFLICT off a managed environment; platform-admin gated (ADR-0068)' }, + { route: 'POST /api/v1/auth/admin/remove-sso-user', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — Setup → Users on a cloud-managed environment posts it; removes a person who is still pending (sys_user.source idp_pending: the email-typo case) with their positions, permission sets and membership, and cancels their invitation at the environment-user host (userRemoved, else userDeactivated), which is asked first so its typed refusal leaves the person as they are; a host that cannot be reached refuses it with 503 SERVICE_UNAVAILABLE and nothing is removed (the door calls the host once and keeps no record to retry from); the person is re-checked inside the unit of work and the row delete carries source idp_pending, so a person who signs in while the host is asked is kept with 409 (on an object with cascading lookups the engine re-deletes by id, so a first sign-in committing in that narrow window is not yet refused); a removal that fails after the host took the cancellation sends the invitation again once through userAdded and says so; body { userId } plus the same optional organizationId as admin/add-sso-user, admitted only when it equals the caller session active organization: a different organization is 400 INVALID_REQUEST naming both organizations, a non-string or empty value is 400 INVALID_REQUEST (a non-string value is checked before the session), a string organization with no session organization is 400 NO_ACTIVE_ORGANIZATION, and every refusal writes nothing and tells no host; it never widens scope; 404 RESOURCE_NOT_FOUND for an unknown id; 409 RESOURCE_CONFLICT off a managed environment or for a person who is not pending; a lookup that restricts the delete refuses it with the engine answer; platform-admin gated (ADR-0068)' }, { route: 'POST /api/v1/auth/admin/list-platform-admins', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_user list_platform_admins action posts it directly from the Users list; answers who holds platform-admin standing (the last-admin guard\'s enumerator, each id confirmed by hasPlatformAdminStanding), served only to a caller who holds that standing; reads no body. ADR-0095 D3' }, { route: 'POST /api/v1/auth/admin/oauth2/toggle-disabled', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application disable/enable actions post it directly; ObjectStack mount closing a vendor gap (better-auth\'s /admin/oauth2/update-client strips `disabled` from its body schema), platform-admin gated (ADR-0068)' }, // #30958 — the tracker id stays HERE and never in the `note` string, per the diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts index d85a0161601..53f51785ad8 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-users.test.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-users.test.ts @@ -1638,3 +1638,234 @@ describe('[#34130] Set Password is offered and works without the admin plugin', expect((await s.signIn(EMAILS.member, NEW_PASSWORD)).status).toBe(200); }); }); + +// ───────────────────────────────────────────────────────────────────────────── +// The organization an identity-route action forward stamps +// ───────────────────────────────────────────────────────────────────────────── +// +// A `type: 'api'` action forwarded to the auth mount carries the caller's +// active organization as `body.organizationId` (`buildApiActionRequest` in +// `@objectstack/runtime`; its control pin lives beside it in +// `api-action-forward.test.ts`). Each of the three doors admits that one key, +// and only when it equals the organization the caller's own session is +// working in; any other value is refused before anything is read or written, +// and the value never feeds scope. The staged admin's session holds +// DEFAULT_ORG as its active organization (the session-create hook selects the +// sole membership), and `clearActiveOrganization` takes it away. + +describe('[#34912] the SSO-user doors admit the stamped organizationId only when it is the session\'s', () => { + const OTHER_ORG = 'org_elsewhere'; + + /** The admin's sessions with no active organization, as a caller working in none holds them. */ + const clearActiveOrganization = (s: Awaited>): number => { + const sessions = ((s.engine.tables.get('sys_session') ?? []) as any[]).filter((r) => String(r.user_id) === s.ids.admin); + for (const session of sessions) { + session.active_organization_id = null; + delete session.activeOrganizationId; + } + return sessions.length; + }; + + /** Whether the staged admin's session holds DEFAULT_ORG, the fixture invariant every equal-key leg rests on. */ + const assertSessionHoldsDefaultOrg = (s: Awaited>): void => { + const sessions = ((s.engine.tables.get('sys_session') ?? []) as any[]).filter((r) => String(r.user_id) === s.ids.admin); + expect( + sessions.some((r) => (r.active_organization_id ?? r.activeOrganizationId) === DEFAULT_ORG), + 'fixture invariant: the admin session works in DEFAULT_ORG', + ).toBe(true); + }; + + describe('admin/add-sso-user', () => { + it.each([ + ['absent', {}], + ['equal to the session organization', { organizationId: DEFAULT_ORG }], + ])('organizationId %s: the person is added, joined to the session organization', async (_label, extra) => { + const s = await managedStage(); + assertSessionHoldsDefaultOrg(s); + const email = `add.${Object.keys(extra).length}@example.com`; + + const res = await s.fire('/admin/add-sso-user', { email, name: 'Stamped', ...extra }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(201); + const row = s.row(email)!; + expect(row.source).toBe(PENDING_SSO_SOURCE); + expect(s.rowsOf('sys_member', String(row.id)).map((m) => m.organization_id)).toEqual([DEFAULT_ORG]); + expect(body.data).toMatchObject({ email, alreadyPending: false, organizationId: DEFAULT_ORG }); + expect(s.told.map((t) => t.kind)).toEqual(['added']); + }); + + it('a different organization is refused 400 naming both, and no one is added or told', async () => { + const s = await managedStage(); + const v = await verdict( + await s.fire('/admin/add-sso-user', { email: 'foreign.add@example.com', name: 'F', organizationId: OTHER_ORG }, s.bearers.admin), + ); + expect([v.status, v.code], v.text).toEqual([400, 'INVALID_REQUEST']); + expect(v.message).toContain(OTHER_ORG); + expect(v.message).toContain(DEFAULT_ORG); + expect(s.row('foreign.add@example.com')).toBeUndefined(); + expect(s.told).toEqual([]); + }); + + it('no active organization in the session plus a body organization is refused 400 NO_ACTIVE_ORGANIZATION; CONTROL: without the key the add stands', async () => { + const s = await managedStage(); + expect(clearActiveOrganization(s)).toBeGreaterThan(0); + + const v = await verdict( + await s.fire('/admin/add-sso-user', { email: 'noorg.add@example.com', name: 'N', organizationId: DEFAULT_ORG }, s.bearers.admin), + ); + expect([v.status, v.code], v.text).toEqual([400, 'NO_ACTIVE_ORGANIZATION']); + expect(s.row('noorg.add@example.com')).toBeUndefined(); + expect(s.told).toEqual([]); + + const control = await s.fire('/admin/add-sso-user', { email: 'noorg.add@example.com', name: 'N' }, s.bearers.admin); + expect(control.status, await control.clone().text()).toBe(201); + }); + + it('an organizationId that is not a non-empty string is refused 400 and no one is added', async () => { + const s = await managedStage(); + for (const organizationId of [null, '', 42]) { + const v = await verdict( + await s.fire('/admin/add-sso-user', { email: 'typed.add@example.com', name: 'T', organizationId }, s.bearers.admin), + ); + expect([v.status, v.code], `${JSON.stringify(organizationId)}: ${v.text}`).toEqual([400, 'INVALID_REQUEST']); + } + expect(s.row('typed.add@example.com')).toBeUndefined(); + }); + }); + + describe('admin/import-sso-users', () => { + const CSV = 'email,name\nstamp.one@example.com,One\nstamp.two@example.com,Two\n'; + + it.each([ + ['absent', {}], + ['equal to the session organization', { organizationId: DEFAULT_ORG }], + ])('organizationId %s: every row is added, joined to the session organization', async (_label, extra) => { + const s = await managedStage(); + assertSessionHoldsDefaultOrg(s); + + const res = await s.fire('/admin/import-sso-users', { csv: CSV, ...extra }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.summary).toEqual({ total: 2, added: 2, alreadyPending: 0, failed: 0 }); + for (const email of ['stamp.one@example.com', 'stamp.two@example.com']) { + const row = s.row(email)!; + expect(row.source).toBe(PENDING_SSO_SOURCE); + expect(s.rowsOf('sys_member', String(row.id)).map((m) => m.organization_id)).toEqual([DEFAULT_ORG]); + } + }); + + it('a different organization is refused 400 naming both, and no row is imported or told', async () => { + const s = await managedStage(); + const before = s.users().length; + const v = await verdict(await s.fire('/admin/import-sso-users', { csv: CSV, organizationId: OTHER_ORG }, s.bearers.admin)); + expect([v.status, v.code], v.text).toEqual([400, 'INVALID_REQUEST']); + expect(v.message).toContain(OTHER_ORG); + expect(v.message).toContain(DEFAULT_ORG); + expect(s.users()).toHaveLength(before); + expect(s.told).toEqual([]); + }); + + it('no active organization in the session plus a body organization is refused 400 NO_ACTIVE_ORGANIZATION', async () => { + const s = await managedStage(); + expect(clearActiveOrganization(s)).toBeGreaterThan(0); + const before = s.users().length; + const v = await verdict(await s.fire('/admin/import-sso-users', { csv: CSV, organizationId: DEFAULT_ORG }, s.bearers.admin)); + expect([v.status, v.code], v.text).toEqual([400, 'NO_ACTIVE_ORGANIZATION']); + expect(s.users()).toHaveLength(before); + expect(s.told).toEqual([]); + }); + }); + + describe('admin/remove-sso-user', () => { + it.each([ + ['absent', {}], + ['equal to the session organization', { organizationId: DEFAULT_ORG }], + ])('organizationId %s: the pending person is removed', async (_label, extra) => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + assertSessionHoldsDefaultOrg(s); + const id = await addPending(s, 'stamp.remove@example.com'); + + const res = await s.fire('/admin/remove-sso-user', { userId: id, ...extra }, s.bearers.admin); + const body: any = await res.json(); + + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data).toMatchObject({ userId: id, removed: true }); + expect(s.row('stamp.remove@example.com')).toBeUndefined(); + expect(told.map((t) => t.kind)).toEqual(['added', 'removed']); + }); + + it('a different organization is refused 400 naming both; the person is kept and the host is not asked', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const id = await addPending(s, 'foreign.remove@example.com'); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id, organizationId: OTHER_ORG }, s.bearers.admin)); + + expect([v.status, v.code], v.text).toEqual([400, 'INVALID_REQUEST']); + expect(v.message).toContain(OTHER_ORG); + expect(v.message).toContain(DEFAULT_ORG); + expect(s.row('foreign.remove@example.com')).toMatchObject({ id, source: PENDING_SSO_SOURCE }); + expect(s.rowsOf('sys_member', id).length).toBeGreaterThan(0); + expect(told.map((t) => t.kind)).toEqual(['added']); + }); + + it('no active organization in the session plus a body organization is refused 400 NO_ACTIVE_ORGANIZATION; the person is kept', async () => { + const { host, told } = removingHost(); + const s = await managedStage({ host }); + const id = await addPending(s, 'noorg.remove@example.com'); + expect(clearActiveOrganization(s)).toBeGreaterThan(0); + + const v = await verdict(await s.fire('/admin/remove-sso-user', { userId: id, organizationId: DEFAULT_ORG }, s.bearers.admin)); + + expect([v.status, v.code], v.text).toEqual([400, 'NO_ACTIVE_ORGANIZATION']); + expect(s.row('noorg.remove@example.com')).toMatchObject({ id, source: PENDING_SSO_SOURCE }); + expect(told.map((t) => t.kind)).toEqual(['added']); + }); + }); + + it('the body organization never feeds scope: on a multi-organization deployment the person joins the session organization', async () => { + // Driven over fakes so the join's target is observable: the door reads the + // organization from the session seam, and an equal body value is admitted + // without being the value the join is handed. + const engine = createMemoryEngine(); + const joined: unknown[] = []; + const sessionReads: string[] = []; + const deps = { + isCloudManaged: () => true, + getDataEngine: () => engine as any, + getTenancy: () => ({ isolationActive: true }) as any, + getCallerActiveOrganizationId: async () => { + sessionReads.push('read'); + return 'org_session'; + }, + getAddMember: async () => async (input: { body: { organizationId: string } }) => { + joined.push(input.body.organizationId); + return {}; + }, + createGrant: { + resolveActorContext: async () => ({}), + runAtomically: async (work: () => Promise) => work(), + }, + } as any; + const request = (organizationId: unknown) => + new Request(`${ORIGIN}${BASE}/admin/add-sso-user`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'multi.org@example.com', name: 'Multi', organizationId }), + }); + + const refused = await runAddSsoUser(deps, { id: 'admin-1' } as any, request('org_attacker')); + expect([refused.status, refused.body.error?.code]).toEqual([400, 'INVALID_REQUEST']); + expect(joined).toEqual([]); + expect(((engine.tables.get('sys_user') ?? []) as any[]).length).toBe(0); + + const admitted = await runAddSsoUser(deps, { id: 'admin-1' } as any, request('org_session')); + expect(admitted.status, JSON.stringify(admitted.body)).toBe(201); + expect(joined).toEqual(['org_session']); + // The check and the join each read the session; neither read the body's value as the scope. + expect(sessionReads.length).toBeGreaterThanOrEqual(2); + }); +}); diff --git a/packages/plugins/plugin-auth/src/pending-sso-users.ts b/packages/plugins/plugin-auth/src/pending-sso-users.ts index 09363b7f12d..ed0b3c405d8 100644 --- a/packages/plugins/plugin-auth/src/pending-sso-users.ts +++ b/packages/plugins/plugin-auth/src/pending-sso-users.ts @@ -158,6 +158,64 @@ const fail = (status: number, code: string, message: string): EndpointResult => const badRequest = (message: string): EndpointResult => fail(400, 'INVALID_REQUEST', message); +/** + * The one body key every door admits beyond its own: `organizationId`. + * + * A `type: 'api'` action forwarded to the auth mount carries the caller's + * active organization as `body.organizationId` (`buildApiActionRequest`, + * `@objectstack/runtime` `action-execution.ts`), so the console's Import + * Users, Add User and any other action that reaches these doors arrives with + * it. A door that refused the key refused every console call. + * + * The key is admitted only as a statement the session already makes: it must + * equal the organization the caller is working in, read from the caller's + * own session (`getCallerActiveOrganizationId`). Any other value, a value of + * any other type, or a value sent by a caller working in no organization is + * refused before anything is read or written. The value never feeds scope: + * no door reads `body.organizationId` past this check, and the organization a + * person joins is the session's, as it was before (seat ruling A on the card + * that admitted the key). + */ +const STAMPED_ORGANIZATION_KEY = 'organizationId'; + +/** Body keys a door does not take: its own set, plus the stamped organization. */ +const unknownBodyKeys = (body: Record, keys: ReadonlySet): string[] => + Object.keys(body).filter((key) => key !== STAMPED_ORGANIZATION_KEY && !keys.has(key)); + +/** + * Refuse a `body.organizationId` that is not the caller's session + * organization. `undefined` when the key is absent or equal; the refusal + * otherwise, naming what was sent and what the session holds. `outcome` ends + * the sentence ("no one was added", "no one was removed"). + */ +async function refuseForeignOrganization( + deps: PendingSsoUserDeps, + body: Record, + outcome: string, +): Promise { + if (!Object.prototype.hasOwnProperty.call(body, STAMPED_ORGANIZATION_KEY)) return undefined; + const sent = body[STAMPED_ORGANIZATION_KEY]; + if (typeof sent !== 'string' || sent.length === 0) { + return badRequest(`organizationId must be the id of the organization you are working in, so ${outcome}.`); + } + const current = deps.getCallerActiveOrganizationId ? await deps.getCallerActiveOrganizationId() : null; + if (typeof current !== 'string' || current.length === 0) { + return fail( + 400, + 'NO_ACTIVE_ORGANIZATION', + `The request names organization ${sent}, but you are not working in an organization, so ${outcome}. ` + + 'Switch to that organization, then try again.', + ); + } + if (sent !== current) { + return badRequest( + `The request names organization ${sent}, but you are working in organization ${current}, so ${outcome}. ` + + 'Switch to that organization, or send the request from the one you are in.', + ); + } + return undefined; +} + /** One person, as either door reads them. */ interface PendingPersonInput { email: string; @@ -539,10 +597,12 @@ export async function runAddSsoUser( const reading = await readJsonRequestBody(request); if (!reading.ok) return badRequest(reading.message); const body = (reading.body && typeof reading.body === 'object' ? reading.body : {}) as Record; - const unknown = Object.keys(body).filter((key) => !ADD_KEYS.has(key)); + const unknown = unknownBodyKeys(body, ADD_KEYS); if (unknown.length > 0) { return badRequest(`Unknown field(s): ${unknown.join(', ')}. This door takes email, name, positions, permissionSets and manager; it sets no password.`); } + const foreign = await refuseForeignOrganization(deps, body, 'no one was added'); + if (foreign) return foreign; const person = readPerson(body, { positions: 'positions', permissionSets: 'permissionSets', manager: 'manager' }); if (typeof person === 'string') return badRequest(person); @@ -610,8 +670,10 @@ export async function runImportSsoUsers( const reading = await readJsonRequestBody(request); if (!reading.ok) return badRequest(reading.message); const body = (reading.body && typeof reading.body === 'object' ? reading.body : {}) as Record; - const unknownKeys = Object.keys(body).filter((key) => !IMPORT_BODY_KEYS.has(key)); + const unknownKeys = unknownBodyKeys(body, IMPORT_BODY_KEYS); if (unknownKeys.length > 0) return badRequest(`Unknown field(s): ${unknownKeys.join(', ')}. Send { csv } or { rows }.`); + const foreign = await refuseForeignOrganization(deps, body, 'no one was imported'); + if (foreign) return foreign; let rows: Array>; if (typeof body.csv === 'string' && body.rows === undefined) { @@ -745,8 +807,10 @@ export async function runRemoveSsoUser( const reading = await readJsonRequestBody(request); if (!reading.ok) return badRequest(reading.message); const body = (reading.body && typeof reading.body === 'object' ? reading.body : {}) as Record; - const unknownKeys = Object.keys(body).filter((key) => !REMOVE_KEYS.has(key)); + const unknownKeys = unknownBodyKeys(body, REMOVE_KEYS); if (unknownKeys.length > 0) return badRequest(`Unknown field(s): ${unknownKeys.join(', ')}. This door takes userId.`); + const foreign = await refuseForeignOrganization(deps, body, 'no one was removed'); + if (foreign) return foreign; const userId = typeof body.userId === 'string' ? body.userId.trim() : ''; if (!userId) return badRequest('userId is required'); diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index 9bd20e54022..a03eaec3df1 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -51,6 +51,7 @@ import { FORWARD_CREDENTIAL_HEADER, redeemForwardCredential } from '@objectstack import { standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; import { ActionActivationProjection } from '@objectstack/objectql'; import { apiKeyManagementCredentialRefusal, API_KEY_MANAGEMENT_SESSION_REQUIRED_MESSAGE } from '@objectstack/core'; +import { SysUser } from '@objectstack/platform-objects/identity'; const OBJECT = 'crm_lead'; const BAN_LEAD = { @@ -1830,3 +1831,36 @@ describe('[#29881] a per-record api action is refused at the door with no record expect(buildApiActionRequest(RECALC_ONE, { recordId: 'r1', params: {}, ec })).toEqual({ method: 'POST', path: '/api/v1/apps/showcase/recalc', body: { recordId: 'r1' } }); }); }); + +// [#34912] The stamp stays generic. The SSO-user doors (plugin-auth +// `pending-sso-users.ts`) admit the `organizationId` this builder stamps on +// every `/api/v1/auth/` target, when it equals the caller's session +// organization; the builder is not taught which doors take it. CONTROL: the +// declared SSO-user actions are stamped with the caller's organization, and +// so is another identity route (Ban User), exactly as before. +describe('[#34912] buildApiActionRequest stamps the caller organization on every identity route, the SSO-user doors included', () => { + const declared = (name: string) => { + const action = (SysUser.actions ?? []).find((a) => a.name === name); + if (!action) throw new Error(`sys_user declares no action named "${name}"`); + return action; + }; + const ec = { userId: 'u_admin', tenantId: 'org_session' }; + + it('Import Users and Add User forward the caller organization as organizationId', () => { + const imported = buildApiActionRequest(declared('import_sso_users'), { params: { csv: 'email\na@example.com\n' }, ec }); + expect(imported).toEqual({ + method: 'POST', path: '/api/v1/auth/admin/import-sso-users', + body: { csv: 'email\na@example.com\n', organizationId: 'org_session' }, + }); + const added = buildApiActionRequest(declared('add_sso_user'), { params: { email: 'b@example.com' }, ec }); + expect((added as any).body).toEqual({ email: 'b@example.com', organizationId: 'org_session' }); + }); + + it('CONTROL: another identity route keeps the stamp, and no organization means no stamp', () => { + const ban = buildApiActionRequest(declared('ban_user'), { recordId: 'u_target', record: { id: 'u_target' }, params: {}, ec }); + expect((ban as any).path).toBe('/api/v1/auth/admin/ban-user'); + expect((ban as any).body).toMatchObject({ userId: 'u_target', organizationId: 'org_session' }); + const none = buildApiActionRequest(declared('import_sso_users'), { params: { csv: 'x' }, ec: { userId: 'u_admin' } }); + expect((none as any).body).toEqual({ csv: 'x' }); + }); +});