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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/34741-delegated-scope-holder-controls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/app-shell': patch
---

fix(console): a permission set outside a delegated security administrator's scope offers no Add and no Remove

Clause-②: no
Metadata-protocol: none

On a permission set's Assigned users section, a delegated security administrator was offered Add user, the member picker and each row's Remove for a set outside every delegated scope they hold, and the server then refused the write (403 `DELEGATION_SCOPE_VIOLATION`). The section now reads the caller's own delegable-scope report (`my-delegable-scope`, through `useAuth().describeDelegableScope`, as the invite dialog does): where the report names delegated scopes and the set is in none of their `assignablePermissionSets`, the section lists the holders with no Add, no picker, no Remove and no "click Add" sentence. The server's gate still decides every write (ADR-0090 D6/D12); the section judges nothing else, so a set the report allowlists keeps its controls and a write the gate still refuses (a target user outside the delegate's business-unit subtree) is refused by the server in its own words.

Every other caller keeps the controls as before: a tenant-level administrator, a caller whose report names no delegated scope (how the report draws an organization administrator), and any caller while the report is read, where no runtime serves it, or where the read fails. An organization administrator who also holds a delegated scope is read as the delegate its scopes describe, since the report does not tell the two apart.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@

import * as React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { DelegableScope } from '@object-ui/auth';
import { normaliseClientError } from '@object-ui/data-objectstack';
import { AssignedUsersSection } from './AssignedUsersSection';

Expand All @@ -37,6 +38,22 @@ vi.mock('@object-ui/fields', async (importOriginal) => {
};
});
const pickedUsers = [{ id: 'u_new', name: 'New Nora' }];
// The caller's delegable-scope report, as `useAuth().describeDelegableScope`
// answers it: none unless a case sets one, as outside a runtime that serves it.
let delegableRead: () => Promise<DelegableScope | null> = async () => null;
// The active organization, which the report is resolved in: none unless a case sets one.
let organizationFixture: { id: string } | null = null;
vi.mock('@object-ui/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/auth')>();
return {
...actual,
useAuth: () => ({
...actual.useAuth(),
activeOrganization: organizationFixture,
describeDelegableScope: () => delegableRead(),
}),
};
});
// The section picks its copy by the console locale; English unless a case sets it.
let localeFixture: 'en-US' | 'zh-CN' = 'en-US';
vi.mock('./i18n', async (importOriginal) => ({
Expand Down Expand Up @@ -351,3 +368,135 @@ describe('AssignedUsersSection — one holder of a name more than one package ho
expect(mockAdapter.create).toHaveBeenCalledWith('sys_user_permission_set', { user_id: 'u_new', permission_set: 'sales_rep' });
});
});

/**
* objectstack#34741 (ADR-0090 D6/D12) — a set outside a delegated security
* administrator's scope offers no Add and no Remove: the server's
* delegated-administration gate refuses both (`DELEGATION_SCOPE_VIOLATION`),
* and the section reads that from the server's own `my-delegable-scope`
* report — the set is in no held scope's `assignablePermissionSets`. Every
* other report, and no report, keeps the controls as before.
*/
describe('AssignedUsersSection — a set outside a delegated scope offers no Add and no Remove (objectstack#34741)', () => {
const scope = (assignablePermissionSets: string[]) => ({
setName: 'security_officer',
businessUnit: 'hq',
includeSubtree: true,
manageAssignments: true,
assignablePermissionSets,
businessUnitIds: ['bu_hq'],
});
/** A delegate whose two scopes allowlist other sets than the one shown. */
const outsideReport: DelegableScope = {
isTenantAdmin: false,
scopes: [scope(['showcase_auditor']), scope(['member_default'])],
placeableBusinessUnitIds: ['bu_hq'],
assignablePositions: ['auditor'],
};

/** Render the set under `report`, and settle both the holders read and the report read. */
let lastRerender: (ui: React.ReactElement) => void = () => {};
async function renderUnder(report: Promise<DelegableScope | null>, permissionSetName = 'showcase_contributor') {
delegableRead = () => report;
lastRerender = render(<AssignedUsersSection permissionSetName={permissionSetName} />).rerender;
await act(async () => {
await report.catch(() => undefined);
});
await waitFor(() => expect(screen.queryByText('Loading…')).toBeNull());
}

afterEach(() => {
delegableRead = async () => null;
organizationFixture = null;
});

it('a delegate whose scopes allowlist the set elsewhere: no Add and no Remove on the direct grant', async () => {
await renderUnder(Promise.resolve(outsideReport));
// The holders are still listed: the read asks only to read.
expect(screen.getByText('Direct Dana')).toBeTruthy();
expect(screen.getByText('Held Henry')).toBeTruthy();
expect(screen.queryByText('Add user')).toBeNull();
expect(screen.queryByLabelText('Remove')).toBeNull();
});

it('a delegate, a set nobody holds: the empty state does not say to click Add', async () => {
await renderUnder(Promise.resolve({ ...outsideReport, scopes: [scope(['member_default'])] }), 'showcase_auditor');
expect(screen.getByText('No users assigned yet.')).toBeTruthy();
expect(screen.queryByText(/Click "Add user"/)).toBeNull();
expect(screen.queryByText('Add user')).toBeNull();
});

it('a delegate: an unresolved grant of the set offers no Remove either', async () => {
const saved = data.sys_user_permission_set;
const savedUsers = data.sys_user;
data.sys_user_permission_set = [
{ id: 'g_bare', permission_set: 'sales_rep', permission_set_package: null, user_id: 'u_bare' },
];
data.sys_user = [...savedUsers, { id: 'u_bare', name: 'Bare Bo' }];
try {
const holding = { packageId: 'com.acme.sales', holders: ['com.acme.crm', 'com.acme.sales'] };
delegableRead = () => Promise.resolve(outsideReport);
render(<AssignedUsersSection permissionSetName="sales_rep" holding={holding} />);
const unresolved = await screen.findByTestId('assigned-users-unresolved');
expect(within(unresolved).getByText('Bare Bo')).toBeTruthy();
await waitFor(() => expect(screen.queryByTestId('assigned-users-unresolved-remove-u_bare')).toBeNull());
expect(screen.queryByText('Add user')).toBeNull();
} finally {
data.sys_user_permission_set = saved;
data.sys_user = savedUsers;
}
});

it('a report read in another organization narrows nothing once the active organization changes', async () => {
organizationFixture = { id: 'org_a' };
await renderUnder(Promise.resolve(outsideReport));
expect(screen.queryByText('Add user')).toBeNull();

// Switched to org_b, whose report is still in flight: org_a's is not answered for it.
let settleB: (report: DelegableScope | null) => void = () => {};
delegableRead = () => new Promise((resolve) => (settleB = resolve));
organizationFixture = { id: 'org_b' };
lastRerender(<AssignedUsersSection permissionSetName="showcase_contributor" />);
expect(screen.getByText('Add user')).toBeTruthy();
expect(screen.getAllByLabelText('Remove')).toHaveLength(1);

await act(async () => settleB(outsideReport));
expect(screen.queryByText('Add user')).toBeNull();
});

it('CONTROL: a delegate one of whose scopes allowlists the set keeps Add and Remove', async () => {
await renderUnder(
Promise.resolve({ ...outsideReport, scopes: [scope(['showcase_auditor']), scope(['showcase_contributor'])] }),
);
expect(screen.getByText('Add user')).toBeTruthy();
expect(screen.getAllByLabelText('Remove')).toHaveLength(1);
});

it('CONTROL: a tenant-level administrator keeps Add and Remove', async () => {
await renderUnder(
Promise.resolve({ isTenantAdmin: true, scopes: [], placeableBusinessUnitIds: ['bu_hq'], assignablePositions: ['auditor'] }),
);
expect(screen.getByText('Add user')).toBeTruthy();
expect(screen.getAllByLabelText('Remove')).toHaveLength(1);
});

it('CONTROL: an organization administrator (no delegated scope on the report) keeps Add and Remove', async () => {
await renderUnder(
Promise.resolve({ isTenantAdmin: false, scopes: [], placeableBusinessUnitIds: ['bu_hq'], assignablePositions: ['auditor'] }),
);
expect(screen.getByText('Add user')).toBeTruthy();
expect(screen.getAllByLabelText('Remove')).toHaveLength(1);
});

it('CONTROL: no report (no runtime serves it) keeps Add and Remove', async () => {
await renderUnder(Promise.resolve(null));
expect(screen.getByText('Add user')).toBeTruthy();
expect(screen.getAllByLabelText('Remove')).toHaveLength(1);
});

it('CONTROL: a failed report read keeps Add and Remove, and the server decides', async () => {
await renderUnder(Promise.reject(new Error('my-delegable-scope unreachable')));
expect(screen.getByText('Add user')).toBeTruthy();
expect(screen.getAllByLabelText('Remove')).toHaveLength(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,29 @@
* active organization (the grant is stored with none, a global grant) or a
* composition that registers no `sys_member` — the picker keeps its whole
* list, as the server does.
*
* ## A set outside a delegated scope (objectstack#34741, ADR-0090 D6/D12)
*
* The server's delegated-administration gate decides every grant write, and
* this section only reflects what the server reports of the caller's own
* authority: `my-delegable-scope`, read through
* `useAuth().describeDelegableScope` as the invite dialog reads it. Where that
* report names delegated scopes and the set is in none of their
* `assignablePermissionSets`, the gate refuses every Add and Remove of the set
* (`DELEGATION_SCOPE_VIOLATION`), so neither is offered: no Add, no picker, no
* Remove on any row, and no click-Add sentence ({@link outsideDelegatedScope}).
* Nothing else is judged here — no business-unit subtree, no package holder,
* no containment: a set the report allowlists keeps its controls, and a write
* the gate still refuses (a target user outside the delegate's subtree) is
* refused by the server, in its own words.
*
* Every other report keeps the controls as the affordance gate above draws
* them: none yet (read in flight), none at all (no runtime serves it, or the
* read failed), a tenant-level administrator (`isTenantAdmin`), and a caller
* holding no delegated scope — which is how the report draws an organization
* administrator. The report does not tell an organization administrator who
* also holds a delegated scope from a delegate, so such a caller is read as
* the delegate its scopes describe.
*/

import * as React from 'react';
Expand All @@ -93,7 +116,7 @@ import {
Button,
buttonVariants,
} from '@object-ui/components';
import { useAuth } from '@object-ui/auth';
import { useAuth, type DelegableScope } from '@object-ui/auth';
import { resolveAffordance, type SchemaLike } from '@object-ui/core';
import { RecordPickerDialog } from '@object-ui/fields';
import { usePermissions } from '@object-ui/permissions';
Expand Down Expand Up @@ -365,6 +388,51 @@ function positionLabels(positions: readonly unknown[]): Map<string, string> {
return out;
}

/**
* Does the caller's delegable-scope report put `setName` outside every
* delegated scope it holds (module doc)? Read off the report alone: `true`
* only where it names delegated scopes and none of them lists the set among
* its `assignablePermissionSets`. No report, a tenant-level administrator and
* a caller holding no delegated scope answer `false` — the server decides.
*/
export function outsideDelegatedScope(report: DelegableScope | null | undefined, setName: string): boolean {
if (!report || report.isTenantAdmin || report.scopes.length === 0) return false;
return !report.scopes.some((scope) => scope.assignablePermissionSets.includes(setName));
}

/**
* The caller's delegable-scope report, or `null` while it is read, where no
* runtime serves it, and where the read fails. Read again when the active
* organization changes, the organization the server resolves the report in,
* and a report read for another organization is never answered. The reader is
* held in a ref, never keyed on its identity (ui AGENTS.md #10).
*/
function useDelegableScope(
describe: (() => Promise<DelegableScope | null>) | undefined,
organizationId: string | null,
): DelegableScope | null {
const describeRef = React.useRef(describe);
React.useEffect(() => {
describeRef.current = describe;
});
const [read, setRead] = React.useState<{ organizationId: string | null; report: DelegableScope | null } | null>(null);
React.useEffect(() => {
let cancelled = false;
describeRef.current?.().then(
(report) => {
if (!cancelled) setRead({ organizationId, report });
},
() => {
/* no report: the controls stay as the affordance gate draws them, and the server decides */
},
);
return () => {
cancelled = true;
};
}, [organizationId]);
return read !== null && read.organizationId === organizationId ? read.report : null;
}

export function AssignedUsersSection({ permissionSetName, onHoldersRead, holding: holdingProp }: AssignedUsersSectionProps) {
const adapter = useAdapter() as any;
// The holding by its value: `load` re-keys when the holder changes, never
Expand Down Expand Up @@ -427,7 +495,11 @@ export function AssignedUsersSection({ permissionSetName, onHoldersRead, holding
*/
const [memberFilter, setMemberFilter] = React.useState<MemberFilter | undefined>(undefined);
const [openingPicker, setOpeningPicker] = React.useState(false);
const activeOrganizationId = useAuth().activeOrganization?.id ?? null;
const auth = useAuth();
const activeOrganizationId = auth.activeOrganization?.id ?? null;
const delegable = useDelegableScope(auth.describeDelegableScope, activeOrganizationId);
/** The set is outside every delegated scope the server reports the caller holding (module doc). */
const outsideScope = outsideDelegatedScope(delegable, permissionSetName);

/**
* May the caller add or remove a holder? Each is a write of a
Expand All @@ -447,7 +519,8 @@ export function AssignedUsersSection({ permissionSetName, onHoldersRead, holding
* repo's pin `organization_admin creates and removes assignment rows, never
* edits them — both variants`) — so it is offered Add and Remove; what it may
* create or remove is bounded on the server by the delegated-administration
* gate.
* gate — and where its report puts the set outside every delegated scope
* the caller holds, neither is offered (`outsideScope`, module doc).
*/
const perms = usePermissions();
const grantSource = {
Expand All @@ -456,8 +529,8 @@ export function AssignedUsersSection({ permissionSetName, onHoldersRead, holding
objectName: GRANT_OBJECT,
perms,
};
const canAdd = resolveAffordance('relatedNew', grantSource).allowed;
const canRemove = resolveAffordance('relatedRowDelete', grantSource).allowed;
const canAdd = !outsideScope && resolveAffordance('relatedNew', grantSource).allowed;
const canRemove = !outsideScope && resolveAffordance('relatedRowDelete', grantSource).allowed;
const memberOrganization = membershipOrganization(activeOrganizationId, metadataStore.objects);
/** `sys_user` as the registry serves it, for the picker's column read rule. */
const userSchema = ((metadataStore.objects ?? []).find((o) => (o as { name?: unknown } | null)?.name === 'sys_user') ??
Expand Down
Loading