|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#27582] A non-system write may only seal a new value or keep its own |
| 5 | + * record's ref. |
| 6 | + * |
| 7 | + * A `secret` field's stored value is an opaque `secret:` ref. On a write that |
| 8 | + * is not the system principal's, a value already spelled as a ref is accepted |
| 9 | + * only when it is the ref that same record's same column already holds, and |
| 10 | + * then it changes nothing (like the echoed read mask). Any other ref is |
| 11 | + * refused with the ADR-0112 `VALIDATION_ERROR` / 400 pair, before any |
| 12 | + * credential row or record is written, and with one answer whatever the ref |
| 13 | + * names. A system write keeps the pass-through. |
| 14 | + * |
| 15 | + * Driven through a real {@link ObjectQL} over an in-memory stub driver, on |
| 16 | + * every engine write door the credential pass sits on: insert (single, batch |
| 17 | + * and the per-row `insertMany`), the by-id update and the predicate update. |
| 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 { SECRET_MASK, makeSecretRef, parseSecretRef } from './secret-fields.js'; |
| 24 | + |
| 25 | +type Row = Record<string, unknown>; |
| 26 | + |
| 27 | +/** An in-memory stub driver whose stores can be read back directly. */ |
| 28 | +function makeDriver() { |
| 29 | + const stores = new Map<string, Map<string, Row>>(); |
| 30 | + const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!); |
| 31 | + const matches = (row: Row, where: any) => |
| 32 | + !where || Object.entries(where).every(([k, v]) => { |
| 33 | + if (k.startsWith('$')) return true; |
| 34 | + if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]); |
| 35 | + return (row[k] ?? null) === (v ?? null); |
| 36 | + }); |
| 37 | + const copy = (r: Row | undefined) => (r == null ? r : { ...r }); |
| 38 | + let n = 0; |
| 39 | + const driver: any = { |
| 40 | + name: 'memory', version: '0.0.0', supports: {}, |
| 41 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 42 | + async syncSchema() {}, |
| 43 | + async find(o: string, ast: any) { |
| 44 | + const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); |
| 45 | + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; |
| 46 | + return page.map(copy); |
| 47 | + }, |
| 48 | + async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; }, |
| 49 | + async create(o: string, data: Row) { |
| 50 | + const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` }; |
| 51 | + storeFor(o).set(String(row.id), row); |
| 52 | + return copy(row); |
| 53 | + }, |
| 54 | + async update(o: string, id: string, data: Row) { |
| 55 | + const row = { ...storeFor(o).get(String(id)), ...data, id }; |
| 56 | + storeFor(o).set(String(id), row); |
| 57 | + return copy(row); |
| 58 | + }, |
| 59 | + async updateMany(o: string, ast: any, data: Row) { |
| 60 | + let k = 0; |
| 61 | + for (const [id, row] of storeFor(o)) { |
| 62 | + if (!matches(row, ast?.where)) continue; |
| 63 | + storeFor(o).set(id, { ...row, ...data, id }); |
| 64 | + k += 1; |
| 65 | + } |
| 66 | + return k; |
| 67 | + }, |
| 68 | + async delete(o: string, id: string) { return storeFor(o).delete(String(id)); }, |
| 69 | + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, |
| 70 | + async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, |
| 71 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 72 | + async beginTransaction() { return {}; }, async commit() {}, async rollback() {}, |
| 73 | + }; |
| 74 | + return { driver, rowsOf: (o: string) => Array.from(storeFor(o).values()) }; |
| 75 | +} |
| 76 | + |
| 77 | +function makeCrypto(): ICryptoProvider & { encrypts: () => number } { |
| 78 | + let n = 0; |
| 79 | + return { |
| 80 | + encrypts: () => n, |
| 81 | + async encrypt(plain: string): Promise<CryptoHandle> { |
| 82 | + n += 1; |
| 83 | + return { id: `sec_${n}`, kmsKeyId: 'local', alg: 'test-b64', version: 1, ciphertext: Buffer.from(plain).toString('base64') }; |
| 84 | + }, |
| 85 | + async decrypt(handle: CryptoHandle) { return Buffer.from(handle.ciphertext, 'base64').toString('utf8'); }, |
| 86 | + async rotateKey(handle: CryptoHandle) { return handle; }, |
| 87 | + digest(plain: string) { return `d:${plain.length}`; }, |
| 88 | + async keyedDigest(plain: string) { return `k:${plain.length}`; }, |
| 89 | + }; |
| 90 | +} |
| 91 | + |
| 92 | +const sysSecret = { |
| 93 | + name: 'sys_secret', label: 'Secret', systemFields: { tenant: false }, |
| 94 | + fields: { |
| 95 | + id: { name: 'id', type: 'text' }, namespace: { name: 'namespace', type: 'text' }, key: { name: 'key', type: 'text' }, |
| 96 | + kms_key_id: { name: 'kms_key_id', type: 'text' }, alg: { name: 'alg', type: 'text' }, |
| 97 | + version: { name: 'version', type: 'number' }, ciphertext: { name: 'ciphertext', type: 'text' }, |
| 98 | + created_at: { name: 'created_at', type: 'datetime' }, |
| 99 | + }, |
| 100 | +}; |
| 101 | +const VAULT = 'qa_ref_vault'; |
| 102 | +const vault = { |
| 103 | + name: VAULT, label: 'Vault', |
| 104 | + fields: { |
| 105 | + id: { name: 'id', type: 'text' }, |
| 106 | + name: { name: 'name', type: 'text' }, |
| 107 | + tier: { name: 'tier', type: 'text' }, |
| 108 | + token: { name: 'token', type: 'secret' }, |
| 109 | + }, |
| 110 | +}; |
| 111 | + |
| 112 | +const SYSTEM = { context: { isSystem: true } } as any; |
| 113 | +const USER = { context: { isSystem: false, userId: 'u1' } } as any; |
| 114 | +/** A ref spelled like a stored one, naming no `sys_secret` row at all. */ |
| 115 | +const UNKNOWN_REF = makeSecretRef('sec_none'); |
| 116 | + |
| 117 | +describe('[#27582] a non-system write may only seal a new value or keep its own record\'s ref', () => { |
| 118 | + let engine: ObjectQL; |
| 119 | + let d: ReturnType<typeof makeDriver>; |
| 120 | + let crypto: ReturnType<typeof makeCrypto>; |
| 121 | + |
| 122 | + const secrets = () => d.rowsOf('sys_secret'); |
| 123 | + const stored = (id: string) => d.rowsOf(VAULT).find((r) => r.id === id) as Row | undefined; |
| 124 | + const refOf = (id: string) => stored(id)!.token as string; |
| 125 | + const seed = async (id: string, token: string, tier = 'gold') => { |
| 126 | + await engine.insert(VAULT, { id, name: id, tier, token }, SYSTEM); |
| 127 | + return refOf(id); |
| 128 | + }; |
| 129 | + /** The refusal envelope: the ADR-0112 pair and the located column. */ |
| 130 | + const refusal = (field = 'token') => ({ code: 'VALIDATION_ERROR', status: 400, httpStatus: 400, object: VAULT, field }); |
| 131 | + const caught = (p: Promise<unknown>) => p.then(() => null, (e: unknown) => e as Error & Row); |
| 132 | + |
| 133 | + beforeEach(async () => { |
| 134 | + engine = new ObjectQL(); |
| 135 | + d = makeDriver(); |
| 136 | + engine.registerDriver(d.driver, true); |
| 137 | + await engine.init(); |
| 138 | + engine.registry.registerObject(sysSecret as any); |
| 139 | + engine.registry.registerObject(vault as any); |
| 140 | + crypto = makeCrypto(); |
| 141 | + engine.setCryptoProvider(crypto); |
| 142 | + }); |
| 143 | + |
| 144 | + describe('create: a new record has no ref of its own', () => { |
| 145 | + it('a create carrying another record\'s ref is refused before anything is written', async () => { |
| 146 | + const theirs = await seed('r1', 'theirs'); |
| 147 | + const before = { secrets: secrets().length, encrypts: crypto.encrypts() }; |
| 148 | + const err = await caught(engine.insert(VAULT, { name: 'mine', token: theirs }, USER)); |
| 149 | + expect(err).toMatchObject(refusal()); |
| 150 | + expect(d.rowsOf(VAULT).map((r) => r.id)).toEqual(['r1']); |
| 151 | + expect(secrets().length).toBe(before.secrets); |
| 152 | + expect(crypto.encrypts()).toBe(before.encrypts); |
| 153 | + }); |
| 154 | + |
| 155 | + it('a ref that names an existing row and one that names nothing get the same answer', async () => { |
| 156 | + const theirs = await seed('r1', 'theirs'); |
| 157 | + const named = await caught(engine.insert(VAULT, { name: 'a', token: theirs }, USER)); |
| 158 | + const unknown = await caught(engine.insert(VAULT, { name: 'b', token: UNKNOWN_REF }, USER)); |
| 159 | + expect(named).toMatchObject(refusal()); |
| 160 | + expect(unknown).toMatchObject(refusal()); |
| 161 | + expect(unknown!.message).toBe(named!.message); |
| 162 | + expect(named!.message).not.toContain(parseSecretRef(theirs)!); |
| 163 | + expect(d.rowsOf(VAULT)).toHaveLength(1); |
| 164 | + }); |
| 165 | + |
| 166 | + it('a create with no context is not the system principal', async () => { |
| 167 | + const theirs = await seed('r1', 'theirs'); |
| 168 | + expect(await caught(engine.insert(VAULT, { name: 'a', token: theirs }))).toMatchObject(refusal()); |
| 169 | + }); |
| 170 | + |
| 171 | + it('a batch create carrying a ref is refused whole', async () => { |
| 172 | + const theirs = await seed('r1', 'theirs'); |
| 173 | + const err = await caught(engine.insert(VAULT, [{ name: 'a', token: 'fresh' }, { name: 'b', token: theirs }], USER)); |
| 174 | + expect(err).toMatchObject(refusal()); |
| 175 | + expect(d.rowsOf(VAULT).map((r) => r.id)).toEqual(['r1']); |
| 176 | + expect(secrets()).toHaveLength(1); |
| 177 | + }); |
| 178 | + |
| 179 | + it('insertMany refuses that row alone and lands the others', async () => { |
| 180 | + const theirs = await seed('r1', 'theirs'); |
| 181 | + const outcomes = await engine.insertMany(VAULT, [{ name: 'a', token: 'fresh' }, { name: 'b', token: theirs }], USER); |
| 182 | + expect(outcomes.map((o) => o.ok)).toEqual([true, false]); |
| 183 | + expect((outcomes[1] as any).error).toMatchObject(refusal()); |
| 184 | + const landed = d.rowsOf(VAULT).find((r) => r.name === 'a')!; |
| 185 | + expect(await engine.resolveSecretField(VAULT, String(landed.id), 'token')).toBe('fresh'); |
| 186 | + expect(d.rowsOf(VAULT).some((r) => r.name === 'b')).toBe(false); |
| 187 | + }); |
| 188 | + |
| 189 | + it('a beforeInsert hook that writes a ref onto the row is judged the same way', async () => { |
| 190 | + const theirs = await seed('r1', 'theirs'); |
| 191 | + engine.registerHook('beforeInsert', (ctx: any) => { ctx.input.data.token = theirs; }, { object: VAULT }); |
| 192 | + expect(await caught(engine.insert(VAULT, { name: 'a' }, USER))).toMatchObject(refusal()); |
| 193 | + expect(d.rowsOf(VAULT)).toHaveLength(1); |
| 194 | + }); |
| 195 | + |
| 196 | + it('a new value is still sealed, and the system principal keeps the pass-through', async () => { |
| 197 | + const created = await engine.insert(VAULT, { name: 'a', token: 'fresh' }, USER); |
| 198 | + expect(await engine.resolveSecretField(VAULT, String(created.id), 'token')).toBe('fresh'); |
| 199 | + const theirs = await seed('r1', 'theirs'); |
| 200 | + await engine.insert(VAULT, { id: 'copy', name: 'copy', token: theirs }, SYSTEM); |
| 201 | + expect(refOf('copy')).toBe(theirs); |
| 202 | + }); |
| 203 | + }); |
| 204 | + |
| 205 | + describe('by-id update: only the ref this record already holds', () => { |
| 206 | + it('keeping its own ref is accepted and changes nothing', async () => { |
| 207 | + const own = await seed('r1', 'mine'); |
| 208 | + const before = secrets().map((s) => s.id); |
| 209 | + await engine.update(VAULT, { id: 'r1', name: 'renamed', token: own }, USER); |
| 210 | + expect(stored('r1')).toMatchObject({ name: 'renamed', token: own }); |
| 211 | + expect(secrets().map((s) => s.id)).toEqual(before); |
| 212 | + expect(await engine.resolveSecretField(VAULT, 'r1', 'token')).toBe('mine'); |
| 213 | + }); |
| 214 | + |
| 215 | + it('keeping its own ref as the only key is accepted too', async () => { |
| 216 | + const own = await seed('r1', 'mine'); |
| 217 | + await engine.update(VAULT, { id: 'r1', token: own }, USER); |
| 218 | + expect(refOf('r1')).toBe(own); |
| 219 | + expect(await engine.resolveSecretField(VAULT, 'r1', 'token')).toBe('mine'); |
| 220 | + }); |
| 221 | + |
| 222 | + it('the echoed read mask is still a no-op', async () => { |
| 223 | + const own = await seed('r1', 'mine'); |
| 224 | + await engine.update(VAULT, { id: 'r1', name: 'renamed', token: SECRET_MASK }, USER); |
| 225 | + expect(refOf('r1')).toBe(own); |
| 226 | + }); |
| 227 | + |
| 228 | + it('a beforeUpdate hook that writes the stored row back keeps its own ref', async () => { |
| 229 | + const own = await seed('r1', 'mine'); |
| 230 | + engine.registerHook('beforeUpdate', (ctx: any) => { |
| 231 | + ctx.input.data = { ...ctx.previous, ...ctx.input.data }; |
| 232 | + }, { object: VAULT }); |
| 233 | + await engine.update(VAULT, { id: 'r1', name: 'renamed' }, USER); |
| 234 | + expect(stored('r1')).toMatchObject({ name: 'renamed', token: own }); |
| 235 | + expect(await engine.resolveSecretField(VAULT, 'r1', 'token')).toBe('mine'); |
| 236 | + }); |
| 237 | + |
| 238 | + it('another record\'s ref is refused and the stored value is untouched', async () => { |
| 239 | + const own = await seed('r1', 'mine'); |
| 240 | + const theirs = await seed('r2', 'theirs'); |
| 241 | + const before = secrets().map((s) => s.id); |
| 242 | + const err = await caught(engine.update(VAULT, { id: 'r1', name: 'renamed', token: theirs }, USER)); |
| 243 | + expect(err).toMatchObject(refusal()); |
| 244 | + expect(stored('r1')).toMatchObject({ name: 'r1', token: own }); |
| 245 | + expect(secrets().map((s) => s.id)).toEqual(before); |
| 246 | + expect(await engine.resolveSecretField(VAULT, 'r1', 'token')).toBe('mine'); |
| 247 | + }); |
| 248 | + |
| 249 | + it('another record\'s ref and a ref naming nothing get the same answer', async () => { |
| 250 | + await seed('r1', 'mine'); |
| 251 | + const theirs = await seed('r2', 'theirs'); |
| 252 | + const named = await caught(engine.update(VAULT, { id: 'r1', token: theirs }, USER)); |
| 253 | + const unknown = await caught(engine.update(VAULT, { id: 'r1', token: UNKNOWN_REF }, USER)); |
| 254 | + expect(named).toMatchObject(refusal()); |
| 255 | + expect(unknown).toMatchObject(refusal()); |
| 256 | + expect(unknown!.message).toBe(named!.message); |
| 257 | + }); |
| 258 | + |
| 259 | + it('a record whose column is empty has no ref to keep', async () => { |
| 260 | + await engine.insert(VAULT, { id: 'r1', name: 'r1' }, SYSTEM); |
| 261 | + const theirs = await seed('r2', 'theirs'); |
| 262 | + expect(await caught(engine.update(VAULT, { id: 'r1', token: theirs }, USER))).toMatchObject(refusal()); |
| 263 | + expect(stored('r1')!.token ?? null).toBeNull(); |
| 264 | + }); |
| 265 | + |
| 266 | + it('the system principal keeps the pass-through', async () => { |
| 267 | + await seed('r1', 'mine'); |
| 268 | + const theirs = await seed('r2', 'theirs'); |
| 269 | + await engine.update(VAULT, { id: 'r1', token: theirs }, SYSTEM); |
| 270 | + expect(refOf('r1')).toBe(theirs); |
| 271 | + }); |
| 272 | + }); |
| 273 | + |
| 274 | + describe('predicate update: only a ref every matched record already holds', () => { |
| 275 | + const multi = (where: Row) => ({ ...USER, where, multi: true }); |
| 276 | + |
| 277 | + it('a ref every matched row already holds is accepted and changes nothing', async () => { |
| 278 | + await seed('r1', 'one'); |
| 279 | + await seed('r2', 'two'); |
| 280 | + await engine.update(VAULT, { token: 'shared' }, { ...SYSTEM, where: { tier: 'gold' }, multi: true }); |
| 281 | + const shared = refOf('r1'); |
| 282 | + expect(refOf('r2')).toBe(shared); |
| 283 | + await engine.update(VAULT, { name: 'renamed', token: shared }, multi({ tier: 'gold' })); |
| 284 | + expect(d.rowsOf(VAULT).map((r) => [r.name, r.token])).toEqual([['renamed', shared], ['renamed', shared]]); |
| 285 | + expect(await engine.resolveSecretField(VAULT, 'r2', 'token')).toBe('shared'); |
| 286 | + }); |
| 287 | + |
| 288 | + it('a ref one matched row does not hold is refused, and nothing is written', async () => { |
| 289 | + const one = await seed('r1', 'one'); |
| 290 | + const two = await seed('r2', 'two'); |
| 291 | + const err = await caught(engine.update(VAULT, { name: 'renamed', token: one }, multi({ tier: 'gold' }))); |
| 292 | + expect(err).toMatchObject(refusal()); |
| 293 | + expect(d.rowsOf(VAULT).map((r) => [r.name, r.token])).toEqual([['r1', one], ['r2', two]]); |
| 294 | + }); |
| 295 | + |
| 296 | + it('a ref on a predicate that matches no row is refused', async () => { |
| 297 | + const one = await seed('r1', 'one'); |
| 298 | + const err = await caught(engine.update(VAULT, { token: one }, multi({ tier: 'silver' }))); |
| 299 | + expect(err).toMatchObject(refusal()); |
| 300 | + }); |
| 301 | + |
| 302 | + it('the system principal keeps the pass-through', async () => { |
| 303 | + const one = await seed('r1', 'one'); |
| 304 | + await seed('r2', 'two', 'silver'); |
| 305 | + await engine.update(VAULT, { token: one }, { ...SYSTEM, where: { tier: 'silver' }, multi: true }); |
| 306 | + expect(refOf('r2')).toBe(one); |
| 307 | + }); |
| 308 | + }); |
| 309 | +}); |
0 commit comments