Skip to content

Commit eac6d96

Browse files
fix(rest)!: security/explain refuses an explicit empty userId with 400 instead of explaining the caller (#27714)
domain:server#2 · os-sales · session_01L6bhgUCizoYWQVJWjhdR6F <!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuPMZ8BHWtPf6nBTp51qSM64)_ Fixes #27442 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: updated here — `content/docs/permissions/explain.mdx` now says an empty `userId` is refused `400 VALIDATION_FAILED`, beside "omit `userId` to explain yourself". No file under `skills/**` teaches an empty `userId`: `skills/objectstack-data/rules/security.md` names the query parameters as a list (`?object=&operation=&userId=`) and says nothing about an empty value, so no skill line changes. ## 维护者速读 - **改了什么**:权限解释接口(`GET/POST /api/v1/security/explain`)收到显式的空 `userId`(`"userId": ""` 或 `?userId=`)时,改为回 `400 VALIDATION_FAILED`,不再悄悄解释调用者本人;不传 `userId` 仍解释调用者本人。 - **为什么改**:路由在校验前把空串当成「没传」丢掉,引擎又按真值判断,于是「解释某个空用户」答成了「解释我自己」,管理员会误以为看到的是别人的权限。 - **风险与回滚**:只收窄这一个请求值;不传 `userId`、传真实用户 id、传不存在的 id 三种行为与 main 一致。引擎侧同步改为 `userId !== undefined` 才算「解释自己」,直接调用引擎的代码传空串会得到 403 或 404。回滚即还原 `security-routes.ts` 与 `security-plugin-explain-access.ts` 各一处。 - **先看**:`packages/rest/src/security-routes.ts` 新增的 `src.userId === ''` 拒绝分支;`packages/plugins/plugin-security/src/security-plugin-explain-access.ts` 的 `request.userId !== undefined` 判断。 - **两分钟验证**:`pnpm --filter @objectstack/rest exec vitest run src/security-routes.test.ts -t 27442`,预期 3/3 通过。 - **需要你做的**:无,席位落地(收窄卡,进队前席位排契约复核)。 ## What changes - **The door (`@objectstack/rest`).** `GET`/`POST {basePath}/security/explain` answers `400 VALIDATION_FAILED` when `userId` is the empty string, through the family's one refusal emitter (the same ADR-0112 envelope and code its schema refusals answer), before any explanation is computed. Before, the route dropped an explicit `""` along with an omitted value, so the request fell through to a self-explanation of the caller. - **GET counts as explicit.** `?userId=` names the key, and the query parser hands the route `""` (measured on the showcase boot), so it is refused the same way. Only a request that does not name `userId` at all, or sends JSON `null`, is "explain me", as before. - **The engine (`@objectstack/plugin-security`).** `explainAccessForCaller` enters the other-user arm when `request.userId !== undefined` (was a truthy test). An empty id therefore meets the existing gates there: a caller without the right to explain others gets the same `403 PERMISSION_DENIED`, and a `manage_users` caller gets the `404 RECORD_NOT_FOUND` an unknown id gets. A direct caller of the engine can no longer reach the self-explain fold with `""`. Every in-tree caller of `security.explain` omits `userId` (measured: `rest-server.ts`, `runtime/domains/automation.ts`, `service-storage` x2, `plugin-webhooks`, `plugin-sharing`, `plugin-audit`), so none of them moves. - **No new code, no spec edit.** `VALIDATION_FAILED` is an existing ledgered code, and `ExplainRequestSchema` is untouched (its `z.string().optional()` admits `""`, which is why the refusal sits at the route). - **Docs.** `content/docs/permissions/explain.mdx` states the refusal next to "omit `userId` to explain yourself". ## Tests - `packages/rest/src/security-routes.test.ts` — new block `[#27442]`: POST `userId: ""` → `400`, `success: false`, `error.code` `VALIDATION_FAILED`, no `allowed`, `explain` never called; GET `?userId=` → the same, `explain` never called; omitted `userId` (POST and GET) still calls `explain` without one, and a real other id is still passed through. - `packages/plugins/plugin-security/src/security-plugin.test.ts` — new block `[#27442]`: a `manage_users` caller asking `userId: ""` gets `ExplainUserNotFoundError` (`RECORD_NOT_FOUND`, 404) instead of an explanation of itself; a plain member gets `PermissionDeniedError` (403); an omitted `userId` still explains the caller. - `packages/qa/dogfood/test/explain-unknown-user.dogfood.test.ts` — new case `[empty]` on the showcase boot (the #26641 sibling, same boot, no new one): the seed admin's POST `userId: ""` and GET `?userId=` both answer `400 VALIDATION_FAILED` with no verdict and no principal. The file's existing `[existing]` case keeps pinning that an omitted `userId` explains the caller and a real other id is answered. ## Acceptance notes - Red first, through the door: before the fix the two route cases answered `200` (`expected 200 to be 400`) and the engine case answered an explanation of the caller. - Ablations (each restored, blob == HEAD, `git diff HEAD` empty): - Route guard disabled (`if (src.userId === '')` replaced by a never-true marker, rebuilt, `ablation-dist-preflight` proved the marker in `packages/rest/dist/index.{js,cjs}`): the unit file goes `2 failed | 17 passed` (`expected 200 to be 400`) and the dogfood file `1 failed | 5 passed`, answering `404 RECORD_NOT_FOUND` naming user `''` — the engine's own line holding once the door's is gone. Rebuilt after restore; preflight `--absent` clean. - Engine check reverted to the truthy `request.userId &&`: the engine block goes `1 failed` (`expected { allowed: true, … }` to be the refusal). - Order of checks at the door is unchanged: anonymous `401` first, then `501` when no explain service, then this `400` with the schema refusals. - `null` in a POST body keeps reading as omitted (unchanged); the ruling refuses only an explicit empty string. - Branch is the harness-pinned `claude/project-thread-sbdkgo` (claim 6504756487 names it); card-thread session `session_01L6bhgTYZasLoBBaTy45mgo`. ## Verification All readings on head `821c2ced` (the fix `297d9907` merged with `origin/main` `86f2afeb`), in a worktree of `objectstack-ai/objectstack`, under `scripts/pm/os-verify-lock.sh`. <details><summary>Unit suites and typecheck</summary> - `pnpm --filter @objectstack/rest exec vitest run`: `Test Files 344 passed (344)`, `Tests 6945 passed | 344 skipped (7289)`. - `pnpm --filter @objectstack/plugin-security exec vitest run`: `Test Files 237 passed (237)`, `Tests 5119 passed | 45 skipped (5164)`. - `pnpm --filter @objectstack/rest typecheck` and `pnpm --filter @objectstack/plugin-security typecheck` (including `check:test-typecheck`, 0 errors): exit 0. - Red before the fix: `security-routes.test.ts` `2 failed | 17 passed` (`expected 200 to be 400`); the engine block `1 failed` (an explanation of the caller where the refusal was expected). </details> <details><summary>Door (dogfood) and the full battery</summary> - `pnpm --filter @objectstack/dogfood exec vitest run test/explain-unknown-user.dogfood.test.ts`: `Tests 6 passed (6)`. - Full battery, `pnpm --filter @objectstack/dogfood test` after the closure build (`turbo run build --filter='@objectstack/dogfood^...'`), no shard, no path: `Test Files 352 passed | 3 skipped (355)`, `Tests 2845 passed | 20 skipped (2865)`, lock VERDICT command-exit 0. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 95 families; each was run and its exit code captured before any pipe; `--ran` reconciliation: `95 derived, 95 run, 0 NOT-MEASURED, 0 UNRUN`. - Four first readings were prerequisites (exit 3, or the generated-tree refusal), not verdicts, and were rerun green after meeting them: `check-plugin-teardown-shape --self-test` (pinned fixture commit fetched, 48 cases pass), spec `check:docs` and `check:skill-examples` (after `gen:schema`), `check:dual-build-cjs-loads` (after building the seven packages it listed with no `dist/`). - `pnpm lint` (repo-wide `eslint . --no-inline-config`): exit 0. - No `packages/spec`, `docs/adr/**`, `skills/**` or `.github/**` path is touched. The claim measured no open PR editing either source file. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgUCizoYWQVJWjhdR6F)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgUCizoYWQVJWjhdR6F Co-authored-by: Claude <noreply@anthropic.com>
1 parent ecd944f commit eac6d96

7 files changed

Lines changed: 135 additions & 2 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/rest': patch
3+
'@objectstack/plugin-security': patch
4+
---
5+
6+
fix(rest)!: `security/explain` refuses an explicit empty `userId` with 400 instead of explaining the caller (#27442)
7+
8+
Clause-②: no (narrowing) — `GET`/`POST /api/v1/security/explain` refuses a request whose `userId` is the empty string, which it answered before. Nothing is widened.
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type changes: the explain door refuses one request value, an empty userId, that it used to drop and answer as the caller. There is no authored or stored shape for a migration to rewrite and no tombstone. -->
12+
13+
**BREAKING** accept-set narrowing at the access-explanation door (`@objectstack/rest`), held by the engine too (`@objectstack/plugin-security`).
14+
15+
- **Before.** `POST /api/v1/security/explain` with `"userId": ""` (or `GET …?userId=`) dropped the empty id and answered `200` with an explanation of the CALLER. A client that lost the selected user (an empty picker) got a confident answer about a principal nobody asked about.
16+
- **Now.** The door answers `400 VALIDATION_FAILED`, in the same envelope as its other request refusals, and no explanation is computed. On `GET`, `?userId=` names the key, so it counts as explicit and is refused the same way.
17+
- **Unchanged.** An omitted `userId` still explains the caller; a `userId` naming another user is explained, refused `403`, or refused `404 RECORD_NOT_FOUND` exactly as before.
18+
- **Engine.** `explainAccessForCaller` no longer reads an empty `userId` as "the caller": it goes through the other-user arm, so a direct caller gets the `403` (no right to explain others) or the `404 RECORD_NOT_FOUND` an unknown id gets.
19+
20+
**The remedy.** Omit `userId` to explain your own access, or send the id of the user to explain.

‎content/docs/permissions/explain.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ curl -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/jso
7171

7272
`operation` is one of `read | create | update | delete | transfer | restore |
7373
purge | export` (defaults to `read`); omit `userId` to explain **yourself**.
74+
An empty `userId` (`"userId": ""`, or `?userId=` with no value) names nobody, so
75+
it is refused `400 VALIDATION_FAILED` rather than read as "yourself".
7476

7577
`export` is the one operation whose answer you cannot infer from `read`. Since
7678
the [export axis](/docs/permissions/permission-sets#allowexport--the-export-axis)

‎packages/plugins/plugin-security/src/security-plugin-explain-access.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,10 @@ export async function explainAccessForCaller(
133133
const recordId = request?.recordId != null && request.recordId !== '' ? String(request.recordId) : undefined;
134134

135135
let targetContext = callerContext ?? {};
136-
if (request.userId && request.userId !== callerContext?.userId) {
136+
// [#27442] Any `userId` that is not omitted, the empty string included, goes
137+
// through the other-user arm: an empty id names nobody, so it is refused
138+
// there like an unknown one, never folded into explaining the caller.
139+
if (request.userId !== undefined && request.userId !== callerContext?.userId) {
137140
const callerIsSystem = callerContext?.isSystem === true;
138141
if (!callerIsSystem) {
139142
const callerSets = await this.resolvePermissionSetsForContext(callerContext).catch(() => []);

‎packages/plugins/plugin-security/src/security-plugin.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3891,6 +3891,34 @@ describe('explainAccessForCaller (ADR-0090 D6/D12)', () => {
38913891
});
38923892
});
38933893

3894+
// [#27442] An explicit empty `userId` names nobody, so it is never read as
3895+
// "explain me": it goes through the other-user arm, where it is refused like
3896+
// any id no `sys_user` row has. The REST door refuses it 400 before this; the
3897+
// engine holds the same line for a caller that reaches it directly.
3898+
describe('[#27442] an explicit empty userId', () => {
3899+
it('is never answered as the caller: manage_users gets 404, a plain member 403', async () => {
3900+
const { plugin } = await boot();
3901+
const hr = { userId: 'u_hr', positions: [], permissions: ['hr_admin'] };
3902+
const admin: any = await plugin
3903+
.explainAccessForCaller({ object: 'task', operation: 'read', userId: '' }, hr)
3904+
.then((d) => d, (e) => e);
3905+
expect(admin, 'refused, not an explanation of the caller').toMatchObject({
3906+
name: 'ExplainUserNotFoundError', code: 'RECORD_NOT_FOUND', status: 404, userId: '',
3907+
});
3908+
const plain = { userId: 'u_east_1', positions: [], permissions: [] };
3909+
await expect(
3910+
plugin.explainAccessForCaller({ object: 'task', operation: 'read', userId: '' }, plain),
3911+
).rejects.toMatchObject({ name: 'PermissionDeniedError', code: 'PERMISSION_DENIED' });
3912+
});
3913+
3914+
it('an omitted userId still explains the caller', async () => {
3915+
const { plugin } = await boot();
3916+
const plain = { userId: 'u_east_1', positions: [], permissions: [] };
3917+
const self = await plugin.explainAccessForCaller({ object: 'task', operation: 'read' }, plain);
3918+
expect(self.principal.userId).toBe('u_east_1');
3919+
});
3920+
});
3921+
38943922
// [#20515] Explaining ANOTHER user resolves that user's grants in the CALLER's
38953923
// organization — the one the explain right was checked in. A grant scoped to
38963924
// an organization applies only while that organization is the one resolved

‎packages/qa/dogfood/test/explain-unknown-user.dogfood.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
* `PERMISSION_DENIED` it gets naming a user who exists.
2424
* - `[unknown]` the seed admin naming the unknown id → 404 `RECORD_NOT_FOUND`
2525
* naming it, for `read` and `create`, consistent with the data door's 404.
26+
* - `[empty]` (#27442) an explicit empty `userId`, in the body or as
27+
* `?userId=`, is refused 400 `VALIDATION_FAILED`: it names nobody, so it is
28+
* never answered as the caller.
2629
* - `[existing]` the seed admin explaining the member who exists is answered
2730
* as before (200, the principal is that member), and explaining yourself is
2831
* unchanged.
@@ -108,6 +111,24 @@ describe('#26641: security explain refuses a userId no sys_user row has', () =>
108111
}
109112
});
110113

114+
// [#27442] The same door's remaining gap: an explicit empty `userId` names
115+
// nobody, and was dropped before the schema, so it explained the CALLER. It
116+
// is refused 400 on both transports; an omitted `userId` (below) is the caller.
117+
it('[empty] an explicit empty userId is refused 400 VALIDATION_FAILED, never answered as the caller', async () => {
118+
const posted = await explain(adminTok, { object: OBJECT, operation: 'read', userId: '' });
119+
const queried = await stack.apiAs(adminTok, 'GET', `/security/explain?object=${OBJECT}&operation=read&userId=`);
120+
const queriedText = await queried.text();
121+
let queriedJson: any = null;
122+
try { queriedJson = JSON.parse(queriedText); } catch { /* the status still reports */ }
123+
for (const [label, r] of [['POST', posted], ['GET', { status: queried.status, text: queriedText, json: queriedJson }]] as const) {
124+
expect(r.status, `${label}: ${r.text}`).toBe(400);
125+
expect(r.json?.success, `${label}: ${r.text}`).toBe(false);
126+
expect(r.json?.error?.code, `${label}: ${r.text}`).toBe('VALIDATION_FAILED');
127+
expect(r.json?.allowed, `${label}: no verdict is answered`).toBeUndefined();
128+
expect(r.json?.principal, `${label}: no principal is answered`).toBeUndefined();
129+
}
130+
});
131+
111132
it('[existing] the seed admin explaining the member who exists, and anyone explaining themselves, is answered', async () => {
112133
const other = await explain(adminTok, { object: OBJECT, operation: 'read', userId: memberId });
113134
expect(other.status, other.text).toBe(200);

‎packages/rest/src/security-routes.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,54 @@ describe('GET/POST /security/explain (ADR-0090 D6)', () => {
154154
});
155155
});
156156

157+
// ── [#27442] an explicit empty userId is refused, an omitted one is the caller ─
158+
159+
describe('[#27442] GET/POST /security/explain with an empty userId', () => {
160+
it('POST userId "" is refused 400 VALIDATION_FAILED and nothing is explained', async () => {
161+
const explain = vi.fn().mockResolvedValue(DECISION);
162+
const { post } = buildServer(async () => ({ explain }), { callerCtx: CALLER });
163+
const res = mockRes();
164+
await post!.handler({ method: 'POST', params: {}, headers: {}, body: { object: 'task', operation: 'read', userId: '' } } as any, res);
165+
166+
expect(res.statusCode).toBe(400);
167+
expect(res.body.success).toBe(false);
168+
expect(res.body.error.code).toBe('VALIDATION_FAILED');
169+
expect(res.body.allowed, 'no verdict is answered').toBeUndefined();
170+
expect(explain).not.toHaveBeenCalled();
171+
});
172+
173+
it('GET ?userId= names the key too, so it is refused the same way', async () => {
174+
const explain = vi.fn().mockResolvedValue(DECISION);
175+
const { get } = buildServer(async () => ({ explain }), { callerCtx: CALLER });
176+
const res = mockRes();
177+
await get!.handler({ method: 'GET', params: {}, headers: {}, query: { object: 'task', userId: '' } } as any, res);
178+
179+
expect(res.statusCode).toBe(400);
180+
expect(res.body.error.code).toBe('VALIDATION_FAILED');
181+
expect(explain).not.toHaveBeenCalled();
182+
});
183+
184+
it('an omitted userId still explains the caller, and a named user is still passed through', async () => {
185+
const explain = vi.fn().mockResolvedValue(DECISION);
186+
const { get, post } = buildServer(async () => ({ explain }), { callerCtx: CALLER });
187+
188+
let res = mockRes();
189+
await post!.handler({ method: 'POST', params: {}, headers: {}, body: { object: 'task', operation: 'read' } } as any, res);
190+
expect(res.statusCode).toBe(200);
191+
expect(explain).toHaveBeenLastCalledWith({ object: 'task', operation: 'read' }, CALLER);
192+
193+
res = mockRes();
194+
await get!.handler({ method: 'GET', params: {}, headers: {}, query: { object: 'task' } } as any, res);
195+
expect(res.statusCode).toBe(200);
196+
expect(explain).toHaveBeenLastCalledWith({ object: 'task', operation: 'read' }, CALLER);
197+
198+
res = mockRes();
199+
await post!.handler({ method: 'POST', params: {}, headers: {}, body: { object: 'task', operation: 'read', userId: 'u_target' } } as any, res);
200+
expect(res.statusCode).toBe(200);
201+
expect(explain).toHaveBeenLastCalledWith({ object: 'task', operation: 'read', userId: 'u_target' }, CALLER);
202+
});
203+
});
204+
157205
// ── [#8326] batch form — recordIds on the same request shape ─────────────────
158206

159207
/**

‎packages/rest/src/security-routes.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,10 +204,21 @@ export function registerSecurityExplainEndpoints(this: SecurityExplainRouteHost,
204204
const rawRecordIds = req.method === 'GET' && typeof src.recordIds === 'string' && src.recordIds !== ''
205205
? [src.recordIds]
206206
: src.recordIds;
207+
// [#27442] An omitted `userId` means the caller; an explicit empty
208+
// one names nobody, so it is refused rather than dropped (dropping
209+
// it answered about the caller, a principal nobody asked about).
210+
// `?userId=` names the key on GET, so it is explicit there too.
211+
// The schema's `z.string()` admits "", so the refusal is here.
212+
if (src.userId === '') {
213+
return respondError(
214+
res, 400, 'VALIDATION_FAILED',
215+
'Invalid explain request — userId is empty. Omit userId to explain your own access, or give the id of the user to explain.',
216+
);
217+
}
207218
const parsed = (ExplainRequestSchema as any).safeParse({
208219
object: src.object,
209220
operation: src.operation ?? 'read',
210-
...(src.userId != null && src.userId !== '' ? { userId: src.userId } : {}),
221+
...(src.userId != null ? { userId: src.userId } : {}),
211222
// [C2 / ADR-0095] Optional record id — explains ONE concrete
212223
// row at record granularity; omitted stays object-level.
213224
...(src.recordId != null && src.recordId !== '' ? { recordId: src.recordId } : {}),

0 commit comments

Comments
 (0)