Repository navigation
Expand file tree
/
Copy pathsql-driver-compile-refusal-seam.test.ts
More file actions
620 lines (585 loc) · 26.2 KB
/
Copy pathsql-driver-compile-refusal-seam.test.ts
File metadata and controls
620 lines (585 loc) · 26.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#20039] EVERY refusal on this driver's filter-compile path goes through the
* #8220 withheld seam — and a builder added later that does not goes red here.
*
* ## What was measured before this file existed
*
* Eight more compile refusals than #20020 converted built their error with
* `unsupportedFilterError` directly, so a read scope — an RLS / sharing /
* tenant predicate a merge boundary ANDs into the caller's `where` and marks
* `'policy'` — that one of them refused came back as an `INVALID_FILTER` / 400
* naming the policy's field or literal. Measured through a real `ObjectQL` over
* a real `SqlDriver` with a `plugin-security`-shaped merge (the scope in the
* `'policy'` arm): an empty or non-string `$icontains`, a non-string `$like`, a
* `$like` pattern with a trailing escape, an object `$contains` comparand, an
* object `$in` member, an `undefined` comparand, a non-node element of `$or`,
* an undeclared node combinator. A ninth, the array-root refusal, relays the
* WHOLE array — every field and literal in it.
*
* ## The contract
*
* `filter-subtree-provenance.ts`, the `'policy'` literal: "A refusal raised
* from inside it keeps the #7929 redaction: identity (`INVALID_FILTER` / 400)
* and capability statement on the wire, operands in the server log." And the
* fail direction: "Unmarked or ambiguous ⇒ withheld."
*
* ## Two halves, and why both
*
* 1. **The enumeration** reads `sql-driver.ts` and its cross-field seam module
* `sql-driver-cross-field-comparison.ts` (#25521 cut 13), plus the read-exit
* fault module `sql-driver-read-exit-fault.ts` (#25521 cut 15) and the
* predicate-emitter module `sql-driver-predicate-emitters.ts` (#25521 cut 16)
* and the generated top-level leaf `sql-driver-top-level.ts` (#29520 codemod),
* and, since #30147, every other `sql-driver-*.ts` module beside it (a
* facet member is named as the `SqlDriver` method whose body it is),
* and lists every function that builds an `INVALID_FILTER` error. Only three may call
* `unsupportedFilterError` directly (the seam itself, the `'author'`
* re-issue, and the column refusal raised from a dialect error AFTER the
* statement ran), and every caller of `withheldFilterError` must have a row
* in the table below. So a new compile refusal that bypasses the seam goes
* red on the first set, and one that uses the seam without a row goes red on
* the second — no door can disclose by omission.
* 2. **The table** drives each of those builders under every mark: policy and
* unmarked withhold (same code and status, no secret on the wire, every
* secret in the log), author gets the full text, and inside a merged `$and`
* the refusing arm's mark decides in both arm orders. Each row proves it
* reached its builder by the error's own stack, so a row cannot silently
* drift onto a sibling door.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { readdirSync, readFileSync } from 'node:fs';
import ts from 'typescript';
import { SqlDriver } from './index.js';
import { markFilterSubtreeProvenance, type FilterCondition } from '@objectstack/spec/data';
interface WireBearingError extends Error {
code?: string;
status?: number;
}
/** A column a policy names, a column it references, and a literal no caller may learn. */
const POLICY_COL = 'secret_policy_col';
const REF_COL = 'secret_ref_col';
const JSON_COL = 'secret_tags';
const SECRET = 'PSECRET_LITERAL';
/** A literal for the doors whose comparand must NOT be a string. */
const SECRET_NUM = 7770123;
const UNDECLARED_KEY = '$psecret_combinator';
type Door = {
/** The builder in `sql-driver.ts` or one of its seam modules this row drives — asserted by the error's stack. */
readonly builder: string;
readonly where: () => Record<string, unknown> | unknown[];
readonly secrets: readonly string[];
/** A fragment of the class statement, which survives redaction. */
readonly klass: string;
/** The author text adds a prescription the log line does not carry. */
readonly authorExtendsLog?: true;
/** The refusal fires only when the array IS the `where` root — no merged arm. */
readonly rootOnly?: true;
/**
* [#20444] Put the driver in the state the refusal needs before each case —
* for a refusal no filter alone can reach on this fixture's SQLite client.
*/
readonly setup?: (driver: SqlDriver) => void;
};
/** [#20444] A column no field of the fixture declares. */
const UNDECLARED_COL = 'secret_undeclared_col';
const DOORS: readonly Door[] = [
// ── #20039: the class this file closes ────────────────────────────────────
{
builder: 'icontainsComparandError',
where: () => ({ [POLICY_COL]: { $icontains: SECRET_NUM } }),
secrets: [POLICY_COL, String(SECRET_NUM)],
klass: 'Operator "$icontains" in this filter requires a NON-EMPTY string comparand',
},
{
builder: 'likePatternComparandError',
where: () => ({ [POLICY_COL]: { $like: SECRET_NUM } }),
// Both pattern operators are NAMED by the class statement ("$like" /
// "$ilike"), so which one fired is not asserted absent; the field and the
// comparand are.
secrets: [POLICY_COL, String(SECRET_NUM)],
klass: 'requires a string comparand',
},
{
builder: 'danglingLikeEscapeError',
where: () => ({ [POLICY_COL]: { $ilike: `${SECRET}\\` } }),
secrets: [POLICY_COL, SECRET],
klass: 'ending in a lone unpaired backslash',
},
// ── #20041: born in the seam ───────────────────────────────────────────────
{
builder: 'nulLikePatternError',
// U+0000 spelled by code point: a source file never holds the raw byte.
where: () => ({ [POLICY_COL]: { $like: `%${SECRET}${String.fromCharCode(0x00)}` } }),
secrets: [POLICY_COL, SECRET],
klass: 'has a pattern holding the NUL character U+0000',
},
{
builder: 'unrenderableTextComparandError',
where: () => ({ [POLICY_COL]: { $startsWith: { k: SECRET } } }),
secrets: [POLICY_COL, SECRET, '$startsWith'],
klass: 'matches against the TEXT of a pattern',
},
{
builder: 'unbindableListMemberError',
where: () => ({ [POLICY_COL]: { $nin: ['a', { k: SECRET }] } }),
secrets: [POLICY_COL, SECRET, 'index 1'],
klass: 'has a member that cannot be bound as a SQL parameter',
},
{
builder: 'undefinedComparandError',
where: () => ({ [POLICY_COL]: { $eq: undefined } }),
secrets: [POLICY_COL],
klass: 'A comparand in this filter is undefined',
},
{
builder: 'assertFilterNode',
where: () => ({ $or: [SECRET] }),
secrets: [SECRET, '$or[0]'],
klass: 'is not a filter condition object',
},
{
builder: 'unknownLogicalOperatorError',
where: () => ({ [UNDECLARED_KEY]: 'x' }),
secrets: [UNDECLARED_KEY],
klass: 'not a declared combinator',
},
{
builder: 'filterArrayReachedDriverError',
where: () => [{ [POLICY_COL]: SECRET }],
secrets: [POLICY_COL, SECRET],
klass: 'A filter ARRAY reached the driver',
rootOnly: true,
},
// ── the doors #7929 / #8197 / #20020 already converted, enumerated here so
// the table IS the set the seam carries ──────────────────────────────────
{
builder: 'crossFieldComparisonError',
where: () => ({ [POLICY_COL]: { $contains: { $field: REF_COL } } }),
secrets: [POLICY_COL, REF_COL],
klass: 'A cross-field comparison',
authorExtendsLog: true,
},
{
builder: 'bareFieldReferenceError',
where: () => ({ [POLICY_COL]: { $field: REF_COL } }),
secrets: [POLICY_COL, REF_COL],
klass: 'bare field reference',
authorExtendsLog: true,
},
{
builder: 'uncompilableFieldReferenceError',
where: () => ({ [POLICY_COL]: { $gt: { $field: 'secret_undeclared_ref' } } }),
secrets: [POLICY_COL, 'secret_undeclared_ref'],
klass: 'cannot be compiled here',
},
// ── #25808: the now-anchored comparand's two doors ─────────────────────────
{
builder: 'nowAnchorPositionError',
where: () => ({ [POLICY_COL]: { $contains: { $now: true, addDays: 1 } } }),
secrets: [POLICY_COL, '$contains'],
klass: 'A now-anchored comparand',
authorExtendsLog: true,
},
{
builder: 'uncompilableNowAnchorError',
where: () => ({ [POLICY_COL]: { $gt: { $now: true, addDays: { $field: 'secret_undeclared_ref' } } } }),
secrets: [POLICY_COL],
klass: 'A now-anchored comparison',
},
{
builder: 'jsonColumnOperatorError',
where: () => ({ [JSON_COL]: { $in: [SECRET] } }),
secrets: [JSON_COL],
klass: 'WAS NOT APPLIED',
},
{
builder: 'emptyFieldConstraintError',
where: () => ({ [POLICY_COL]: {}, stage: { $eq: 'won' } }),
secrets: [POLICY_COL],
klass: 'carries zero operators',
},
{
builder: 'unbindableComparandError',
where: () => ({ [POLICY_COL]: { $eq: { k: SECRET } } }),
secrets: [POLICY_COL, SECRET],
klass: 'cannot be bound as a SQL parameter',
},
{
builder: 'betweenArityError',
where: () => ({ [POLICY_COL]: { $between: [SECRET] } }),
secrets: [POLICY_COL],
klass: 'requires a [min, max] value array',
},
{
builder: 'retiredFilterOperatorError',
where: () => ({ [POLICY_COL]: { $regex: `^${SECRET}` } }),
secrets: [POLICY_COL, '$regex'],
klass: 'is RETIRED',
},
{
builder: 'unsupportedFilterOperatorError',
where: () => ({ [POLICY_COL]: { $sounds_like: SECRET } }),
secrets: [POLICY_COL, '$sounds_like'],
klass: 'not one this driver evaluates',
},
{
builder: 'assertFilterNodeList',
where: () => ({ $or: { [POLICY_COL]: SECRET } }),
secrets: [POLICY_COL, SECRET],
klass: 'requires an array of filter conditions',
},
{
builder: 'nonBooleanNullComparandError',
where: () => ({ [POLICY_COL]: { $null: SECRET } }),
secrets: [POLICY_COL, SECRET],
klass: 'Operator "$null" in this filter requires a boolean comparand',
},
{
builder: 'nonBooleanExistsComparandError',
where: () => ({ [POLICY_COL]: { $exists: SECRET } }),
secrets: [POLICY_COL, SECRET],
klass: 'Operator "$exists" in this filter requires a boolean comparand',
},
// ── #20444: the `$empty` operator, born in the seam ─────────────────────────
{
builder: 'nonBooleanEmptyComparandError',
where: () => ({ [POLICY_COL]: { $empty: SECRET } }),
secrets: [POLICY_COL, SECRET],
klass: 'Operator "$empty" in this filter requires a boolean comparand',
},
{
builder: 'undeclaredEmptyOperatorFieldError',
where: () => ({ [UNDECLARED_COL]: { $empty: true } }),
secrets: [UNDECLARED_COL],
klass: 'targets a field whose declaration this driver does not hold',
},
{
builder: 'emptyListUnsupportedDialectError',
where: () => ({ [JSON_COL]: { $empty: false } }),
secrets: [JSON_COL],
klass: 'whose empty list is tested with a JSON function that differs per SQL dialect',
// A knex client this driver does not model (mssql, oracle) reads as the
// `'unknown'` dialect, where the multi-value row has no construct.
setup: (driver) => {
Object.defineProperty(driver, 'dialectName', { get: () => 'unknown', configurable: true });
},
},
];
// ── Half 1: the enumeration ───────────────────────────────────────────────────
/**
* Every function in `sql-driver.ts` and every `sql-driver-*.ts` module beside it that builds an `INVALID_FILTER` error, by the route it takes. Read with the TypeScript parser, not a regex, so a call
* split across lines, an inline `throw`, or a builder written as a method or an
* arrow cannot slip past the count.
*/
function enumerateRefusalBuilders(): {
files: string[];
directCallers: Set<string>;
seamCallers: Set<string>;
codeWriters: Set<string>;
} {
// [#25521 cut 13] The cross-field and now-anchored comparison compile moved to
// its own seam module with two of the builders below; the scan reads both.
// [#25521 cut 15] The read exits' fault terminals moved to a third, with
// `unresolvableFilterColumnError`; the scan reads it too.
// [#25521 cut 16] The leaf predicate emitters moved to a fourth, with the two
// `$empty` refusals; the scan reads it too.
// [#29520 codemod] The top-level declarations ahead of the class moved to a
// generated leaf, with the refusal builders among them; the scan reads it too.
// [#30147] The codemod moves a class method's body into a facet class
// (`export class <X>Facet`) in any section module, so the scan reads every
// `sql-driver-*.ts` module, not a list a move can outrun, and names a facet's
// static `x` as `SqlDriver.x`: it is that method's body.
const files = readdirSync(new URL('.', import.meta.url))
.filter((f) => /^sql-driver(-[a-z0-9-]+)?\.ts$/.test(f) && !f.endsWith('.test.ts'))
.sort();
const sources = files.map((f) => [f, readFileSync(new URL(`./${f}`, import.meta.url), 'utf8')] as const);
const directCallers = new Set<string>();
const seamCallers = new Set<string>();
const codeWriters = new Set<string>();
const enclosingName = (node: ts.Node): string => {
for (let at: ts.Node | undefined = node.parent; at; at = at.parent) {
if (ts.isFunctionDeclaration(at) && at.name) return at.name.text;
if (ts.isMethodDeclaration(at) && ts.isIdentifier(at.name)) {
const owner = at.parent;
const cls = ts.isClassDeclaration(owner) && owner.name ? owner.name.text : '?';
return `${/^[A-Z][A-Za-z0-9]*Facet$/.test(cls) ? 'SqlDriver' : cls}.${at.name.text}`;
}
if ((ts.isArrowFunction(at) || ts.isFunctionExpression(at)) && ts.isVariableDeclaration(at.parent)) {
const decl = at.parent;
if (ts.isIdentifier(decl.name)) return decl.name.text;
}
}
return '(module scope)';
};
const calleeName = (call: ts.CallExpression): string | null => {
const callee = call.expression;
if (ts.isIdentifier(callee)) return callee.text;
if (ts.isPropertyAccessExpression(callee)) return callee.name.text;
return null;
};
const isInvalidFilterCode = (expr: ts.Expression): boolean =>
(ts.isStringLiteralLike(expr) && expr.text === 'INVALID_FILTER') ||
(ts.isPropertyAccessExpression(expr) && expr.name.text === 'INVALID_FILTER');
const visit = (node: ts.Node): void => {
if (ts.isCallExpression(node)) {
const name = calleeName(node);
if (name === 'unsupportedFilterError') directCallers.add(enclosingName(node));
if (name === 'withheldFilterError') seamCallers.add(enclosingName(node));
}
// `err.code = …INVALID_FILTER` or `{ code: 'INVALID_FILTER' }` — a builder
// that hand-rolls the envelope instead of calling either constructor.
if (
ts.isBinaryExpression(node) &&
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
ts.isPropertyAccessExpression(node.left) &&
node.left.name.text === 'code' &&
isInvalidFilterCode(node.right)
) {
codeWriters.add(enclosingName(node));
}
if (
ts.isPropertyAssignment(node) &&
ts.isIdentifier(node.name) &&
node.name.text === 'code' &&
isInvalidFilterCode(node.initializer)
) {
codeWriters.add(enclosingName(node));
}
ts.forEachChild(node, visit);
};
for (const [name, source] of sources) visit(ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true));
return { files, directCallers, seamCallers, codeWriters };
}
describe('[#20039] the filter-compile refusal class is closed — enumeration', () => {
const found = enumerateRefusalBuilders();
it('positive control: the scan sees the doors #20020 converted, and the column door it left', () => {
// If the parser stopped seeing builders, every assertion below would pass
// over empty sets. These are known members of both sets.
for (const builder of [
'retiredFilterOperatorError',
'unsupportedFilterOperatorError',
'assertFilterNodeList',
'nonBooleanNullComparandError',
'nonBooleanExistsComparandError',
]) {
expect(found.seamCallers, builder).toContain(builder);
}
expect(found.directCallers).toContain('unresolvableFilterColumnError');
// [#30147] The modules the builders were found in before the scan read
// every module, and one facet module, are among those it reads.
for (const f of ['sql-driver.ts', 'sql-driver-cross-field-comparison.ts', 'sql-driver-read-exit-fault.ts',
'sql-driver-predicate-emitters.ts', 'sql-driver-top-level.ts', 'sql-driver-filter-helpers.ts']) {
expect(found.files, `the scan lost ${f}`).toContain(f);
}
});
it('only three functions build the envelope WITHOUT the seam, none of them on the compile path', () => {
// - `withheldFilterError`: the seam itself;
// - `SqlDriver.resolveWithheldFilterRefusal`: the `'author'` re-issue, after
// the verdict;
// - `unresolvableFilterColumnError`: raised from a dialect error AFTER the
// statement ran, with its own by-name provenance
// (`unresolvableColumnProvenance`, #20020).
// A NEW name here is a compile refusal that decides by omission what the
// wire may name. Route it through `withheldFilterError` with the node it
// was raised from, and give it a row in DOORS.
expect([...found.directCallers].sort()).toEqual(
['SqlDriver.resolveWithheldFilterRefusal', 'unresolvableFilterColumnError', 'withheldFilterError'].sort(),
);
// And nothing hand-rolls the envelope beside the one constructor.
expect([...found.codeWriters]).toEqual(['unsupportedFilterError']);
});
it('every builder that goes through the seam is driven by a row below, and every row is one', () => {
expect([...found.seamCallers].sort()).toEqual(DOORS.map((d) => d.builder).sort());
});
});
// ── Half 2: every builder under every mark ────────────────────────────────────
describe('[#20039] every filter-compile refusal × filter-subtree provenance', () => {
let driver: SqlDriver;
let logged: string[];
beforeEach(async () => {
driver = new SqlDriver({
client: 'better-sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true,
});
await driver.initObjects([
{
name: 'deal',
fields: {
id: { type: 'text', name: 'id' },
stage: { type: 'text', name: 'stage' },
[POLICY_COL]: { type: 'text', name: POLICY_COL },
[REF_COL]: { type: 'text', name: REF_COL },
[JSON_COL]: { type: 'lookup', name: JSON_COL, multiple: true },
},
} as any,
]);
await driver.create('deal', { id: '1', stage: 'won', [POLICY_COL]: 'a', [REF_COL]: 'b' });
logged = [];
(driver as unknown as { logger: unknown }).logger = {
warn: (m: string) => { logged.push(String(m)); },
error: () => {},
info: () => {},
debug: () => {},
};
});
const refusalOf = async (where: unknown): Promise<WireBearingError> => {
try {
await driver.find('deal', { fields: ['id'], where: where as FilterCondition });
} catch (e) {
return e as WireBearingError;
}
throw new Error('expected the driver to refuse this filter, but it resolved');
};
const expectWithheld = (err: WireBearingError, door: Door) => {
expect(err.code).toBe('INVALID_FILTER');
expect(err.status).toBe(400);
// The error's own keys are the envelope and nothing else.
expect(Object.keys(err).sort()).toEqual(['code', 'status']);
for (const secret of door.secrets) expect(err.message, `names "${secret}"`).not.toContain(secret);
expect(err.message).toContain(door.klass);
expect(err.message).not.toContain('[sql-driver]');
// Relocated, not deleted: every secret is in the server log.
for (const secret of door.secrets) expect(logged.join('\n'), `log lost "${secret}"`).toContain(secret);
// The row reached the builder it names — not a sibling door.
expect(err.stack ?? '').toMatch(new RegExp(`\\bat ${door.builder}\\b`));
};
for (const door of DOORS) {
describe(door.builder, () => {
beforeEach(() => {
door.setup?.(driver);
});
it('policy-marked ⇒ same code and status, operands WITHHELD, and in the server log', async () => {
expectWithheld(await refusalOf(markFilterSubtreeProvenance(door.where(), 'policy')), door);
});
it('author-marked ⇒ the full diagnostic', async () => {
const policy = await refusalOf(markFilterSubtreeProvenance(door.where(), 'policy'));
const log = logged.join('\n');
logged = [];
const author = await refusalOf(markFilterSubtreeProvenance(door.where(), 'author'));
expect(author.code).toBe('INVALID_FILTER');
expect(author.status).toBe(400);
for (const secret of door.secrets) expect(author.message).toContain(secret);
expect(author.message).not.toBe(policy.message);
// The author's text is the diagnostic the policy population only logged.
if (!door.authorExtendsLog) expect(log).toContain(author.message);
// The seam re-issues it and logs nothing: it was the caller's to read.
expect(logged).toEqual([]);
});
it('UNMARKED ⇒ withheld, byte-identical to policy — the fail direction', async () => {
const unmarked = await refusalOf(door.where());
expectWithheld(unmarked, door);
const policy = await refusalOf(markFilterSubtreeProvenance(door.where(), 'policy'));
expect(unmarked.message).toBe(policy.message);
});
if (!door.rootOnly) {
it("merged $and: the refusing arm's mark decides, in both arm orders", async () => {
for (const order of ['author-first', 'policy-first'] as const) {
const other = { stage: 'won' };
const disclosedArms = [
markFilterSubtreeProvenance(door.where(), 'author'),
markFilterSubtreeProvenance({ ...other }, 'policy'),
];
const disclosed = await refusalOf({
$and: order === 'author-first' ? disclosedArms : [...disclosedArms].reverse(),
});
for (const secret of door.secrets) expect(disclosed.message, order).toContain(secret);
logged = [];
const withheldArms = [
markFilterSubtreeProvenance({ ...other }, 'author'),
markFilterSubtreeProvenance(door.where(), 'policy'),
];
const withheld = await refusalOf({
$and: order === 'author-first' ? withheldArms : [...withheldArms].reverse(),
});
expectWithheld(withheld, door);
}
});
}
});
}
});
// ── The node each refusal hands the seam ──────────────────────────────────────
describe('[#20039] the node a walk refusal resolves is the one it was raised from', () => {
let driver: SqlDriver;
beforeEach(async () => {
driver = new SqlDriver({
client: 'better-sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true,
});
await driver.initObjects([
{
name: 'deal',
fields: { id: { type: 'text', name: 'id' }, stage: { type: 'text', name: 'stage' } },
} as any,
]);
(driver as unknown as { logger: unknown }).logger = {
warn: () => {}, error: () => {}, info: () => {}, debug: () => {},
};
});
const messageOf = async (where: unknown): Promise<string> => {
try {
await driver.find('deal', { fields: ['id'], where: where as FilterCondition });
} catch (e) {
return (e as Error).message;
}
throw new Error('expected the driver to refuse this filter, but it resolved');
};
it('a primitive $or element nested in an AUTHOR arm is the author arm (found through its list)', async () => {
const message = await messageOf({
$or: [
markFilterSubtreeProvenance({ stage: 'won' }, 'policy'),
markFilterSubtreeProvenance({ $and: [{ $or: [SECRET] }] }, 'author'),
],
});
expect(message).toContain(SECRET);
expect(message).toContain('filter.$or[1].$and[0].$or[0]');
});
it('the same element nested in a POLICY arm is withheld', async () => {
const message = await messageOf({
$or: [
markFilterSubtreeProvenance({ stage: 'won' }, 'author'),
markFilterSubtreeProvenance({ $and: [{ $or: [SECRET] }] }, 'policy'),
],
});
expect(message).not.toContain(SECRET);
expect(message).toContain('is not a filter condition object');
});
it('a primitive $not operand inherits from the node carrying $not', async () => {
expect(await messageOf(markFilterSubtreeProvenance({ $not: SECRET }, 'author'))).toContain(SECRET);
expect(await messageOf(markFilterSubtreeProvenance({ $not: SECRET }, 'policy'))).not.toContain(SECRET);
});
it('a DIRECT undefined comparand is decided by the node carrying the field, at any depth', async () => {
const author = await messageOf({
$and: [
markFilterSubtreeProvenance({ stage: 'won' }, 'policy'),
markFilterSubtreeProvenance({ $or: [{ secret_field: undefined }] }, 'author'),
],
});
expect(author).toContain('secret_field');
const policy = await messageOf({
$and: [
markFilterSubtreeProvenance({ stage: 'won' }, 'author'),
markFilterSubtreeProvenance({ $or: [{ secret_field: undefined }] }, 'policy'),
],
});
expect(policy).not.toContain('secret_field');
});
it('an undeclared key is decided by the node CARRYING it, never by its own value', async () => {
// The value is marked 'author' on its own, inside a policy node: the KEY is
// the policy's, so the refusal stays withheld.
const message = await messageOf({
$and: [
markFilterSubtreeProvenance({ stage: 'won' }, 'author'),
markFilterSubtreeProvenance(
{ [UNDECLARED_KEY]: markFilterSubtreeProvenance({ a: 1 }, 'author') },
'policy',
),
],
});
expect(message).not.toContain(UNDECLARED_KEY);
expect(message).toContain('not a declared combinator');
});
});