|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#27762] A `datasource` saved through the metadata door may name, in |
| 5 | + * `external.credentialsRef`, only the reference its own stored row already |
| 6 | + * holds. This is the own-reference rule #27582 set for the engine's secret |
| 7 | + * fields and #27722 applied to the datasource admin door's create: a |
| 8 | + * non-system write may only seal a new value or keep its own record's stored |
| 9 | + * reference. The metadata door seals nothing, so its one legal reference is |
| 10 | + * the one it keeps. |
| 11 | + * |
| 12 | + * Pinned at `saveMetaItem`, the one save the REST `PUT /api/v1/meta/:type/:name` |
| 13 | + * door and the runtime dispatcher's `/meta` door both call (`meta-envelope`, |
| 14 | + * `meta-dispatch`), and the in-process doors that write through it: |
| 15 | + * |
| 16 | + * - refused, `VALIDATION_ERROR` / 400, before anything is written: a create |
| 17 | + * naming any reference; an edit naming a reference other than the one its |
| 18 | + * row holds, or naming one where its row holds none; a draft naming one the |
| 19 | + * row it overlays does not hold. One answer whatever the reference names, |
| 20 | + * and the reference is never echoed; |
| 21 | + * - accepted: an edit or a draft that sends back its own stored reference |
| 22 | + * (the GET → edit → PUT round trip), and a body that names none; |
| 23 | + * - the server-stated rewrites (`source` set, the stored-metadata migration) |
| 24 | + * keep their pass-through. |
| 25 | + * |
| 26 | + * Harness: the real write path over a stub engine, the shape of |
| 27 | + * `protocol.metadata-redaction.test.ts`; every row is seeded directly. |
| 28 | + */ |
| 29 | +import { describe, expect, it } from 'vitest'; |
| 30 | +// [#5619] The producer's own dispatch decisions, so the stub cannot accept a call ObjectQL refuses. |
| 31 | +import { assertEngineFindOnePredicate, assertEngineUpdateDispatch, hashSpec } from '@objectstack/metadata-core'; |
| 32 | +import { ObjectStackProtocolImplementation } from './protocol.js'; |
| 33 | +import type { MetadataWriteFace } from './protocol.js'; |
| 34 | + |
| 35 | +interface Row { |
| 36 | + id: string; |
| 37 | + type: string; |
| 38 | + name: string; |
| 39 | + organization_id: string | null; |
| 40 | + package_id: string | null; |
| 41 | + state: string; |
| 42 | + metadata: string; |
| 43 | + checksum?: string; |
| 44 | + version?: number; |
| 45 | +} |
| 46 | + |
| 47 | +/** [#24371] One `where` value as the store reads it: `{ $in: [...] }` or equality. */ |
| 48 | +const whereValueMatches = (actual: unknown, want: unknown): boolean => |
| 49 | + want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in) |
| 50 | + ? (want as { $in: unknown[] }).$in.includes(actual) |
| 51 | + : actual === want; |
| 52 | + |
| 53 | +const matches = (r: Row, where: Record<string, unknown>): boolean => |
| 54 | + Object.entries(where).every(([k, v]) => v === undefined || whereValueMatches((r as any)[k], v)); |
| 55 | + |
| 56 | +const keyOf = (w: Record<string, unknown>) => |
| 57 | + `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; |
| 58 | + |
| 59 | +/** A stub engine over one `sys_metadata` map, logging every write it is asked for. */ |
| 60 | +function makeStubEngine() { |
| 61 | + const rows = new Map<string, Row>(); |
| 62 | + const writes: string[] = []; |
| 63 | + let nextId = 0; |
| 64 | + const findRow = (w: Record<string, unknown>) => { |
| 65 | + for (const [k, r] of rows) if (matches(r, w)) return { key: k, row: r }; |
| 66 | + return null; |
| 67 | + }; |
| 68 | + const engine: any = { |
| 69 | + async findOne(table: string, opts: { where: Record<string, unknown> }) { |
| 70 | + assertEngineFindOnePredicate(table, opts); |
| 71 | + return findRow(opts.where)?.row ?? null; |
| 72 | + }, |
| 73 | + async find(_table: string, opts: { where: Record<string, unknown> }) { |
| 74 | + return Array.from(rows.values()).filter((r) => matches(r, opts.where)); |
| 75 | + }, |
| 76 | + async insert(table: string, data: Record<string, unknown>) { |
| 77 | + writes.push(`insert ${table}`); |
| 78 | + if (table !== 'sys_metadata') return { id: 'side_table' }; |
| 79 | + const row = { id: `r_${++nextId}`, ...(data as any) } as Row; |
| 80 | + rows.set(keyOf(data), row); |
| 81 | + return { id: row.id }; |
| 82 | + }, |
| 83 | + async update(table: string, data: Record<string, unknown>, opts: { where: Record<string, unknown> }) { |
| 84 | + assertEngineUpdateDispatch(data, opts); |
| 85 | + writes.push(`update ${table}`); |
| 86 | + if (table !== 'sys_metadata') return { id: null }; |
| 87 | + const found = findRow(opts.where); |
| 88 | + if (!found) return { id: null }; |
| 89 | + const merged = { ...found.row, ...(data as any) }; |
| 90 | + rows.delete(found.key); |
| 91 | + rows.set(keyOf(merged), merged); |
| 92 | + return { id: found.row.id }; |
| 93 | + }, |
| 94 | + async transaction<T>(cb: (ctx: any, info: { owned: boolean }) => Promise<T>): Promise<T> { |
| 95 | + return cb(undefined, { owned: true }); |
| 96 | + }, |
| 97 | + async syncObjectSchema() { /* no DDL in this stub */ }, |
| 98 | + registry: { |
| 99 | + listItems: () => [], |
| 100 | + isPackageDisabled: () => false, |
| 101 | + getItem: () => undefined, |
| 102 | + registerItem: () => {}, |
| 103 | + registerObject: () => {}, |
| 104 | + getPackage: () => undefined, |
| 105 | + }, |
| 106 | + }; |
| 107 | + return { engine, rows, writes }; |
| 108 | +} |
| 109 | + |
| 110 | +/** A schema-valid datasource body, so every refusal below is this rule's and never a 422. */ |
| 111 | +const datasourceBody = (name: string, label: string, credentialsRef?: string) => ({ |
| 112 | + name, |
| 113 | + label, |
| 114 | + driver: 'postgres', |
| 115 | + config: { host: 'db.internal', database: name, username: 'app' }, |
| 116 | + ...(credentialsRef === undefined ? {} : { external: { credentialsRef } }), |
| 117 | +}); |
| 118 | + |
| 119 | +/** The reference `ledger`'s own row holds. */ |
| 120 | +const OWN_REF = 'sys_secret:ledger_own_27762'; |
| 121 | +/** The reference another datasource's row (`vault`) holds. */ |
| 122 | +const OTHER_REF = 'sys_secret:vault_own_27762'; |
| 123 | +/** A reference no row holds. */ |
| 124 | +const UNHELD_REF = 'sys_secret:held_by_no_row_27762'; |
| 125 | + |
| 126 | +function seed(rows: Map<string, Row>, name: string, credentialsRef?: string) { |
| 127 | + const where = { type: 'datasource', name, organization_id: null, package_id: null, state: 'active' }; |
| 128 | + const body = datasourceBody(name, name, credentialsRef); |
| 129 | + rows.set(keyOf(where), { |
| 130 | + id: `r_seed_${name}`, |
| 131 | + ...where, |
| 132 | + metadata: JSON.stringify(body), |
| 133 | + // A real row carries its own checksum, which the save's parent read compares. |
| 134 | + checksum: hashSpec(body), |
| 135 | + version: 1, |
| 136 | + }); |
| 137 | +} |
| 138 | + |
| 139 | +/** `ledger` holds its own reference, `vault` another, `plain` none. */ |
| 140 | +function session() { |
| 141 | + const stub = makeStubEngine(); |
| 142 | + seed(stub.rows, 'ledger', OWN_REF); |
| 143 | + seed(stub.rows, 'vault', OTHER_REF); |
| 144 | + seed(stub.rows, 'plain'); |
| 145 | + return { ...stub, protocol: new ObjectStackProtocolImplementation(stub.engine) }; |
| 146 | +} |
| 147 | + |
| 148 | +const rowOf = (rows: Map<string, Row>, name: string, state: 'active' | 'draft' = 'active') => |
| 149 | + Array.from(rows.values()).find((r) => r.type === 'datasource' && r.name === name && r.state === state); |
| 150 | + |
| 151 | +const storedRefOf = (rows: Map<string, Row>, name: string, state: 'active' | 'draft' = 'active') => { |
| 152 | + const row = rowOf(rows, name, state); |
| 153 | + return row ? JSON.parse(row.metadata).external?.credentialsRef : undefined; |
| 154 | +}; |
| 155 | + |
| 156 | +/** The store as a comparable value, so "nothing was written" is a reading, not a claim. */ |
| 157 | +const snapshot = (rows: Map<string, Row>) => JSON.stringify(Array.from(rows.entries()).sort()); |
| 158 | + |
| 159 | +/** Runs a save expected to be refused; returns the refusal after asserting nothing was written. */ |
| 160 | +async function refused( |
| 161 | + s: ReturnType<typeof session>, |
| 162 | + request: Parameters<ObjectStackProtocolImplementation['saveMetaItem']>[0], |
| 163 | +): Promise<{ code: unknown; status: unknown; message: string }> { |
| 164 | + const before = snapshot(s.rows); |
| 165 | + const writesBefore = s.writes.length; |
| 166 | + let caught: any; |
| 167 | + try { |
| 168 | + await s.protocol.saveMetaItem(request); |
| 169 | + } catch (err) { |
| 170 | + caught = err; |
| 171 | + } |
| 172 | + expect(caught, 'the save was accepted').toBeDefined(); |
| 173 | + expect(snapshot(s.rows)).toBe(before); |
| 174 | + expect(s.writes.slice(writesBefore)).toEqual([]); |
| 175 | + return { code: caught.code, status: caught.status, message: String(caught.message) }; |
| 176 | +} |
| 177 | + |
| 178 | +const expectRuleRefusal = (r: { code: unknown; status: unknown; message: string }) => { |
| 179 | + expect({ code: r.code, status: r.status }, r.message).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); |
| 180 | + for (const ref of [OWN_REF, OTHER_REF, UNHELD_REF]) expect(r.message).not.toContain(ref); |
| 181 | +}; |
| 182 | + |
| 183 | +describe('[#27762] datasource `external.credentialsRef`: a non-system save may only keep its own stored reference', () => { |
| 184 | + describe('refused before anything is written, with one answer whatever the reference names', () => { |
| 185 | + it('a create naming a reference another datasource holds, and one naming a reference no row holds', async () => { |
| 186 | + const s = session(); |
| 187 | + const other = await refused(s, { type: 'datasource', name: 'fresh', item: datasourceBody('fresh', 'Fresh', OTHER_REF) }); |
| 188 | + const unheld = await refused(s, { type: 'datasource', name: 'fresh', item: datasourceBody('fresh', 'Fresh', UNHELD_REF) }); |
| 189 | + expectRuleRefusal(other); |
| 190 | + expect(unheld).toEqual(other); |
| 191 | + expect(rowOf(s.rows, 'fresh')).toBeUndefined(); |
| 192 | + }); |
| 193 | + |
| 194 | + it('an edit naming a reference other than the one its own row holds', async () => { |
| 195 | + const s = session(); |
| 196 | + const other = await refused(s, { type: 'datasource', name: 'ledger', item: datasourceBody('ledger', 'Ledger', OTHER_REF) }); |
| 197 | + const unheld = await refused(s, { type: 'datasource', name: 'ledger', item: datasourceBody('ledger', 'Ledger', UNHELD_REF) }); |
| 198 | + expectRuleRefusal(other); |
| 199 | + expect(unheld).toEqual(other); |
| 200 | + expect(storedRefOf(s.rows, 'ledger')).toBe(OWN_REF); |
| 201 | + }); |
| 202 | + |
| 203 | + it('an edit naming a reference where its own row holds none', async () => { |
| 204 | + const s = session(); |
| 205 | + expectRuleRefusal(await refused(s, { type: 'datasource', name: 'plain', item: datasourceBody('plain', 'Plain', OTHER_REF) })); |
| 206 | + expect(storedRefOf(s.rows, 'plain')).toBeUndefined(); |
| 207 | + }); |
| 208 | + |
| 209 | + it('a draft naming a reference the active row it overlays does not hold', async () => { |
| 210 | + const s = session(); |
| 211 | + expectRuleRefusal(await refused(s, { |
| 212 | + type: 'datasource', name: 'ledger', mode: 'draft', item: datasourceBody('ledger', 'Ledger', OTHER_REF), |
| 213 | + })); |
| 214 | + expect(rowOf(s.rows, 'ledger', 'draft')).toBeUndefined(); |
| 215 | + }); |
| 216 | + |
| 217 | + it('a reference with the plural type spelling is judged the same', async () => { |
| 218 | + const s = session(); |
| 219 | + expectRuleRefusal(await refused(s, { type: 'datasources', name: 'fresh', item: datasourceBody('fresh', 'Fresh', OTHER_REF) })); |
| 220 | + }); |
| 221 | + |
| 222 | + const faces: Array<{ face: string; extra: { writeFace?: MetadataWriteFace; surface?: 'mcp' | 'studio' } }> = [ |
| 223 | + { face: 'the REST `PUT` door (`meta-envelope`)', extra: { writeFace: 'meta-envelope' } }, |
| 224 | + { face: 'the runtime dispatcher\'s `/meta` door (`meta-dispatch`)', extra: { writeFace: 'meta-dispatch' } }, |
| 225 | + { face: 'the package copy (`package-duplicate`)', extra: { writeFace: 'package-duplicate' } }, |
| 226 | + { face: 'the unmanaged import (`package-unmanaged-import`)', extra: { writeFace: 'package-unmanaged-import' } }, |
| 227 | + { face: 'an MCP save', extra: { surface: 'mcp' } }, |
| 228 | + ]; |
| 229 | + for (const { face, extra } of faces) { |
| 230 | + it(`on ${face}`, async () => { |
| 231 | + const s = session(); |
| 232 | + expectRuleRefusal(await refused(s, { |
| 233 | + type: 'datasource', name: 'fresh', item: datasourceBody('fresh', 'Fresh', OTHER_REF), ...extra, |
| 234 | + })); |
| 235 | + }); |
| 236 | + } |
| 237 | + }); |
| 238 | + |
| 239 | + describe('accepted', () => { |
| 240 | + it('an edit that sends back its own stored reference (the GET → edit → PUT round trip) keeps it', async () => { |
| 241 | + const s = session(); |
| 242 | + const served: any = (await s.protocol.getMetaItem({ type: 'datasource', name: 'ledger' })).item; |
| 243 | + expect(served.external?.credentialsRef).toBe(OWN_REF); |
| 244 | + await s.protocol.saveMetaItem({ type: 'datasource', name: 'ledger', item: { ...served, label: 'Ledger (edited)' } }); |
| 245 | + expect(JSON.parse(rowOf(s.rows, 'ledger')!.metadata).label).toBe('Ledger (edited)'); |
| 246 | + expect(storedRefOf(s.rows, 'ledger')).toBe(OWN_REF); |
| 247 | + }); |
| 248 | + |
| 249 | + it('a first draft that sends back the reference the active row holds keeps it on the draft', async () => { |
| 250 | + const s = session(); |
| 251 | + await s.protocol.saveMetaItem({ |
| 252 | + type: 'datasource', name: 'ledger', mode: 'draft', item: datasourceBody('ledger', 'Ledger (draft)', OWN_REF), |
| 253 | + }); |
| 254 | + expect(storedRefOf(s.rows, 'ledger', 'draft')).toBe(OWN_REF); |
| 255 | + }); |
| 256 | + |
| 257 | + it('a body that names no reference saves as before', async () => { |
| 258 | + const s = session(); |
| 259 | + await s.protocol.saveMetaItem({ type: 'datasource', name: 'fresh', item: datasourceBody('fresh', 'Fresh') }); |
| 260 | + expect(rowOf(s.rows, 'fresh')).toBeDefined(); |
| 261 | + expect(storedRefOf(s.rows, 'fresh')).toBeUndefined(); |
| 262 | + }); |
| 263 | + |
| 264 | + it('a server-stated rewrite (`source: \'migrate-stored\'`) keeps its pass-through', async () => { |
| 265 | + const s = session(); |
| 266 | + await s.protocol.saveMetaItem({ |
| 267 | + type: 'datasource', name: 'plain', item: datasourceBody('plain', 'Plain', OTHER_REF), source: 'migrate-stored', |
| 268 | + }); |
| 269 | + expect(storedRefOf(s.rows, 'plain')).toBe(OTHER_REF); |
| 270 | + }); |
| 271 | + }); |
| 272 | +}); |
0 commit comments