|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#20964] A snapshot field the reading caller is served MASKED is not served |
| 5 | + * as stored. |
| 6 | + * |
| 7 | + * ## What is pinned, and why each half is load-bearing |
| 8 | + * |
| 9 | + * The data plane serves a field whose `maskingRule` applies to the caller with |
| 10 | + * its value replaced. The security contract's read projection, |
| 11 | + * `getReadableFields`, therefore counts that field READABLE: it is a served |
| 12 | + * column. A snapshot redaction that narrows by the read projection alone keeps |
| 13 | + * the key, and with it the value as it was captured at submission time. |
| 14 | + * |
| 15 | + * The contract's query-side answer, `getQueryableFields` (#20935), is a subset of |
| 16 | + * the read projection that differs from it by exactly the fields this caller is |
| 17 | + * served masked. The redaction reads that answer and drops those keys. It does |
| 18 | + * not re-derive who a masking rule applies to, and it does not reproduce the |
| 19 | + * mask: the contract publishes WHICH fields are masked for a caller, not the |
| 20 | + * masked value. |
| 21 | + * |
| 22 | + * 1. **not served as stored** — for a caller the rule applies to, the key is |
| 23 | + * absent from the served snapshot, on both read doors (the service door and |
| 24 | + * the generic data door), and from the derived maps built from its keys. |
| 25 | + * 2. **control** — for a caller who holds what lifts the rule, the same key |
| 26 | + * carries the stored value. Without it, a redaction that dropped the field |
| 27 | + * for everyone would pass (1). |
| 28 | + * 3. **audit preserved** — the stored column still holds the whole row. |
| 29 | + * 4. **fail closed** — a source that cannot say which readable fields are |
| 30 | + * masked for this caller (the answer is missing, `undefined`, or throws) is |
| 31 | + * served no snapshot field, as the contract obliges a consumer that cannot |
| 32 | + * get the answer. An unresolvable read projection still passes the |
| 33 | + * snapshot through whole, exactly as before (#3807). |
| 34 | + * 5. **wiring** — the approvals plugin's bridge to the `security` service |
| 35 | + * forwards the query-side answer as well as the read projection. |
| 36 | + * |
| 37 | + * The source double below mirrors the contract's two answers per caller; the |
| 38 | + * real `SecurityPlugin` composition is pinned at the HTTP door in |
| 39 | + * `packages/qa/dogfood/test/approval-snapshot-masked-field.dogfood.test.ts`. |
| 40 | + * Fixtures are synthetic. |
| 41 | + */ |
| 42 | + |
| 43 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 44 | +import { ApprovalService } from './approval-service.js'; |
| 45 | +import { ApprovalsServicePlugin } from './approvals-plugin.js'; |
| 46 | +import { type FieldVisibilitySource } from './payload-redaction.js'; |
| 47 | +import { redactRowsInPlace } from './payload-redaction-middleware.js'; |
| 48 | + |
| 49 | +const OBJECT = 'probe_note'; |
| 50 | +const RECORD = 'pn_1'; |
| 51 | +const REQUEST = 'req_pn_1'; |
| 52 | +const TENANT = 't1'; |
| 53 | +/** An approver the field's masking rule applies to. */ |
| 54 | +const MEMBER = 'probe_member'; |
| 55 | +/** An approver on the same request who holds what lifts the rule. */ |
| 56 | +const UNMASKER = 'probe_unmasker'; |
| 57 | +/** The field served masked to MEMBER. */ |
| 58 | +const MASKED_KEY = 'probe_code'; |
| 59 | + |
| 60 | +/** The submitted row, as the flow handed it over. Synthetic values. */ |
| 61 | +const FULL_ROW = { |
| 62 | + id: RECORD, |
| 63 | + title: 'Synthetic note', |
| 64 | + amount: 10, |
| 65 | + [MASKED_KEY]: 'SYNTH-0000-VALUE', |
| 66 | +}; |
| 67 | +const ALL_FIELDS = Object.keys(FULL_ROW); |
| 68 | +const BUSINESS = { id: RECORD, title: 'Synthetic note', amount: 10 }; |
| 69 | + |
| 70 | +type Answer = string[] | undefined; |
| 71 | + |
| 72 | +/** |
| 73 | + * The contract's two answers for each caller: the read projection counts the |
| 74 | + * masked field readable (it is served, masked); the query-side answer leaves it |
| 75 | + * out for the caller the rule applies to and keeps it for the unmasker. |
| 76 | + */ |
| 77 | +const CONTRACT: Record<string, { readable: Answer; queryable: Answer }> = { |
| 78 | + [MEMBER]: { readable: ALL_FIELDS, queryable: ALL_FIELDS.filter((f) => f !== MASKED_KEY) }, |
| 79 | + [UNMASKER]: { readable: ALL_FIELDS, queryable: ALL_FIELDS }, |
| 80 | +}; |
| 81 | + |
| 82 | +function contractSource(opts: { |
| 83 | + queryable?: 'answer' | 'absent' | 'undefined' | 'throws'; |
| 84 | + readable?: 'answer' | 'undefined'; |
| 85 | +} = {}): FieldVisibilitySource { |
| 86 | + const userOf = (context: unknown) => String((context as { userId?: string } | undefined)?.userId ?? ''); |
| 87 | + const source: FieldVisibilitySource = { |
| 88 | + async getReadableFields(_object: string, context?: unknown) { |
| 89 | + if (opts.readable === 'undefined') return undefined; |
| 90 | + return CONTRACT[userOf(context)]?.readable; |
| 91 | + }, |
| 92 | + }; |
| 93 | + const q = opts.queryable ?? 'answer'; |
| 94 | + if (q !== 'absent') { |
| 95 | + source.getQueryableFields = async (_object: string, context?: unknown) => { |
| 96 | + if (q === 'throws') throw new Error('synthetic outage'); |
| 97 | + if (q === 'undefined') return undefined; |
| 98 | + return CONTRACT[userOf(context)]?.queryable; |
| 99 | + }; |
| 100 | + } |
| 101 | + return source; |
| 102 | +} |
| 103 | + |
| 104 | +interface FakeRow { [k: string]: any } |
| 105 | + |
| 106 | +/** |
| 107 | + * Engine double — reads and inserts only. This file's subject is the READ path, |
| 108 | + * which never reaches a write verb, so `update` / `delete` are deliberately not |
| 109 | + * declared (the same reasoning as `approval-payload-redaction.test.ts`). |
| 110 | + */ |
| 111 | +function makeEngine() { |
| 112 | + const tables: Record<string, FakeRow[]> = {}; |
| 113 | + const ensure = (n: string) => (tables[n] ??= []); |
| 114 | + function matches(row: FakeRow, filter: any): boolean { |
| 115 | + if (!filter || typeof filter !== 'object') return true; |
| 116 | + for (const [k, v] of Object.entries(filter)) { |
| 117 | + if (k === '$or') { if (!(v as any[]).some((s) => matches(row, s))) return false; continue; } |
| 118 | + if (k === '$and') { if (!(v as any[]).every((s) => matches(row, s))) return false; continue; } |
| 119 | + const rv = row[k]; |
| 120 | + if (v != null && typeof v === 'object' && '$in' in (v as any)) { |
| 121 | + if (!(v as any).$in.includes(rv)) return false; continue; |
| 122 | + } |
| 123 | + if (rv !== v) return false; |
| 124 | + } |
| 125 | + return true; |
| 126 | + } |
| 127 | + return { |
| 128 | + _tables: tables, |
| 129 | + async find(object: string, options?: any) { |
| 130 | + const rows = ensure(object).filter((r) => matches(r, options?.filter ?? options?.where)); |
| 131 | + return rows.slice(options?.offset ?? 0, (options?.offset ?? 0) + (options?.limit ?? 1000)); |
| 132 | + }, |
| 133 | + async insert(object: string, data: any) { ensure(object).push({ ...data }); return { ...data }; }, |
| 134 | + /** The subject object's labels, so the derived `payload_labels` map is really built. */ |
| 135 | + getSchema(object: string) { |
| 136 | + if (object !== OBJECT) return undefined; |
| 137 | + return { |
| 138 | + name: OBJECT, |
| 139 | + label: 'Probe Note', |
| 140 | + fields: Object.fromEntries(ALL_FIELDS.map((f) => [f, { name: f, label: `Label ${f}` }])), |
| 141 | + }; |
| 142 | + }, |
| 143 | + }; |
| 144 | +} |
| 145 | + |
| 146 | +function seed(engine: ReturnType<typeof makeEngine>) { |
| 147 | + engine._tables[OBJECT] = [{ ...FULL_ROW, organization_id: TENANT }]; |
| 148 | + engine._tables['sys_approval_request'] = [{ |
| 149 | + id: REQUEST, |
| 150 | + organization_id: TENANT, |
| 151 | + process_name: 'flow:probe_review', |
| 152 | + object_name: OBJECT, |
| 153 | + record_id: RECORD, |
| 154 | + submitter_id: 'probe_submitter', |
| 155 | + status: 'pending', |
| 156 | + current_step: 'review', |
| 157 | + pending_approvers: [MEMBER, UNMASKER].join(','), |
| 158 | + payload_json: JSON.stringify(FULL_ROW), |
| 159 | + created_at: '2026-09-30T00:00:00Z', |
| 160 | + }]; |
| 161 | + engine._tables['sys_approval_approver'] = [ |
| 162 | + { id: 'idx_m', request_id: REQUEST, approver: MEMBER, organization_id: TENANT }, |
| 163 | + { id: 'idx_u', request_id: REQUEST, approver: UNMASKER, organization_id: TENANT }, |
| 164 | + ]; |
| 165 | + engine._tables['sys_approval_action'] = []; |
| 166 | +} |
| 167 | + |
| 168 | +const asUser = (userId: string) => ({ userId, tenantId: TENANT, positions: [], permissions: [] }) as any; |
| 169 | + |
| 170 | +const storedSnapshot = (engine: ReturnType<typeof makeEngine>) => |
| 171 | + JSON.parse(String(engine._tables['sys_approval_request'][0].payload_json)) as Record<string, unknown>; |
| 172 | + |
| 173 | +describe('[#20964] a snapshot field served masked to the reader is not served as stored — the service door', () => { |
| 174 | + let engine: ReturnType<typeof makeEngine>; |
| 175 | + let service: ApprovalService; |
| 176 | + |
| 177 | + beforeEach(() => { |
| 178 | + engine = makeEngine(); |
| 179 | + seed(engine); |
| 180 | + service = new ApprovalService({ engine: engine as any }); |
| 181 | + }); |
| 182 | + |
| 183 | + it('(1) getRequest: the masked-for-this-caller key is not served, and the business fields still are', async () => { |
| 184 | + service.attachFieldVisibility(contractSource()); |
| 185 | + const row = await service.getRequest(REQUEST, asUser(MEMBER)); |
| 186 | + const payload = row!.payload as Record<string, unknown>; |
| 187 | + expect(payload).not.toHaveProperty(MASKED_KEY); |
| 188 | + expect(payload).toEqual(BUSINESS); |
| 189 | + }); |
| 190 | + |
| 191 | + it('(1) listRequests: the masked-for-this-caller key is not served', async () => { |
| 192 | + service.attachFieldVisibility(contractSource()); |
| 193 | + const rows = await service.listRequests({ approverId: MEMBER }, asUser(MEMBER)); |
| 194 | + expect(rows).toHaveLength(1); |
| 195 | + expect(rows[0].payload).toEqual(BUSINESS); |
| 196 | + }); |
| 197 | + |
| 198 | + it('(1) the derived label map built from the snapshot keys does not carry the masked-for-this-caller key', async () => { |
| 199 | + service.attachFieldVisibility(contractSource()); |
| 200 | + const row = (await service.getRequest(REQUEST, asUser(MEMBER))) as any; |
| 201 | + // Built at all (the fixture's schema labels reach it) ... |
| 202 | + expect(row.payload_labels).toHaveProperty('title'); |
| 203 | + // ... and without the key the redaction dropped. |
| 204 | + expect(Object.keys(row.payload_labels)).not.toContain(MASKED_KEY); |
| 205 | + const control = (await service.getRequest(REQUEST, asUser(UNMASKER))) as any; |
| 206 | + expect(control.payload_labels).toHaveProperty(MASKED_KEY); |
| 207 | + }); |
| 208 | + |
| 209 | + it('(2) control: a reader who holds what lifts the rule is served the stored value', async () => { |
| 210 | + service.attachFieldVisibility(contractSource()); |
| 211 | + const row = await service.getRequest(REQUEST, asUser(UNMASKER)); |
| 212 | + expect(row!.payload).toEqual(FULL_ROW); |
| 213 | + }); |
| 214 | + |
| 215 | + it('(3) audit preserved: the stored column still holds the whole row after a masked read', async () => { |
| 216 | + service.attachFieldVisibility(contractSource()); |
| 217 | + await service.getRequest(REQUEST, asUser(MEMBER)); |
| 218 | + expect(storedSnapshot(engine)).toEqual(FULL_ROW); |
| 219 | + }); |
| 220 | + |
| 221 | + it('(4) fail closed: a source with no query-side answer serves no snapshot field', async () => { |
| 222 | + service.attachFieldVisibility(contractSource({ queryable: 'absent' })); |
| 223 | + const row = await service.getRequest(REQUEST, asUser(UNMASKER)); |
| 224 | + expect(row!.payload).toEqual({}); |
| 225 | + }); |
| 226 | + |
| 227 | + it('(4) fail closed: a query-side answer of `undefined` serves no snapshot field', async () => { |
| 228 | + service.attachFieldVisibility(contractSource({ queryable: 'undefined' })); |
| 229 | + const row = await service.getRequest(REQUEST, asUser(UNMASKER)); |
| 230 | + expect(row!.payload).toEqual({}); |
| 231 | + }); |
| 232 | + |
| 233 | + it('(4) fail closed: a query-side answer that throws serves no snapshot field', async () => { |
| 234 | + service.attachFieldVisibility(contractSource({ queryable: 'throws' })); |
| 235 | + const row = await service.getRequest(REQUEST, asUser(UNMASKER)); |
| 236 | + expect(row!.payload).toEqual({}); |
| 237 | + }); |
| 238 | + |
| 239 | + it('(4) an unresolvable read projection still passes the snapshot through whole (#3807)', async () => { |
| 240 | + service.attachFieldVisibility(contractSource({ readable: 'undefined', queryable: 'absent' })); |
| 241 | + const row = await service.getRequest(REQUEST, asUser(MEMBER)); |
| 242 | + expect(row!.payload).toEqual(FULL_ROW); |
| 243 | + }); |
| 244 | +}); |
| 245 | + |
| 246 | +describe('[#20964] a snapshot field served masked to the reader is not served as stored — the generic data door', () => { |
| 247 | + const rowsFor = () => [{ id: REQUEST, object_name: OBJECT, payload_json: JSON.stringify(FULL_ROW) }]; |
| 248 | + |
| 249 | + it('(1) the raw snapshot string loses the masked-for-this-caller key and keeps the business fields', async () => { |
| 250 | + const rows = rowsFor(); |
| 251 | + await redactRowsInPlace(rows, contractSource(), asUser(MEMBER)); |
| 252 | + expect(JSON.parse(rows[0].payload_json)).toEqual(BUSINESS); |
| 253 | + }); |
| 254 | + |
| 255 | + it('(2) control: a reader who holds what lifts the rule is served the stored value', async () => { |
| 256 | + const rows = rowsFor(); |
| 257 | + await redactRowsInPlace(rows, contractSource(), asUser(UNMASKER)); |
| 258 | + expect(JSON.parse(rows[0].payload_json)).toEqual(FULL_ROW); |
| 259 | + }); |
| 260 | + |
| 261 | + it('(4) fail closed: a source with no query-side answer serves no snapshot field', async () => { |
| 262 | + const rows = rowsFor(); |
| 263 | + await redactRowsInPlace(rows, contractSource({ queryable: 'absent' }), asUser(UNMASKER)); |
| 264 | + expect(JSON.parse(rows[0].payload_json)).toEqual({}); |
| 265 | + }); |
| 266 | +}); |
| 267 | + |
| 268 | +describe('[#20964] the approvals plugin forwards the query-side answer to the redaction', () => { |
| 269 | + it('(5) the service door narrows by the `security` service\'s query-side answer', async () => { |
| 270 | + const engine = makeEngine(); |
| 271 | + seed(engine); |
| 272 | + const services: Record<string, unknown> = { objectql: engine, security: contractSource() }; |
| 273 | + const ctx: any = { |
| 274 | + getService: (name: string) => { |
| 275 | + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); |
| 276 | + return services[name]; |
| 277 | + }, |
| 278 | + registerService: (name: string, svc: unknown) => { services[name] = svc; }, |
| 279 | + logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }, |
| 280 | + }; |
| 281 | + await new ApprovalsServicePlugin({ disableAutoHooks: true }).start(ctx); |
| 282 | + const approvals = services.approvals as ApprovalService; |
| 283 | + expect(approvals).toBeInstanceOf(ApprovalService); |
| 284 | + |
| 285 | + const masked = await approvals.getRequest(REQUEST, asUser(MEMBER)); |
| 286 | + expect(masked!.payload).toEqual(BUSINESS); |
| 287 | + const control = await approvals.getRequest(REQUEST, asUser(UNMASKER)); |
| 288 | + expect(control!.payload).toEqual(FULL_ROW); |
| 289 | + }); |
| 290 | +}); |
0 commit comments