Skip to content

Commit 3f1c837

Browse files
committed
fix(metadata-protocol): a revert or a publish writes a connector's live row without the keys a save drains
A revert to a history version and the publish of a stored draft now write the live row without the positions a save of the served form drains (a connector's undeclared auth keys and undeclared retryConfig keys), using the helper history snapshots use. Every other body is written as before. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5mgePB9NQ4PNhvYVxk
1 parent 07559ce commit 3f1c837

5 files changed

Lines changed: 520 additions & 6 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): a revert or a publish writes a connector's live row without the keys a save drains
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A revert to a history version (`rollbackMetaItem`, commit revert) and the publish of a stored draft (`publishMetaItem`) now write the live `sys_metadata` row without the positions a save of the served form drains: a connector's undeclared `auth` keys and the undeclared keys of an object `retryConfig`.
11+
12+
- `SysMetadataRepository.restoreVersion` and `promoteDraft` remove those positions from the stored body with the same helper history snapshots use (`historySnapshotBody`), before `deriveRestoredBody` / `deriveActiveBody` see it, so the body a caller judges is the body written.
13+
- Every other type, and a connector with nothing undeclared, is restored and published exactly as before.
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The LIVE `sys_metadata` row a revert (`restoreVersion`) or a publish
5+
* (`promoteDraft`) writes carries no position the type's redactor marks
6+
* withheld AND not carried forward: a connector's undeclared `auth` keys and
7+
* the undeclared keys of an object `retryConfig`, the positions a save of the
8+
* served form drains.
9+
*
10+
* The placeholders below are fixture strings, not credentials.
11+
*/
12+
13+
import { describe, it, expect, beforeEach } from 'vitest';
14+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core';
15+
import { SysMetadataRepository } from './sys-metadata-repository.js';
16+
17+
interface Row { [k: string]: unknown }
18+
19+
const LEGACY_AUTH_VALUE = 'TEST_PLACEHOLDER_LEGACY_AUTH_VALUE';
20+
21+
/** Minimal engine fake that stores exactly what it is handed (the recorded-by suite's shape). */
22+
function makeFakeEngine() {
23+
const rows = new Map<string, Row>();
24+
const historyRows: Row[] = [];
25+
26+
const keyOf = (w: Record<string, unknown>) =>
27+
`${String(w.type)}|${String(w.name)}|${String(w.organization_id ?? 'null')}|${String(w.state ?? 'active')}`;
28+
29+
const findRow = (where: Record<string, unknown>) => {
30+
if (where.id !== undefined) {
31+
for (const [k, r] of rows) if (r.id === where.id) return { key: k, row: r };
32+
return null;
33+
}
34+
const k = keyOf(where);
35+
const r = rows.get(k);
36+
return r ? { key: k, row: r } : null;
37+
};
38+
39+
const matchesHistory = (h: Row, where: Record<string, unknown>): boolean =>
40+
Object.entries(where).every(([k, v]) => {
41+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
42+
return v === undefined || h[k] === v;
43+
});
44+
45+
return {
46+
rows,
47+
historyRows,
48+
async find(table: string, opts: { where: Record<string, unknown>; limit?: number }) {
49+
const found = table === 'sys_metadata_history'
50+
? historyRows.filter((h) => matchesHistory(h, opts.where))
51+
: Array.from(rows.values()).filter((r) => {
52+
if (opts.where.type && r.type !== opts.where.type) return false;
53+
if (opts.where.organization_id !== undefined && r.organization_id !== opts.where.organization_id) return false;
54+
if (opts.where.state && r.state !== opts.where.state) return false;
55+
return true;
56+
});
57+
// The caller's bound, applied after the filter (check:objectql-double-limit).
58+
return typeof opts?.limit === 'number' ? found.slice(0, opts.limit) : found;
59+
},
60+
async findOne(table: string, opts: { where: Record<string, unknown> }) {
61+
assertEngineFindOnePredicate(table, opts);
62+
if (table === 'sys_metadata_history') return historyRows.find((h) => matchesHistory(h, opts.where)) ?? null;
63+
return findRow(opts.where)?.row ?? null;
64+
},
65+
async insert(table: string, data: Record<string, unknown>) {
66+
if (table === 'sys_metadata_history') {
67+
const h: Row = { ...data };
68+
if (!h.id) h.id = `h_${historyRows.length + 1}`;
69+
historyRows.push(h);
70+
return { id: h.id as string };
71+
}
72+
const k = keyOf(data);
73+
const row: Row = { id: `r_${rows.size + 1}`, ...data };
74+
rows.set(k, row);
75+
return { id: row.id as string };
76+
},
77+
async update(_t: string, data: Record<string, unknown>, opts: { where: Record<string, unknown> }) {
78+
assertEngineUpdateDispatch(data, opts);
79+
const found = findRow(opts.where);
80+
if (!found) throw new Error('not found');
81+
rows.set(found.key, { ...found.row, ...data });
82+
return { id: found.row.id as string };
83+
},
84+
async delete(_t: string, opts: { where: Record<string, unknown> }) {
85+
assertEngineDeleteDispatch(opts);
86+
const found = findRow(opts.where);
87+
if (!found) return { deleted: 0 };
88+
rows.delete(found.key);
89+
return { deleted: 1 };
90+
},
91+
async transaction<T>(cb: (ctx: any, info: { owned: boolean }) => Promise<T>): Promise<T> { return cb(undefined, { owned: true }); },
92+
};
93+
}
94+
95+
/** A connector whose `auth` holds a key its `bearer` kind does not declare. */
96+
function legacyConnector(label = 'Vendor API'): Row {
97+
return {
98+
name: 'vendor_api',
99+
label,
100+
type: 'api',
101+
provider: 'rest',
102+
// A DECLARED credential position (withheld on read, carried forward on save): kept in history.
103+
providerConfig: { baseUrl: 'https://api.vendor.example/v1', headers: { Accept: 'application/json' } },
104+
auth: { type: 'bearer', credentialRef: 'VENDOR_API_TOKEN', token: LEGACY_AUTH_VALUE },
105+
};
106+
}
107+
108+
const DECLARED_AUTH = { type: 'bearer', credentialRef: 'VENDOR_API_TOKEN' };
109+
const RETRY_VALUE = 'TEST_PLACEHOLDER_RETRY_VALUE';
110+
111+
describe('a revert or a publish writes no drained connector key to the live row', () => {
112+
let engine: ReturnType<typeof makeFakeEngine>;
113+
let repo: SysMetadataRepository;
114+
// `connector` is not in the repository's typed `MetaRef` union; the protocol
115+
// builds its refs the same way.
116+
const ref = { org: 'org_alpha', type: 'connector', name: 'vendor_api' } as unknown as Parameters<SysMetadataRepository['put']>[0];
117+
118+
beforeEach(() => {
119+
engine = makeFakeEngine();
120+
repo = new SysMetadataRepository({ engine, orgLabel: 'org_alpha' });
121+
});
122+
123+
const liveRow = (state: 'active' | 'draft' = 'active'): Row | undefined =>
124+
Array.from(engine.rows.values()).find((r) => r.type === 'connector' && r.name === 'vendor_api' && (r.state ?? 'active') === state);
125+
const liveBody = (state: 'active' | 'draft' = 'active'): Row => JSON.parse(liveRow(state)!.metadata as string) as Row;
126+
127+
/** Two versions; version 1's snapshot set to `legacy`. */
128+
async function twoVersionsWithLegacyFirst(legacy: Row): Promise<void> {
129+
const first = await repo.put(ref, legacy, { parentVersion: null, actor: null, intent: 'runtime-only' });
130+
const { auth: _a, retryConfig: _r, ...rest } = legacy;
131+
await repo.put(ref, { ...rest, auth: { ...DECLARED_AUTH }, label: 'Vendor API (drained)' }, {
132+
parentVersion: first.version, actor: null, intent: 'runtime-only',
133+
});
134+
engine.historyRows.find((h) => h.version === 1)!.metadata = JSON.stringify(legacy);
135+
}
136+
137+
it('a revert to a version that holds an undeclared `auth` key writes the live row without it', async () => {
138+
await twoVersionsWithLegacyFirst(legacyConnector());
139+
140+
await repo.restoreVersion(ref, 1, { actor: null, intent: 'runtime-only' });
141+
142+
expect(liveRow()!.metadata as string).not.toContain(LEGACY_AUTH_VALUE);
143+
expect(liveBody().auth).toEqual(DECLARED_AUTH);
144+
expect(liveBody().label).toBe('Vendor API');
145+
});
146+
147+
it('a revert to a version that holds an undeclared `retryConfig` key writes the live row without it', async () => {
148+
await twoVersionsWithLegacyFirst({ ...legacyConnector(), retryConfig: { maxAttempts: 3, secret: RETRY_VALUE } });
149+
150+
await repo.restoreVersion(ref, 1, { actor: null, intent: 'runtime-only' });
151+
152+
expect(liveRow()!.metadata as string).not.toContain(RETRY_VALUE);
153+
expect(liveBody().retryConfig).toEqual({ maxAttempts: 3 });
154+
});
155+
156+
it('the body a revert hands `deriveRestoredBody` is the one it writes: without the key', async () => {
157+
await twoVersionsWithLegacyFirst(legacyConnector());
158+
const seen: unknown[] = [];
159+
160+
await repo.restoreVersion(ref, 1, {
161+
actor: null,
162+
intent: 'runtime-only',
163+
deriveRestoredBody: (body) => { seen.push(body); return body; },
164+
});
165+
166+
expect(seen).toHaveLength(1);
167+
expect(JSON.stringify(seen[0])).not.toContain(LEGACY_AUTH_VALUE);
168+
expect(liveRow()!.metadata as string).not.toContain(LEGACY_AUTH_VALUE);
169+
});
170+
171+
it('a publish of a stored draft that holds an undeclared `auth` key writes the live row without it', async () => {
172+
await repo.put(ref, legacyConnector(), { parentVersion: null, actor: null, intent: 'runtime-only', state: 'draft' });
173+
// The stored draft row holds the key.
174+
expect(liveRow('draft')!.metadata as string).toContain(LEGACY_AUTH_VALUE);
175+
176+
await repo.promoteDraft(ref, { actor: null, intent: 'runtime-only' });
177+
178+
expect(liveRow()!.metadata as string).not.toContain(LEGACY_AUTH_VALUE);
179+
expect(liveBody().auth).toEqual(DECLARED_AUTH);
180+
expect(liveRow('draft')).toBeUndefined();
181+
});
182+
183+
it('CONTROL: a revert of a connector with nothing undeclared writes the version exactly', async () => {
184+
const { auth: _a, ...rest } = legacyConnector();
185+
const clean = { ...rest, auth: { ...DECLARED_AUTH } };
186+
const first = await repo.put(ref, clean, { parentVersion: null, actor: null, intent: 'runtime-only' });
187+
await repo.put(ref, { ...clean, label: 'Vendor API (edited)' }, { parentVersion: first.version, actor: null, intent: 'runtime-only' });
188+
189+
await repo.restoreVersion(ref, 1, { actor: null, intent: 'runtime-only' });
190+
191+
expect(liveRow()!.metadata).toBe(JSON.stringify(clean));
192+
});
193+
194+
it('CONTROL: a publish of another type\'s draft writes the draft body byte for byte', async () => {
195+
const viewRef = { org: 'org_alpha', type: 'view' as const, name: 'case_grid' };
196+
const body = { name: 'case_grid', label: 'Cases', object: 'case', columns: [{ field: 'name' }], extra: { anything: 'kept' } };
197+
await repo.put(viewRef, body, { parentVersion: null, actor: null, intent: 'runtime-only', state: 'draft' });
198+
199+
await repo.promoteDraft(viewRef, { actor: null, intent: 'runtime-only' });
200+
201+
const active = Array.from(engine.rows.values()).find((r) => r.type === 'view' && (r.state ?? 'active') === 'active')!;
202+
expect(active.metadata).toBe(JSON.stringify(body));
203+
});
204+
});

‎packages/metadata-protocol/src/sys-metadata-repository.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,9 +1522,10 @@ export class SysMetadataRepository implements MetadataRepository {
15221522
* source), so a publish stores what an active save of the same body
15231523
* would. Return the argument unchanged when there is nothing to derive.
15241524
*
1525-
* Omitted → the draft body is promoted byte for byte, as before. The
1526-
* draft row is still drained by its OWN hash: the derivation changes
1527-
* what lands in `active`, never which draft is consumed.
1525+
* It is handed the draft body without the positions a save drains
1526+
* (`historySnapshotBody`). Omitted → that body is promoted byte for
1527+
* byte. The draft row is still drained by its OWN hash: the derivation
1528+
* changes what lands in `active`, never which draft is consumed.
15281529
*/
15291530
deriveActiveBody?: (draftBody: unknown) => unknown;
15301531
/**
@@ -1605,7 +1606,12 @@ export class SysMetadataRepository implements MetadataRepository {
16051606
// [#23495] The scope written is `activePackageId`: the draft's own binding,
16061607
// or the package an unbound draft is adopted into.
16071608
const currentActive = await this.get(ref, { state: 'active', packageId: activePackageId, member: opts.member });
1608-
const activeBody = opts.deriveActiveBody ? opts.deriveActiveBody(draft.body) : draft.body;
1609+
// The active row a publish writes carries no position a save drains (the
1610+
// type's redactor marks it withheld AND not carried forward): the same
1611+
// removal a history snapshot gets (`historySnapshotBody`), by reference
1612+
// when there is none.
1613+
const promotable = historySnapshotBody(ref.type, draft.body);
1614+
const activeBody = opts.deriveActiveBody ? opts.deriveActiveBody(promotable) : promotable;
16091615
const result = await this.put(ref, activeBody, {
16101616
parentVersion: currentActive?.hash ?? null,
16111617
actor: opts.actor,
@@ -1682,7 +1688,9 @@ export class SysMetadataRepository implements MetadataRepository {
16821688
* judges read the store. Awaited before the active row is read and
16831689
* before the put, so a refused version writes nothing.
16841690
*
1685-
* Omitted → the history body is restored byte for byte, as before.
1691+
* It is handed the history body without the positions a save drains
1692+
* (`historySnapshotBody`). Omitted → that body is restored byte for
1693+
* byte.
16861694
*/
16871695
deriveRestoredBody?: (historyBody: unknown) => unknown | Promise<unknown>;
16881696
/**
@@ -1740,7 +1748,12 @@ export class SysMetadataRepository implements MetadataRepository {
17401748
err.status = 404;
17411749
throw err;
17421750
}
1743-
const body = opts.deriveRestoredBody ? await opts.deriveRestoredBody(historyBody) : historyBody;
1751+
// The live row a revert writes carries no position a save drains: the
1752+
// same removal a history snapshot gets (`historySnapshotBody`), applied
1753+
// before `deriveRestoredBody` so the body it judges is the body written,
1754+
// by reference when there is none.
1755+
const restorable = historySnapshotBody(ref.type, historyBody);
1756+
const body = opts.deriveRestoredBody ? await opts.deriveRestoredBody(restorable) : restorable;
17441757
// ADR-0048 / #6215 — read the RAW active row, not just its body, and carry
17451758
// its `package_id` into the write. `put` upserts exactly ONE row and scopes
17461759
// its optimistic-lock lookup by package; an unstated `packageId` resolves to

0 commit comments

Comments
 (0)