Skip to content

Commit ff6bdac

Browse files
committed
fix(objectql): a non-system write to a secret field may only seal a new value or keep its own record's ref
Claude-Session: https://claude.ai/code/session_01L6bhgUCizoYWQVJWjhdR6F Co-authored-by: Claude <noreply@anthropic.com>
1 parent bf7eff9 commit ff6bdac

4 files changed

Lines changed: 105 additions & 6 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a non-system write to a `secret` field may only seal a new value or keep its own record's reference (#27582)
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **The rule.** A `secret` field value that starts with `secret:` is read as a reference to a credential already stored, not as a credential. From any caller but the system principal, such a value is now accepted only when it is the reference that record's column already holds: on an update, every record the write lands on must already hold exactly that value, and the column is then left as it is, as an echoed read mask is. A create has no reference of its own, so it never takes one. Any other reference is refused with `VALIDATION_ERROR` / 400 before anything is written, and the answer is the same whatever the reference names.
11+
- **Every engine write door.** The single and batch create, `insertMany` (the refused row is reported on its own and the others land), the by-id update and the predicate update, and so every REST door that writes through them (create, bulk, import, update).
12+
- **Unchanged.** The system principal (`isSystem: true`: seed replay, migration) still stores such a value as given. A new value is sealed as before, `null` clears, the echoed mask changes nothing, and reads still mask.

‎packages/objectql/src/engine-secret-internal-fields.ts‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@
2222
* handle once a write that did not land, or a committed one that moved the
2323
* column off it, has left it unreferenced.
2424
*
25+
* [#27582] And one on the value already spelled as a ref: a non-system write
26+
* may only seal a new value or keep its own record's ref. `encryptSecretFields`
27+
* takes the write's own stored rows ({@link StoredRowsReader}) and refuses any
28+
* other ref with {@link SecretRefWriteError}; the system principal keeps the
29+
* pass-through.
30+
*
2531
* ## How the moved bodies reach the class
2632
*
2733
* The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts`
@@ -105,17 +111,66 @@ export interface SecretHandleSlot {
105111
readonly handleId: string;
106112
}
107113

114+
/**
115+
* [#27582] The rows a write's own record(s) hold in storage now, read for one
116+
* question: is a ref on a non-system payload the value that record's column
117+
* already holds? Each call site says what its own rows are — none for an
118+
* insert (a new record holds no ref of its own), the pre-image for a by-id
119+
* update, the matched rows for a predicate update — and the reader is called
120+
* only when a non-system payload carries a ref, so every other write reads
121+
* nothing more than it did.
122+
*/
123+
export type StoredRowsReader = () => Promise<readonly (Record<string, unknown> | null | undefined)[] | null>;
124+
125+
/**
126+
* [#27582] The ADR-0112 pair carried by the refusal of a ref that is not the
127+
* record's own. `VALIDATION_ERROR` / 400 is the standard-catalog member the
128+
* sibling credential refusals use (`EMPTY_CREDENTIAL_REFUSAL_CODE`): the
129+
* payload is wrong and the caller can fix it, so no ledger registration is
130+
* needed.
131+
*/
132+
export const SECRET_REF_WRITE_REFUSAL_CODE = 'VALIDATION_ERROR';
133+
export const SECRET_REF_WRITE_REFUSAL_STATUS = 400;
134+
135+
/**
136+
* [#27582] Refusal of a `secret:` ref on a non-system write that is not the
137+
* value the record's own column already holds. Fail closed, with one answer:
138+
* the message names the column and never the ref, and nothing about the handle
139+
* the ref names is looked up, so the answer is the same whatever it names.
140+
*/
141+
export class SecretRefWriteError extends Error {
142+
readonly code = SECRET_REF_WRITE_REFUSAL_CODE;
143+
readonly status = SECRET_REF_WRITE_REFUSAL_STATUS;
144+
/** The same number under ADR-0112 D5's spelling, as `EmptyCredentialWriteError` carries it. */
145+
readonly httpStatus = SECRET_REF_WRITE_REFUSAL_STATUS;
146+
readonly object: string;
147+
readonly field: string;
148+
constructor(object: string, field: string) {
149+
super(
150+
`Stored-reference value refused for secret field "${object}.${field}": a value that starts with "secret:" `
151+
+ 'is read as a reference to a credential already stored, not as a credential, and a write may only keep '
152+
+ 'the reference this record already holds. To set the secret, send its value; to clear it, write null; '
153+
+ 'to leave it unchanged, omit the field. Nothing was written.',
154+
);
155+
this.name = 'SecretRefWriteError';
156+
this.object = object;
157+
this.field = field;
158+
}
159+
}
160+
108161
/** The body of `ObjectQL#encryptSecretFields`; the method's docblock there is its contract. */
109162
export async function encryptSecretFields(
110163
this: Pick<SecretInternalFieldsHost, '_registry' | 'cryptoProvider' | 'getDriver'>,
111164
object: string,
112165
row: Record<string, unknown>,
113166
context: ExecutionContext | undefined,
114167
driverOptions: unknown,
168+
storedRows: StoredRowsReader,
115169
): Promise<PendingSecretRow[]> {
116170
const pending: PendingSecretRow[] = [];
117171
if (!row || typeof row !== 'object') return pending;
118172
const schema = this._registry.getObject(object);
173+
let ownRows: readonly (Record<string, unknown> | null | undefined)[] | undefined;
119174

120175
// Echoed-mask drop for every field the read path masks (secret + generic
121176
// password). The read path returns SECRET_MASK; a client that PATCHes it
@@ -140,7 +195,22 @@ export async function encryptSecretFields(
140195
// on the payload, so it must not depend on whether a CryptoProvider or
141196
// sys_secret store happens to be wired.
142197
if (value === '') throw new EmptyCredentialWriteError(object, field, 'secret');
143-
if (isSecretRef(value)) continue; // already encrypted ref
198+
if (isSecretRef(value)) {
199+
// The system principal's ref passes through as it always has: a system
200+
// writer may copy a ref on purpose (seed replay, migration).
201+
if (context?.isSystem === true) continue;
202+
// [#27582] A non-system write may only seal a new value or keep its own
203+
// record's ref: every row this write lands on must already hold exactly
204+
// this value in this column. A write with no own row (an insert, a
205+
// predicate that matches nothing) has nothing to keep. Kept, the key is
206+
// dropped, as the echoed mask is: the column is not rewritten at all, so
207+
// the verdict cannot go stale before the statement runs.
208+
ownRows ??= (await storedRows()) ?? [];
209+
const keepsOwn = ownRows.length > 0 && ownRows.every((own) => own?.[field] === value);
210+
if (!keepsOwn) throw new SecretRefWriteError(object, field);
211+
delete row[field];
212+
continue;
213+
}
144214

145215
if (!this.cryptoProvider) {
146216
throw new Error(

‎packages/objectql/src/engine.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ import {
123123
stripSearchCompanionFromRead,
124124
type PendingSecretRow,
125125
type SecretHandleSlot,
126+
type StoredRowsReader,
126127
} from './engine-secret-internal-fields.js';
127128
// [#25522 cut 6] The predicate-write hook dispatch bodies; the methods of the
128129
// same names below hand each body the members it reads (`HookDispatchHost`).
@@ -10570,7 +10571,16 @@ export class ObjectQL implements IObjectQLEngine {
1057010571
* (maintainer ruling 2026-08-13 on #8559). The `password` half of the same
1057110572
* ruling lands at its own seam — {@link refuseEmptyPasswordFields} — since
1057210573
* the two types share the read mask but not this encryption path.
10573-
* - Secret value already a ref (re-save of an unchanged ref) ⇒ left as-is.
10574+
* - Secret value already a ref ⇒ [#27582] a non-system write may only seal
10575+
* a new value or keep its own record's ref. From the system principal
10576+
* (`context.isSystem === true`) it is left as-is, as it always was. From
10577+
* any other caller it is kept only when every row the write lands on
10578+
* already holds exactly that ref in that column — read from `storedRows`,
10579+
* which each call site supplies (none for an insert, the pre-image for a
10580+
* by-id update, the matched rows for a predicate update) — and then the
10581+
* key is dropped, as the echoed mask is. Any other ref is REFUSED with
10582+
* {@link SecretRefWriteError} (ADR-0112 `VALIDATION_ERROR`/400), one
10583+
* answer whatever the ref names.
1057410584
* - **Fail-closed:** any other secret value with no CryptoProvider registered,
1057510585
* or no reachable `sys_secret` store, THROWS — never persists cleartext.
1057610586
* (A `password` field needs no CryptoProvider — it is stored as-is.)
@@ -10580,6 +10590,7 @@ export class ObjectQL implements IObjectQLEngine {
1058010590
row: Record<string, unknown>,
1058110591
context: ExecutionContext | undefined,
1058210592
driverOptions: unknown,
10593+
storedRows: StoredRowsReader,
1058310594
): Promise<PendingSecretRow[]> {
1058410595
// [#25522 cut 5] The body moved to `engine-secret-internal-fields.ts` (see `SecretInternalFieldsHost`).
1058510596
const readRegistry = () => this._registry;
@@ -10589,7 +10600,7 @@ export class ObjectQL implements IObjectQLEngine {
1058910600
get cryptoProvider() { return readCryptoProvider(); },
1059010601
getDriver: (...a) => this.getDriver(...a),
1059110602
};
10592-
return encryptSecretFields.call(host, object, row, context, driverOptions);
10603+
return encryptSecretFields.call(host, object, row, context, driverOptions, storedRows);
1059310604
}
1059410605

1059510606
/**
@@ -15355,7 +15366,8 @@ export class ObjectQL implements IObjectQLEngine {
1535515366
// carries the secret-arm refusal). Same try, so partial mode
1535615367
// reports either refusal per-row instead of killing the batch.
1535715368
this.refuseEmptyPasswordFields(object, rows[i]);
15358-
sealedSecrets[i] = await this.encryptSecretFields(object, rows[i], opCtx.context, driverOptions);
15369+
// [#27582] A new record holds no ref of its own: no stored rows.
15370+
sealedSecrets[i] = await this.encryptSecretFields(object, rows[i], opCtx.context, driverOptions, async () => []);
1535915371
} catch (e) {
1536015372
if (!partialMode) throw e;
1536115373
rowErrors[i] = e;
@@ -17007,7 +17019,8 @@ export class ObjectQL implements IObjectQLEngine {
1700717019
// [#8559] Password half of the credential write door, then the
1700817020
// secret channel (which carries the secret-arm refusal).
1700917021
this.refuseEmptyPasswordFields(object, hookContext.input.data as Record<string, unknown>);
17010-
sealedSecrets = await this.encryptSecretFields(object, hookContext.input.data as Record<string, unknown>, opCtx.context, hookContext.input.options);
17022+
// [#27582] This record's own stored row is the pre-image read above.
17023+
sealedSecrets = await this.encryptSecretFields(object, hookContext.input.data as Record<string, unknown>, opCtx.context, hookContext.input.options, async () => [priorRecord]);
1701117024
// [#21663] Scope `'skip'` — the public `validateRecord` IS that
1701217025
// scope: the readonly strip has NOT run yet, so a readonly value
1701317026
// here may be a caller's the strip is about to drop — judged, a
@@ -17404,7 +17417,9 @@ export class ObjectQL implements IObjectQLEngine {
1740417417
// [#8559] Password half of the credential write door, then the
1740517418
// secret channel (which carries the secret-arm refusal).
1740617419
this.refuseEmptyPasswordFields(object, hookContext.input.data as Record<string, unknown>);
17407-
sealedSecrets = await this.encryptSecretFields(object, hookContext.input.data as Record<string, unknown>, opCtx.context, hookContext.input.options);
17420+
// [#27582] The rows this write lands on are the matched rows: the
17421+
// D7 memo, read here only when a non-system payload carries a ref.
17422+
sealedSecrets = await this.encryptSecretFields(object, hookContext.input.data as Record<string, unknown>, opCtx.context, hookContext.input.options, readPriorRows);
1740817423
// [#21663] Scope `'skip'` — the public `validateRecord` IS that
1740917424
// scope: the readonly strip has NOT run yet, so a readonly value
1741017425
// here may be a caller's the strip is about to drop — judged, a

‎packages/objectql/src/error-http-status-spelling.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { DuplicateRecordError } from './duplicate-record-error.js';
3737
import { HookUnscopedDataAccessError } from './hook-run-as.js';
3838
import { MultiUpdateHookKeyDivergenceError } from './multi-update-hook-key-divergence.js';
3939
import { EmptyCredentialWriteError } from './secret-fields.js';
40+
import { SecretRefWriteError } from './engine-secret-internal-fields.js';
4041
import { SystemWriteOrganizationRequiredError } from './tenancy/system-write-organization.js';
4142
import { NamespaceConflictError, ArtifactObjectNameConflictError, ObjectOwnershipConflictError } from './registry.js';
4243
import { invalidFilterError } from './filter-comparand-shape.js';
@@ -52,6 +53,7 @@ const CONSTRUCTED: Array<[string, () => unknown, number]> = [
5253
['HookUnscopedDataAccessError', () => new HookUnscopedDataAccessError({ hook: 'beforeFind', object: 'customer', event: 'beforeFind' }), 403],
5354
['MultiUpdateHookKeyDivergenceError', () => new MultiUpdateHookKeyDivergenceError('customer', ['a', 'b'], 2), 400],
5455
['EmptyCredentialWriteError', () => new EmptyCredentialWriteError('datasource', 'secret_key', 'secret'), 400],
56+
['SecretRefWriteError', () => new SecretRefWriteError('datasource', 'secret_key'), 400],
5557
['SystemWriteOrganizationRequiredError', () => new SystemWriteOrganizationRequiredError('sys_job', 'group', 'walled-posture'), 500],
5658
['NamespaceConflictError', () => new NamespaceConflictError('crm', 'pkg_a', 'pkg_b'), 422],
5759
['ArtifactObjectNameConflictError', () => new ArtifactObjectNameConflictError('customer', 'pkg_a', 'pkg_b'), 422],

0 commit comments

Comments
 (0)