Skip to content

Commit 107be28

Browse files
fix(plugin-security): type explainAccessForCaller's request as the contract's ExplainAccessRequest (#29578)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8VXJ5hk8EG2fKt5gobE64M1)_ Fixes #29481 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`SecurityPlugin#explainAccessForCaller` 的请求参数类型从内联的 `{ object; operation; userId?; recordId? }` 改为契约里的 `ExplainAccessRequest`,于是批量形态 `recordIds` 也在声明类型里了。 - 为什么改:方法体早已支持 `recordIds`,公开契约也已声明它,只有方法签名漏掉;类型化调用方想批量解释访问权限必须强转。 - 风险与回滚:纯类型改动,运行时零变化;回滚即撤回 `security-plugin.ts` 的一行签名与一个 import。 - 先看:`packages/plugins/plugin-security/src/security-plugin.ts`(签名与 import),`packages/plugins/plugin-security/src/explain-batch-parity.test.ts`(新增的类型钉与直调用例)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-security typecheck`,预期退出 0;把签名改回旧的内联类型后同一命令出现 3 个错误(见 Verification)。 - 需要你做的:无,席位落地。 ## What changes - `packages/plugins/plugin-security/src/security-plugin.ts`: `explainAccessForCaller(request: ExplainAccessRequest, callerContext?)`, importing the interface from `@objectstack/spec/contracts`. The body module (`security-plugin-explain-access.ts`) already reads `request.recordIds`; nothing else moves. `SecurityServiceHost['explainAccessForCaller']` is `SecurityPlugin['explainAccessForCaller']`, so the service host picks the contract type up with no edit. - `packages/plugins/plugin-security/src/explain-batch-parity.test.ts`: a new `describe` (item 3 of the file header, "THE TYPED DOOR"): - compile-time: `expectTypeOf` holds the method's first parameter equal to `ExplainAccessRequest`, with a `@ts-expect-error` control showing the matcher can fail (the selector without `recordIds` is a different type). Both are live: `tsconfig.test.json` compiles this file, and `check:test-typecheck` runs it from the package's `typecheck` script. - runtime: a typed caller passes `recordIds` as an object literal straight to `plugin.explainAccessForCaller` and gets exactly the answer the registered `security` service gives for the same batch. - `plugin` is lifted from a `beforeAll` local to a module binding so the case can call it. - `.changeset/29481-explain-access-request-type.md`: `patch` for `@objectstack/plugin-security` (a published package; the method is public on the exported class). ## Why The published `ExplainAccessRequest` gained `recordIds?: ExplainRequest['recordIds']` with #29297, and the body honours it, but the reference implementation's own method still declared a request without it. A typed caller of `SecurityPlugin.explainAccessForCaller` could not pass a batch without a cast, and the declared type disagreed with what the method honours. ## Tests - `pnpm --filter @objectstack/plugin-security test`: Test Files 241 passed (241), Tests 5202 passed, 45 skipped (5247), lock VERDICT command-exit 0 (run at ace9462; the later head eafb125 changes only the new test case, re-run below). - `pnpm --filter @objectstack/plugin-security exec vitest run --maxWorkers=2 src/explain-batch-parity.test.ts` at eafb125: Test Files 1 passed (1), Tests 46 passed (46), exit 0. - `pnpm --filter @objectstack/plugin-security typecheck` at eafb125: exit 0; `check:test-typecheck: OK`, the test layer compiles under `tsconfig.test.json` with 0 errors. ## Acceptance notes - No runtime change, so no ablation: the reverse verification below is the proof the pin can fail. - The runtime case passes the request as an object literal on purpose, so the excess-property check would refuse `recordIds` against the old declared type. ## Verification <details><summary>Reverse verification: the old signature restored, the test kept (3 errors, then restored)</summary> `security-plugin.ts` replaced by its `origin/main` blob (old inline request type), the committed test unchanged, `tsc --noEmit -p tsconfig.test.json` under the verify lock: exit 2, VERDICT command-exit 2. ``` src/explain-batch-parity.test.ts(290,91): error TS2344: Type 'ExplainAccessRequest' does not satisfy the constraint '{ object: string; operation: string; userId?: string | undefined; recordId?: string | undefined; ... src/explain-batch-parity.test.ts(292,5): error TS2578: Unused '@ts-expect-error' directive. src/explain-batch-parity.test.ts(298,93): error TS2561: Object literal may only specify known properties, but 'recordIds' does not exist in type '{ object: string; operation: string; userId?: string | undefined; recordId ... ``` Restored with `git checkout HEAD -- PATH`; `git hash-object` equals the HEAD blob and `git status --porcelain` is empty. Direction observed: red, as expected. </details> <details><summary>Gates (local subset, head eafb125)</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 62 families for this diff; each ran at eafb125 with its exit code captured before any pipe, then `--ran` reconciled the record: **62 derived, 61 run, 1 NOT-MEASURED, 0 UNRUN** (exit 0). - 61 families exit 0. Two of them first exited 3 (prerequisite not met) and were re-run after the stated prerequisite: `node scripts/check-plugin-teardown-shape.mjs --self-test` after fetching its pinned fixture commit (48 cases pass), and `pnpm check:i18n` after its own one-command build closure (`check-i18n-bundles: OK (10 package(s) — all bundles in sync, no undeclared authoring keys)`). - NOT MEASURED: `pnpm check:dual-build-cjs-loads`, exit 3 (reads every package's `dist/`, which needs a whole-workspace `pnpm build`); declared to CI's `Lint & Repo Gates`. - `pnpm lint`: exit 0. - Dogfood battery: n/a, no `!` in the title and no `(narrowing)` arm. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (exit 0 at eafb125). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a, not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block is the dispatch contract's Chinese summary). Card thread for seat `domain:server#4`; dispatch claim on #29481. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbZiGjTXK1aGW4idvJ7)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3557366 commit 107be28

3 files changed

Lines changed: 43 additions & 3 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-security': patch
3+
---
4+
5+
fix(plugin-security): `SecurityPlugin#explainAccessForCaller` takes the contract's `ExplainAccessRequest`, so a typed caller passes `recordIds` without a cast
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The method's request was declared inline as `{ object; operation; userId?; recordId? }`, while the body it delegates to already honours the batch form `recordIds` and the published `ExplainAccessRequest` (`@objectstack/spec/contracts`) declares it. The parameter is now typed as that contract interface, so the declared type carries every member the method honours and follows the contract from here on. Type-only: no runtime behaviour changes.

‎packages/plugins/plugin-security/src/explain-batch-parity.test.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,24 @@
2323
// person row are read once for a batch, as for one singular explanation,
2424
// never once per id: that per-id repetition is what made a 31-row list page
2525
// wait seconds for its row menus.
26+
// 3. THE TYPED DOOR. `SecurityPlugin#explainAccessForCaller`, the method the
27+
// service's `explain` delegates to, declares the contract's
28+
// `ExplainAccessRequest` as its request, so a typed caller passes
29+
// `recordIds` without a cast and gets the service's answer. Compile-time
30+
// half: `expectTypeOf` plus a `@ts-expect-error` control, both live because
31+
// `tsconfig.test.json` compiles this file.
2632
//
2733
// The real `SecurityPlugin`, `SharingService` and sharing middleware over a
2834
// real `ObjectQL` and SQL driver (better-sqlite3, in memory), asked through
2935
// the registered `security` service, the member the REST door calls.
3036

31-
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
37+
import { describe, it, expect, expectTypeOf, beforeAll, afterAll, vi } from 'vitest';
3238
import { ObjectQL } from '@objectstack/objectql';
3339
import { SqlDriver } from '@objectstack/driver-sql';
3440
import { SharingService, buildSharingMiddleware, SysRecordShare } from '@objectstack/plugin-sharing';
3541
import { PermissionSetSchema } from '@objectstack/spec/security';
3642
import type { ExplainDecision, ExplainOperation } from '@objectstack/spec/security';
43+
import type { ExplainAccessRequest } from '@objectstack/spec/contracts';
3744
import { SysOrganization, SysUser, SysMember } from '@objectstack/platform-objects/identity';
3845

3946
import { SysPosition } from './__tests__/legacy-catalog-objects.testkit.js';
@@ -99,6 +106,7 @@ const IDS: Record<string, string[]> = {
99106
};
100107

101108
let engine: ObjectQL;
109+
let plugin: SecurityPlugin;
102110
let security: { explain: (request: Record<string, unknown>, ctx?: unknown) => Promise<ExplainDecision> };
103111
/** Engine reads, by `<verb> <object>`, while counting is on. */
104112
let reads: Map<string, number> | undefined;
@@ -199,7 +207,7 @@ beforeAll(async () => {
199207
return services[name];
200208
},
201209
};
202-
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
210+
plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
203211
await plugin.init(ctx as never);
204212
await plugin.start(ctx as never);
205213
wireEngineSecuritySource(engine, () => plugin);
@@ -277,6 +285,23 @@ describe('[#29112] security/explain: a batch answers what N singular explanation
277285
});
278286
});
279287

288+
describe('SecurityPlugin#explainAccessForCaller: the request is typed as the contract declares it', () => {
289+
it('declares the contract request, so recordIds is a typed member and not an extra key', () => {
290+
expectTypeOf<Parameters<SecurityPlugin['explainAccessForCaller']>[0]>().toEqualTypeOf<ExplainAccessRequest>();
291+
// Control: the matcher can fail. The request without its batch member is a different type.
292+
// @ts-expect-error -- the declared request carries recordIds, so it is not the selector without it
293+
expectTypeOf<Parameters<SecurityPlugin['explainAccessForCaller']>[0]>().toEqualTypeOf<Omit<ExplainAccessRequest, 'recordIds'>>();
294+
});
295+
296+
it('a typed caller passes recordIds with no cast and gets the answer the service gives', async () => {
297+
// An object literal, so the compiler checks every key against the declared request.
298+
const direct = await plugin.explainAccessForCaller({ object: LINE, operation: 'update', recordIds: IDS[LINE] }, { ...SELF });
299+
const viaService = await security.explain(request(SELF, LINE, 'update', { recordIds: IDS[LINE] }), { ...SELF });
300+
expect(direct.records?.map((r) => r.recordId)).toEqual(IDS[LINE]);
301+
expect(direct).toEqual(viaService);
302+
});
303+
});
304+
280305
describe('[#29112] security/explain: a batch reads the explained principal once, not once per id', () => {
281306
const PRINCIPAL_READS = ['find sys_user_permission_set', 'find sys_user_position', 'findOne sys_user'];
282307

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,7 @@ import {
287287
type ControlledByParentWriteDenialLeg,
288288
type ControlledByParentWriteOutcome,
289289
type PositionGrantSummary,
290+
type ExplainAccessRequest,
290291
} from '@objectstack/spec/contracts';
291292
import {
292293
type MatchesFilterOptions,
@@ -2372,9 +2373,13 @@ export class SecurityPlugin implements Plugin {
23722373
* explaining ANOTHER user whose read of the record is refused (a declared
23732374
* 4xx) is answered so too; a caller explaining itself keeps the write path's
23742375
* notion (no row), so its explanation shows what its own doors do.
2376+
*
2377+
* The request is the contract's `ExplainAccessRequest` itself, so the
2378+
* method's declared type carries every member the body honours, the batch
2379+
* form `recordIds` included, and cannot drift from the published selector.
23752380
*/
23762381
explainAccessForCaller(
2377-
request: { object: string; operation: string; userId?: string; recordId?: string },
2382+
request: ExplainAccessRequest,
23782383
callerContext?: any,
23792384
): Promise<ExplainDecision> {
23802385
// [#25223 cut 10] The body moved to `security-plugin-explain-access.ts` (see `ExplainAccessHost`).

0 commit comments

Comments
 (0)