Skip to content

Commit 6880b04

Browse files
fix(objectql): a read-only secret field keeps its stored value on update (#34620)
Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:更新记录时,`readonlyWhen` 谓词为真而锁定的 `secret` 字段、以及静态 `readonly` 的 `secret` 字段,不再接受调用方写入;按 id 与按谓词(`multi`)两条更新路径都保持存储值,并像其它只读字段一样报告丢弃(`onFieldsDropped`、`X-ObjectStack-Dropped-Fields`、`strictReadonlyWrites` 拒绝)。 - 为什么改:规则是「调用方不可写的字段保持存储值,无论字段类型」,`secret` 字段同样适用。 - 风险与回滚:只涉及更新路径上两道只读剥离对 `secret` 字段的作者判定,以及 `sys_secret` 行只在语句仍引用它时写入;未锁定的 `secret` 照旧加密存为引用,hook 写入的值照旧保留。回滚即 revert 本 PR。 - 先看:`packages/objectql/src/engine-update-sealed-secrets.ts`(判定本身);`packages/objectql/src/engine-update.ts` 两个分支的调用点与两处 `persistSecretRows`;`packages/objectql/src/engine-update-locked-secret.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run src/engine-update-locked-secret.test.ts`,预期 12/12 通过。 - 需要你做的:无,席位落地。 ## What changes A field the caller may not write keeps its stored value, whatever its type. This PR makes that hold for a `secret` field on both update paths, by id and by predicate (`multi: true`): - A `secret` field locked by a TRUE `readonlyWhen`, or declared static `readonly`, takes no caller write: the stored reference is unchanged and no `sys_secret` row is written for the value sent. - The read-only strips report the field as they report any other: `onFieldsDropped` (`readonly_when` / `readonly`), the REST `droppedFields` body and `X-ObjectStack-Dropped-Fields` header, and the `strictReadonlyWrites` refusal (`ERR_READONLY_FIELD_REJECTED`). - New `packages/objectql/src/engine-update-sealed-secrets.ts`: authorship of each `secret` key is read immediately before the credential pass, and both strips (and the views they build) judge a submission in which each caller-held key carries the reference that stands for the caller's value. A sealed `sys_secret` row is written only when the payload handed to the statement still names it. - Unchanged: an unlocked `secret` is sealed and stored as a reference; a value a `beforeUpdate` hook writes on a locked `secret` is the hook's and is kept; hooks read `ctx.submitted` as before. As for every `readonlyWhen` field, `isSystem` does not exempt a caller value on a locked `secret`. ## Tests - `packages/objectql/src/engine-update-locked-secret.test.ts` (new, 12 cases), by id and by predicate: a `readonlyWhen`-locked secret and a static `readonly` secret keep their stored value and are reported; `strictReadonlyWrites` refuses with `ERR_READONLY_FIELD_REJECTED` naming both and writes nothing; `isSystem` does not exempt the `readonlyWhen` lock; controls: an unlocked secret is sealed and stored as a reference, a hook-written value on a locked secret is kept (alone, and over a caller value). - `packages/rest/src/rest-update-locked-secret.test.ts` (new, 2 cases): `PATCH /data/:object/:id` on the locked secrets answers 200 with both fields in `droppedFields` and the header, stored references unchanged; control: an unlocked secret through the same door is sealed and stored as a reference. ## Acceptance notes - `Clause-②: no`. The declared contract already states the rule: `packages/spec/src/data/field.zod.ts`, `readonly` — "server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE and on INSERT ... symmetric with `readonlyWhen`". No spec, schema, export or error code changes; no published accept set or surface widens. ## Verification Readings as of head `5abed35fbe` (the branch with `origin/main` b019048 merged in). Readings not yet taken are named NOT MEASURED with their reason; they follow to the seat, not into this body. <details><summary>Reproduction on the base (temporary probe, not committed)</summary> Base `6c7d730f16`, non-system caller, by id and by predicate: 4 of 4 rule checks failed (2 locked secrets × 2 paths), 0 drops reported. Same probe on head: NOT MEASURED (lock queue); the committed pins measure head instead. </details> <details><summary>Engine pins</summary> `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-update-locked-secret.test.ts` on `8cedf9f52d` (before the merge): 11 passed, 1 failed. The failure was the multi hook control's own construction (its handler keyed on a value it rewrote, so the matched rows' handlers wrote different keys and the engine refused the write as designed); fixed in `3524713e38`. Re-run on the current head: NOT MEASURED (shared verify lock held by a sibling's full dogfood run for over an hour). </details> <details><summary>REST pin, package suites, typecheck</summary> `packages/rest/src/rest-update-locked-secret.test.ts`, `pnpm --filter @objectstack/objectql test`, `pnpm --filter @objectstack/rest test`, both packages' `typecheck`: NOT MEASURED locally (same lock queue; rest's test closure is 32 packages to build). CI's Test Core and TypeScript Type Check run them on this PR. </details> <details><summary>Ablation</summary> Planned one-shot: the authorship view in `engine-update-sealed-secrets.ts` disabled, engine pins expected red on the locked cases and green on the controls, then restored and proven by blob hash. NOT MEASURED at open (lock queue); the reading goes to the seat. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `5abed35fbe`: 67 commands, each run, exit captured before any pipe. 63 exit 0. Not passes: - `check:dts-closure` exit 1: `packages/formula` and `packages/metadata-core` dists were half-written by a build a container restart killed; not from this diff. Re-run after the rebuild: NOT MEASURED. - `check:lean-entry-closure` exit 3, `check:dual-build-cjs-loads` exit 3: PREREQUISITE NOT MET (no built dist) — NOT MEASURED. - `check:type-check-debt` exit 3: its closure build never got the lock (99) — NOT MEASURED. CI's Lint & Repo Gates and TypeScript Type Check carry all four. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 8bc0808 commit 6880b04

5 files changed

Lines changed: 640 additions & 11 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a read-only secret field keeps its stored value on update
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A field the caller may not write keeps its stored value, whatever its type. This now holds for a `secret` field on both update paths, by id and by predicate (`multi: true`):
11+
12+
- A `secret` field locked by a TRUE `readonlyWhen`, or declared static `readonly`, takes no caller write. The stored reference is unchanged, and no `sys_secret` row is written for the value the caller sent.
13+
- The read-only strip reports the field like any other: `onFieldsDropped` names it (`readonly_when` or `readonly`), and `strictReadonlyWrites` refuses the write with `ERR_READONLY_FIELD_REJECTED`.
14+
- As for any `readonlyWhen` field, `isSystem` does not exempt a caller value on a locked `secret`; a system write still sets a static `readonly` one.
15+
16+
Unchanged: an unlocked `secret` is sealed and stored as a reference, and a value a `beforeUpdate` hook writes on a locked `secret` is kept.
Lines changed: 325 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,325 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A field the caller may not write keeps its stored value, whatever its type —
5+
* a `secret` field included, on both update paths (by id and by predicate).
6+
*
7+
* A `secret` locked by a TRUE `readonlyWhen`, or declared static `readonly`,
8+
* takes no caller write: the stored reference is unchanged, no `sys_secret`
9+
* row is written for the value, and the read-only strip reports the field
10+
* (`onFieldsDropped`, and the `strictReadonlyWrites` refusal). The controls
11+
* hold the rest of the rule in place: an unlocked `secret` is still sealed and
12+
* stored as a reference, and a value a hook writes on a locked `secret` is
13+
* still the hook's and is kept.
14+
*
15+
* Driven through a real {@link ObjectQL} over a stub driver that keeps every
16+
* store in memory, so the stored reference and the `sys_secret` table can be
17+
* read after each write. See `engine-update-sealed-secrets.ts`.
18+
*/
19+
20+
import { describe, it, expect, beforeEach } from 'vitest';
21+
import type { ICryptoProvider, CryptoHandle } from '@objectstack/spec/contracts';
22+
import { ObjectQL } from './engine.js';
23+
import { isSecretRef, parseSecretRef } from './secret-fields.js';
24+
import { READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js';
25+
26+
type Row = Record<string, unknown>;
27+
28+
/** A stub driver whose stores can be read back, with snapshot transactions. */
29+
function makeDriver() {
30+
let stores = new Map<string, Map<string, Row>>();
31+
const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!);
32+
const matches = (row: Row, where: any) =>
33+
!where || Object.entries(where).every(([k, v]) => {
34+
if (k.startsWith('$')) return true;
35+
if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]);
36+
return (row[k] ?? null) === (v ?? null);
37+
});
38+
const copy = (r: Row | undefined) => (r == null ? r : { ...r });
39+
const snapshots = new Map<unknown, typeof stores>();
40+
let n = 0;
41+
const driver: any = {
42+
name: 'memory', version: '0.0.0', supports: {},
43+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
44+
async syncSchema() {},
45+
async find(o: string, ast: any) {
46+
const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
47+
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
48+
return page.map(copy);
49+
},
50+
async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; },
51+
async create(o: string, data: Row) {
52+
const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` };
53+
storeFor(o).set(String(row.id), row);
54+
return copy(row);
55+
},
56+
async update(o: string, id: string, data: Row) {
57+
const row = { ...storeFor(o).get(String(id)), ...data, id };
58+
storeFor(o).set(String(id), row);
59+
return copy(row);
60+
},
61+
async updateMany(o: string, ast: any, data: Row) {
62+
let k = 0;
63+
for (const [id, row] of storeFor(o)) {
64+
if (!matches(row, ast?.where)) continue;
65+
storeFor(o).set(id, { ...row, ...data, id });
66+
k += 1;
67+
}
68+
return k;
69+
},
70+
async delete(o: string, id: string) { return storeFor(o).delete(String(id)); },
71+
async deleteMany(o: string, ast: any) {
72+
let k = 0;
73+
for (const [id, row] of Array.from(storeFor(o))) {
74+
if (!matches(row, ast?.where)) continue;
75+
storeFor(o).delete(id);
76+
k += 1;
77+
}
78+
return k;
79+
},
80+
async count(o: string, ast: any) { return (await this.find(o, ast)).length; },
81+
async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); },
82+
async bulkUpdate() { return []; }, async bulkDelete() {},
83+
async beginTransaction() {
84+
const handle = { trx: snapshots.size + 1 };
85+
snapshots.set(handle, new Map(Array.from(stores, ([o, s]) => [o, new Map(Array.from(s, ([k, v]) => [k, { ...v }]))])));
86+
return handle;
87+
},
88+
async commit(h: unknown) { snapshots.delete(h); },
89+
async rollback(h: unknown) { stores = snapshots.get(h) ?? stores; snapshots.delete(h); },
90+
};
91+
return { driver, rowsOf: (o: string) => Array.from(storeFor(o).values()) };
92+
}
93+
94+
function makeCrypto(): ICryptoProvider {
95+
let n = 0;
96+
return {
97+
async encrypt(plain: string): Promise<CryptoHandle> {
98+
n += 1;
99+
return { id: `sec_${n}`, kmsKeyId: 'local', alg: 'test-b64', version: 1, ciphertext: Buffer.from(plain).toString('base64') };
100+
},
101+
async decrypt(handle: CryptoHandle) { return Buffer.from(handle.ciphertext, 'base64').toString('utf8'); },
102+
async rotateKey(handle: CryptoHandle) { return handle; },
103+
digest(plain: string) { return `d:${plain.length}`; },
104+
async keyedDigest(plain: string) { return `k:${plain.length}`; },
105+
};
106+
}
107+
108+
const sysSecret = {
109+
name: 'sys_secret', label: 'Secret', systemFields: { tenant: false },
110+
fields: {
111+
id: { name: 'id', type: 'text' }, namespace: { name: 'namespace', type: 'text' }, key: { name: 'key', type: 'text' },
112+
kms_key_id: { name: 'kms_key_id', type: 'text' }, alg: { name: 'alg', type: 'text' },
113+
version: { name: 'version', type: 'number' }, ciphertext: { name: 'ciphertext', type: 'text' },
114+
created_at: { name: 'created_at', type: 'datetime' },
115+
},
116+
};
117+
118+
const CRED = 'qa_locked_cred';
119+
const cred = {
120+
name: CRED, label: 'Credential',
121+
fields: {
122+
id: { name: 'id', type: 'text' },
123+
name: { name: 'name', type: 'text' },
124+
status: { name: 'status', type: 'text' },
125+
/** Locked by state: read-only while the row is `locked`. */
126+
state_key: { name: 'state_key', type: 'secret', readonlyWhen: "record.status == 'locked'" },
127+
/** Locked always: a static `readonly` secret. */
128+
fixed_key: { name: 'fixed_key', type: 'secret', readonly: true },
129+
/** Not locked: the control. */
130+
open_key: { name: 'open_key', type: 'secret' },
131+
},
132+
};
133+
134+
const SYSTEM = { context: { isSystem: true } } as any;
135+
136+
describe('a secret field the caller may not write keeps its stored value', () => {
137+
let engine: ObjectQL;
138+
let d: ReturnType<typeof makeDriver>;
139+
let drops: Array<{ object: string; fields: string[]; reason: string }>;
140+
141+
const stored = (id: string) => d.rowsOf(CRED).find((r) => r.id === id) as Row;
142+
const secretRows = () => d.rowsOf('sys_secret');
143+
/** The plaintext a stored reference opens to, read from the `sys_secret` row it names. */
144+
const opens = (ref: unknown) => {
145+
const handle = parseSecretRef(ref);
146+
const row = secretRows().find((r) => r.id === handle);
147+
return row ? Buffer.from(String(row.ciphertext), 'base64').toString('utf8') : undefined;
148+
};
149+
const listen = { onFieldsDropped: (e: any) => drops.push(e) };
150+
151+
beforeEach(async () => {
152+
drops = [];
153+
const logger: any = { warn() {}, debug() {}, info() {}, error() {}, trace() {}, fatal() {}, child() { return logger; } };
154+
engine = new ObjectQL({ logger });
155+
d = makeDriver();
156+
engine.registerDriver(d.driver, true);
157+
await engine.init();
158+
engine.registry.registerObject(sysSecret as any, 'test');
159+
engine.registry.registerObject(cred as any, 'test');
160+
engine.setCryptoProvider(makeCrypto());
161+
for (const [id, name] of [['c1', 'one'], ['c2', 'pair'], ['c3', 'pair']] as const) {
162+
await engine.insert(CRED, {
163+
id, name, status: 'locked',
164+
state_key: `state-${id}`, fixed_key: `fixed-${id}`, open_key: `open-${id}`,
165+
}, SYSTEM);
166+
}
167+
});
168+
169+
describe('by id', () => {
170+
it('a secret locked by a TRUE readonlyWhen keeps its stored value, and the strip reports it', async () => {
171+
const before = stored('c1').state_key;
172+
const secretsBefore = secretRows().length;
173+
174+
await engine.update(CRED, { id: 'c1', name: 'renamed', state_key: 'caller-value' }, listen as any);
175+
176+
expect(stored('c1').name).toBe('renamed');
177+
expect(stored('c1').state_key).toBe(before);
178+
expect(opens(stored('c1').state_key)).toBe('state-c1');
179+
expect(secretRows()).toHaveLength(secretsBefore);
180+
expect(drops).toEqual([{ object: CRED, fields: ['state_key'], reason: 'readonly_when' }]);
181+
});
182+
183+
it('a static readonly secret keeps its stored value, and the strip reports it', async () => {
184+
const before = stored('c1').fixed_key;
185+
const secretsBefore = secretRows().length;
186+
187+
await engine.update(CRED, { id: 'c1', name: 'renamed', fixed_key: 'caller-value' }, listen as any);
188+
189+
expect(stored('c1').name).toBe('renamed');
190+
expect(stored('c1').fixed_key).toBe(before);
191+
expect(opens(stored('c1').fixed_key)).toBe('fixed-c1');
192+
expect(secretRows()).toHaveLength(secretsBefore);
193+
expect(drops).toEqual([{ object: CRED, fields: ['fixed_key'], reason: 'readonly' }]);
194+
});
195+
196+
it('under strictReadonlyWrites a write to a locked secret is refused, naming it, and nothing is written', async () => {
197+
const before = { ...stored('c1') };
198+
const secretsBefore = secretRows().length;
199+
200+
await expect(engine.update(
201+
CRED, { id: 'c1', name: 'renamed', state_key: 'caller-a', fixed_key: 'caller-b' },
202+
{ strictReadonlyWrites: true } as any,
203+
)).rejects.toMatchObject({ code: READONLY_FIELD_REJECTED_CODE, fields: expect.arrayContaining(['state_key', 'fixed_key']) });
204+
205+
expect(stored('c1')).toEqual(before);
206+
expect(secretRows()).toHaveLength(secretsBefore);
207+
});
208+
209+
it('isSystem does not exempt a caller value on a secret locked by a TRUE readonlyWhen', async () => {
210+
const before = stored('c1').state_key;
211+
212+
await engine.update(CRED, { id: 'c1', state_key: 'system-value' }, SYSTEM);
213+
214+
expect(stored('c1').state_key).toBe(before);
215+
});
216+
217+
it('control: an unlocked secret is still sealed and stored as a reference', async () => {
218+
const before = stored('c1').open_key;
219+
220+
await engine.update(CRED, { id: 'c1', open_key: 'fresh-value' }, listen as any);
221+
222+
const after = stored('c1').open_key;
223+
expect(isSecretRef(after)).toBe(true);
224+
expect(after).not.toBe(before);
225+
expect(opens(after)).toBe('fresh-value');
226+
expect(drops).toEqual([]);
227+
});
228+
229+
it('control: a value a hook writes on a locked secret is kept', async () => {
230+
engine.registerHook('beforeUpdate', async (ctx: any) => {
231+
if (ctx.input.data.name === 'rotate') {
232+
ctx.input.data.state_key = 'hook-state';
233+
ctx.input.data.fixed_key = 'hook-fixed';
234+
}
235+
}, { object: CRED });
236+
237+
await engine.update(CRED, { id: 'c1', name: 'rotate' }, listen as any);
238+
239+
expect(opens(stored('c1').state_key)).toBe('hook-state');
240+
expect(opens(stored('c1').fixed_key)).toBe('hook-fixed');
241+
expect(drops).toEqual([]);
242+
});
243+
244+
it('control: a hook value written over a caller value on a locked secret is kept', async () => {
245+
engine.registerHook('beforeUpdate', async (ctx: any) => {
246+
if ('state_key' in ctx.input.data) ctx.input.data.state_key = 'hook-state';
247+
}, { object: CRED });
248+
249+
await engine.update(CRED, { id: 'c1', state_key: 'caller-value' }, listen as any);
250+
251+
expect(opens(stored('c1').state_key)).toBe('hook-state');
252+
expect(drops).toEqual([]);
253+
});
254+
});
255+
256+
describe('by predicate (multi)', () => {
257+
const pair = (o: Row = {}) => ({ where: { name: 'pair' }, multi: true, ...listen, ...o }) as any;
258+
259+
it('a secret locked by a TRUE readonlyWhen keeps its stored value on every matched row, and the strip reports it', async () => {
260+
const before = [stored('c2').state_key, stored('c3').state_key];
261+
const secretsBefore = secretRows().length;
262+
263+
await engine.update(CRED, { status: 'locked', state_key: 'caller-value' }, pair());
264+
265+
expect([stored('c2').state_key, stored('c3').state_key]).toEqual(before);
266+
expect(opens(stored('c2').state_key)).toBe('state-c2');
267+
expect(opens(stored('c3').state_key)).toBe('state-c3');
268+
expect(secretRows()).toHaveLength(secretsBefore);
269+
expect(drops).toEqual([{ object: CRED, fields: ['state_key'], reason: 'readonly_when' }]);
270+
});
271+
272+
it('a static readonly secret keeps its stored value on every matched row, and the strip reports it', async () => {
273+
const before = [stored('c2').fixed_key, stored('c3').fixed_key];
274+
const secretsBefore = secretRows().length;
275+
276+
await engine.update(CRED, { status: 'locked', fixed_key: 'caller-value' }, pair());
277+
278+
expect([stored('c2').fixed_key, stored('c3').fixed_key]).toEqual(before);
279+
expect(opens(stored('c2').fixed_key)).toBe('fixed-c2');
280+
expect(secretRows()).toHaveLength(secretsBefore);
281+
expect(drops).toEqual([{ object: CRED, fields: ['fixed_key'], reason: 'readonly' }]);
282+
});
283+
284+
it('under strictReadonlyWrites a write to a locked secret is refused, naming it, and nothing is written', async () => {
285+
const before = [{ ...stored('c2') }, { ...stored('c3') }];
286+
const secretsBefore = secretRows().length;
287+
288+
await expect(engine.update(
289+
CRED, { state_key: 'caller-a', fixed_key: 'caller-b' }, pair({ strictReadonlyWrites: true }),
290+
)).rejects.toMatchObject({ code: READONLY_FIELD_REJECTED_CODE, fields: expect.arrayContaining(['state_key', 'fixed_key']) });
291+
292+
expect([stored('c2'), stored('c3')]).toEqual(before);
293+
expect(secretRows()).toHaveLength(secretsBefore);
294+
});
295+
296+
it('control: an unlocked secret is still sealed and stored as a reference on every matched row', async () => {
297+
await engine.update(CRED, { open_key: 'fresh-value' }, pair());
298+
299+
for (const id of ['c2', 'c3']) {
300+
expect(isSecretRef(stored(id).open_key)).toBe(true);
301+
expect(opens(stored(id).open_key)).toBe('fresh-value');
302+
}
303+
expect(drops).toEqual([]);
304+
});
305+
306+
it('control: a value a hook writes on a locked secret is kept', async () => {
307+
// Every matched row's handler writes the same keys: a predicate update
308+
// has one payload for all of them.
309+
engine.registerHook('beforeUpdate', async (ctx: any) => {
310+
if (ctx.input.data.name === 'pair') {
311+
ctx.input.data.state_key = 'hook-state';
312+
ctx.input.data.fixed_key = 'hook-fixed';
313+
}
314+
}, { object: CRED });
315+
316+
await engine.update(CRED, { name: 'pair' }, pair());
317+
318+
for (const id of ['c2', 'c3']) {
319+
expect(opens(stored(id).state_key)).toBe('hook-state');
320+
expect(opens(stored(id).fixed_key)).toBe('hook-fixed');
321+
}
322+
expect(drops).toEqual([]);
323+
});
324+
});
325+
});

0 commit comments

Comments
 (0)