Skip to content

Commit 43106bd

Browse files
committed
fix(react,components,app-shell): a delegated admin's out-of-scope save shows the server's reason
A 403 DELEGATION_SCOPE_VIOLATION carries the boundary of the caller's own delegated scope that refused the write. The record form and the flow-run path classed every 403 as a plain denial and showed the fixed form.noPermissionToSave line. delegationScopeMessage reads the code before isPermissionError; every other denial keeps the fixed line (ruling B' on the record-save rule, unchanged). Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JZRTRVa5FXXjuAJC6ZPM8P
1 parent e14d9ce commit 43106bd

8 files changed

Lines changed: 188 additions & 5 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@object-ui/react': patch
3+
'@object-ui/components': patch
4+
'@object-ui/app-shell': patch
5+
---
6+
7+
fix(react,components,app-shell): a delegated admin's out-of-scope save shows the server's reason instead of the fixed no-permission line
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
When a delegated administrator saved something outside their own scope, the server answered `403 DELEGATION_SCOPE_VIOLATION` with the boundary that refused it (a business unit outside the delegated subtree, a permission set not in the scope's allowlist, a target user outside the subtree). The console read every 403 as a plain denial, so the toast and the in-form banner said only "You don't have permission to save this record."
13+
14+
- **`@object-ui/react`.** New `delegationScopeMessage(err)`: the server's reason, without the `[Security] ` machine prefix, when the error's code (`code` or `details.code`) is `DELEGATION_SCOPE_VIOLATION`; `null` for everything else. It is read before `isPermissionError`, which still answers true for any 403.
15+
- **`@object-ui/components`.** The record form's toast and banner show that reason. A producer-marked `userMessage` still comes first.
16+
- **`@object-ui/app-shell`.** A flow run whose write node met the same refusal (`innerRefusal`) shows the same reason.
17+
18+
Every other denial is unchanged: `PERMISSION_DENIED`, `FORBIDDEN`, a bare 403 and a row-level-security refusal still show the fixed localized line and never the server's text.
19+
20+
What to do: nothing.

‎ui/packages/app-shell/src/utils/__tests__/flowResponse.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,25 @@ describe('interpretFlowResponse — a refusal met inside the run, by the record-
696696
expect((zh as { error: string }).error).not.toContain('crm_account');
697697
});
698698

699+
// objectstack#26059 Q3: a delegated admin's out-of-scope write is the one
700+
// denial whose reason is shown; it describes only the caller's own scope.
701+
it('a delegated-admin scope refusal shows the server reason, not the fixed permission line', () => {
702+
const SCOPE_REASON =
703+
"Outside your delegated scope: delegated 'create' on sys_user_position rejected — business unit 'bu_west' is outside the delegated subtree (scope from 'regional_admin').";
704+
const SCOPE = { code: 'DELEGATION_SCOPE_VIOLATION', message: `[Security] ${SCOPE_REASON}` } as const;
705+
706+
expect(failed400(flowFailed({ innerRefusal: SCOPE }))).toEqual({
707+
kind: 'failed', error: SCOPE_REASON, retryable: false,
708+
});
709+
const on200 = interpretFlowResponse(ok, {
710+
success: true,
711+
data: { success: false, status: 'failed', error: RAW_ERROR, innerRefusal: SCOPE },
712+
}, 'Flow "assign"');
713+
expect(on200).toMatchObject({ kind: 'failed', error: SCOPE_REASON });
714+
// Control: a plain denial on the same path still reads the fixed line.
715+
expect(failed400(flowFailed({ innerRefusal: DENIED }))).toMatchObject({ error: builtInLocales.en.form.noPermissionToSave });
716+
});
717+
699718
it('a producer-marked userMessage wins over the inner refusal, verbatim', () => {
700719
expect(failed400(flowFailed({ innerRefusal: UNIQUE }, USER_TEXT))).toMatchObject({ error: USER_TEXT });
701720
expect(failed400(flowFailed({ innerRefusal: DENIED }, USER_TEXT))).toMatchObject({ error: USER_TEXT });

‎ui/packages/app-shell/src/utils/flowResponse.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@
214214
import { actionCopySource, actionErrorDetail } from '@object-ui/core';
215215
import type { ActionResult } from '@object-ui/core';
216216
import { getLoadedBuiltInLocales } from '@object-ui/i18n';
217-
import { declaredUserMessage, isPermissionError } from '@object-ui/react';
217+
import { declaredUserMessage, delegationScopeMessage, isPermissionError } from '@object-ui/react';
218218
import { errorCodeIs } from '@object-ui/types';
219219
import type { AutomationResult } from '@objectstack/spec/contracts';
220220
import { translateFlow, type TranslationBundle } from '@objectstack/spec/system';
@@ -368,7 +368,9 @@ function permissionDeniedLine(locale: string | undefined): string {
368368
* The inner refusal is rendered exactly as the record form renders the same
369369
* refusal on a save: a permission denial (`isPermissionError`) becomes the
370370
* form's localized permission line instead of server prose (objectstack#3821),
371-
* anything else reads its own sentence. `message` stays the last rung, so a
371+
* anything else reads its own sentence. A delegated-admin scope refusal
372+
* (`DELEGATION_SCOPE_VIOLATION`) reads its own reason, asked before the
373+
* permission check exactly as the form asks it (objectstack#26059, Q3). `message` stays the last rung, so a
372374
* run that met no refusal still says something, never nothing.
373375
*/
374376
function flowFailureMessage(failure: FlowFailureCarriers, message: string, copy: FlowCopyLocale | undefined): string {
@@ -378,6 +380,8 @@ function flowFailureMessage(failure: FlowFailureCarriers, message: string, copy:
378380
const inner = failure.innerRefusal as { code?: unknown; message?: unknown } | null | undefined;
379381
if (inner && typeof inner === 'object' && typeof inner.code === 'string') {
380382
const refusal = { code: inner.code, message: typeof inner.message === 'string' ? inner.message : '' };
383+
const scopeReason = delegationScopeMessage(refusal);
384+
if (scopeReason) return scopeReason;
381385
if (isPermissionError(refusal)) return permissionDeniedLine(copy?.locale);
382386
if (refusal.message.trim()) return refusal.message;
383387
}

‎ui/packages/components/src/__tests__/form-write-error-message.test.tsx‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,53 @@ describe('a producer-marked refusal reaches the user', () => {
160160
expect(await screen.findByText(/title must be unique/i)).toBeInTheDocument();
161161
});
162162
});
163+
164+
/**
165+
* objectstack#26059 Q3 (child #26190) — a delegated administrator who saves
166+
* outside their own scope is told which boundary refused it.
167+
*
168+
* `403 DELEGATION_SCOPE_VIOLATION` is the one denial whose server reason is
169+
* shown: it describes only the caller's own delegated scope. Every other denial
170+
* keeps the fixed line (objectstack#24914 B′, unchanged), which the plain-403
171+
* control below holds.
172+
*/
173+
describe('a delegated-admin scope refusal shows the server reason', () => {
174+
const REASON =
175+
"Outside your delegated scope: delegated 'update' on sys_user_position rejected — business unit 'bu_west' is outside the delegated subtree (scope from 'regional_admin').";
176+
177+
beforeEach(() => {
178+
vi.spyOn(console, 'warn').mockImplementation(() => {});
179+
});
180+
181+
function scopeRefusal() {
182+
// The shape `@objectstack/client` hands the form for a 403: the server's
183+
// message on `message`, the semantic code on `code`, the status on
184+
// `httpStatus`.
185+
return Object.assign(new Error(`[Security] ${REASON}`), {
186+
code: 'DELEGATION_SCOPE_VIOLATION',
187+
httpStatus: 403,
188+
});
189+
}
190+
191+
it("renders the server's reason, without the machine prefix, instead of the fixed line", async () => {
192+
const { container } = renderForm(async () => { throw scopeRefusal(); });
193+
fireEvent.click(screen.getByRole("button", { name: /submit/i }));
194+
195+
expect(await screen.findByText(REASON)).toBeInTheDocument();
196+
expect(screen.queryByText(/permission to save/i)).not.toBeInTheDocument();
197+
expect(container.textContent).not.toMatch(/\[Security\]/);
198+
});
199+
200+
it('CONTROL: a plain 403 PERMISSION_DENIED keeps the fixed line and withholds its text', async () => {
201+
const { container } = renderForm(async () => {
202+
throw Object.assign(
203+
new Error("[Security] Access denied: delegated 'update' on sys_user_position rejected — no delegated scope covers this write."),
204+
{ code: 'PERMISSION_DENIED', httpStatus: 403 },
205+
);
206+
});
207+
fireEvent.click(screen.getByRole("button", { name: /submit/i }));
208+
209+
expect(await screen.findByText(/permission to save/i)).toBeInTheDocument();
210+
expect(container.textContent).not.toMatch(/sys_user_position/);
211+
});
212+
});

‎ui/packages/components/src/renderers/form/form.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import { FullscreenEditor } from '../../custom/fullscreen-editor';
4242
import { CharacterCount } from '../../custom/character-count';
4343
import { cn } from '../../lib/utils';
4444
import React from 'react';
45-
import { SchemaRendererContext, usePredicateScope, isPermissionError, extractWriteErrorMessage, extractFieldErrors, declaredUserMessage } from '@object-ui/react';
45+
import { SchemaRendererContext, usePredicateScope, isPermissionError, extractWriteErrorMessage, extractFieldErrors, declaredUserMessage, delegationScopeMessage } from '@object-ui/react';
4646
import { createSafeTranslation } from '@object-ui/i18n';
4747

4848
/**
@@ -3048,8 +3048,15 @@ ComponentRegistry.register('form',
30483048
// construction rather than by us guessing what a 403 body contains.
30493049
// Status-agnostic on purpose: 403 is where this was reported
30503050
// (objectui#5210), not a fence the contract draws.
3051+
// A delegated administrator's out-of-scope write (`403
3052+
// DELEGATION_SCOPE_VIOLATION`) is the one denial whose reason is shown:
3053+
// it describes only the caller's own scope, and it tells them which
3054+
// boundary to fix (objectstack#26059, Q3). It is read before
3055+
// `isPermissionError`, which answers true for any 403; every other
3056+
// denial keeps the fixed line (objectstack#24914 B′).
30513057
const errorMessage =
30523058
declaredUserMessage(error) ??
3059+
delegationScopeMessage(error) ??
30533060
(isPermissionError(error)
30543061
? t('form.noPermissionToSave')
30553062
: extractWriteErrorMessage(error) ?? t('form.submitFailed'));

‎ui/packages/react/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export type { PredicateGateKind } from './utils/visibilityDiagnostic.js';
8484

8585
// Write-error surfacing utilities (shared by drag-write plugins so a failed
8686
// PATCH — e.g. an RLS 403 — is never silently swallowed).
87-
export { extractWriteErrorMessage, isPermissionError, extractFieldErrors, classifyLoadError, declaredUserMessage } from './utils/error-message.js';
87+
export { extractWriteErrorMessage, isPermissionError, extractFieldErrors, classifyLoadError, declaredUserMessage, delegationScopeMessage } from './utils/error-message.js';
8888
export type { WriteFieldError, LoadErrorKind } from './utils/error-message.js';
8989

9090
// Built-in i18n support

‎ui/packages/react/src/utils/error-message.test.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { describe, it, expect } from 'vitest';
1010

1111
import { ApiErrorSchema } from '@objectstack/spec/api';
1212

13-
import { extractFieldErrors, classifyLoadError, declaredUserMessage } from './error-message';
13+
import { extractFieldErrors, classifyLoadError, declaredUserMessage, delegationScopeMessage, isPermissionError } from './error-message';
1414

1515
describe('extractFieldErrors', () => {
1616
// The wire shape the server actually sends: `@objectstack/rest` serves a
@@ -250,3 +250,44 @@ describe('declaredUserMessage', () => {
250250
expect(declaredUserMessage(parsedUnmarked)).toBeNull();
251251
});
252252
});
253+
254+
// objectstack#26059 Q3: the one denial whose server reason a surface shows.
255+
describe('delegationScopeMessage', () => {
256+
const REASON =
257+
"Outside your delegated scope: delegated 'update' on sys_user_permission_set rejected — permission set 'finance_admin' is not in the scope's allowlist (scope from 'regional_admin').";
258+
259+
it("answers the server's reason, without the machine prefix, for a 403 DELEGATION_SCOPE_VIOLATION", () => {
260+
const err = Object.assign(new Error(`[Security] ${REASON}`), {
261+
code: 'DELEGATION_SCOPE_VIOLATION',
262+
httpStatus: 403,
263+
});
264+
expect(delegationScopeMessage(err)).toBe(REASON);
265+
// The reason it must be asked first: the permission predicate claims it too.
266+
expect(isPermissionError(err)).toBe(true);
267+
});
268+
269+
it('reads the code from `details` too, the pair isPermissionError reads', () => {
270+
const err = Object.assign(new Error(`[Security] ${REASON}`), {
271+
httpStatus: 403,
272+
details: { code: 'DELEGATION_SCOPE_VIOLATION' },
273+
});
274+
expect(delegationScopeMessage(err)).toBe(REASON);
275+
});
276+
277+
it('CONTROL: every other denial answers null, so its text stays withheld', () => {
278+
const denied = (code: string | undefined) =>
279+
Object.assign(new Error("[Security] Access denied: delegated 'update' on sys_user_position rejected — no scope."), {
280+
code,
281+
httpStatus: 403,
282+
});
283+
expect(delegationScopeMessage(denied('PERMISSION_DENIED'))).toBeNull();
284+
expect(delegationScopeMessage(denied('FORBIDDEN'))).toBeNull();
285+
expect(delegationScopeMessage(denied(undefined))).toBeNull();
286+
expect(delegationScopeMessage(new Error('row-level security policy violation'))).toBeNull();
287+
expect(delegationScopeMessage(null)).toBeNull();
288+
});
289+
290+
it('answers null for a scope refusal with no usable text, so the caller still says something', () => {
291+
expect(delegationScopeMessage({ code: 'DELEGATION_SCOPE_VIOLATION', httpStatus: 403, message: '' })).toBeNull();
292+
});
293+
});

‎ui/packages/react/src/utils/error-message.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
*/
2323

2424
import { isApiAccessDeniedError } from '@object-ui/data-objectstack';
25+
import { errorCodeIs } from '@object-ui/types';
2526
import type { ApiError } from '@objectstack/spec/api';
2627

2728
/**
@@ -136,6 +137,43 @@ export function declaredUserMessage(err: unknown): string | null {
136137
return null;
137138
}
138139

140+
/**
141+
* The ADR-0112 code a delegated administrator's write answers when it falls
142+
* outside the caller's OWN `adminScope` (the ledger row registered under
143+
* `@objectstack/plugin-security`, thrown as `DelegationScopeViolationError`).
144+
*/
145+
const DELEGATION_SCOPE_VIOLATION = 'DELEGATION_SCOPE_VIOLATION';
146+
147+
/**
148+
* The server's reason for a delegated-admin scope refusal, or `null` when the
149+
* refusal is anything else.
150+
*
151+
* A `403 DELEGATION_SCOPE_VIOLATION` names which boundary of the caller's own
152+
* delegated scope refused the write (a business unit outside the delegated
153+
* subtree, a permission set outside the allowlist, a target user outside the
154+
* subtree). That text describes only the caller's own scope, so it is safe to
155+
* show, and it tells the delegate what to fix (ruling on objectstack#26059, Q3).
156+
* Every other denial stays opaque: `PERMISSION_DENIED`, `FORBIDDEN`, a bare 403
157+
* or a row-level-security refusal answers `null` here, and callers keep their
158+
* fixed localized line (ruling B′ on objectstack#24914, unchanged).
159+
*
160+
* Callers must ask this BEFORE {@link isPermissionError}: that predicate answers
161+
* true for any 403, so a scope refusal read after it is flattened into the
162+
* plain denial. The code is read from the same pair {@link isPermissionError}
163+
* reads (`code`, then `details.code`); the text is
164+
* {@link extractWriteErrorMessage}'s, without the `[Security] ` machine prefix.
165+
* A scope refusal that carries no usable text answers `null`, so the caller
166+
* still says something.
167+
*/
168+
export function delegationScopeMessage(err: unknown): string | null {
169+
if (!err || typeof err !== 'object') return null;
170+
const details = (err as { details?: unknown }).details;
171+
if (!errorCodeIs(err, DELEGATION_SCOPE_VIOLATION) && !errorCodeIs(details, DELEGATION_SCOPE_VIOLATION)) {
172+
return null;
173+
}
174+
return extractWriteErrorMessage(err);
175+
}
176+
139177
/** One field the server rejected, normalised for `form.setError`. */
140178
export interface WriteFieldError {
141179
/** Field name, matching the form control's `name`. */
@@ -198,6 +236,10 @@ export function extractFieldErrors(err: unknown): WriteFieldError[] | null {
198236
* `PERMISSION_DENIED` / `FORBIDDEN` / a row-level-security denial). Lets a
199237
* caller show a friendly "you don't have permission" toast rather than dumping
200238
* the raw server text.
239+
*
240+
* A delegated-admin scope refusal is a 403 too, so this answers true for it:
241+
* a caller that shows that refusal's reason asks
242+
* {@link delegationScopeMessage} first.
201243
*/
202244
export function isPermissionError(err: unknown): boolean {
203245
const e = err as Record<string, any> | null | undefined;

0 commit comments

Comments
 (0)