/** * Integration test for the data-access-rules fixture. * * Each data-access rule gets a dedicated file with a true-positive function * (must trigger the rule) and a near-miss negative function (must NOT trigger * the rule). The test asserts exact per-file, per-rule counts to catch both * false negatives (lost detection) and false positives (over-eager matching). * * Baseline established 2026-08-09 from cold run; recalibrated 2026-09-10 for * Spec 55 R5 — `unfiltered-query` now fires on an unfiltered *write* (DELETE/ * UPDATE with no WHERE/HAVING/LIMIT), not on an unfiltered read; `complex-query` * now fires on a genuinely join-heavy query (many tables), not on a subquery. * The fixture's `.codeauditor.json` sets `skipTestFiles: false` so the * query-shape rules (loop-query, unfiltered-query) still run against files * under `tests/` (Spec 55 R3 excludes them by default). * rm -rf node_modules/.cache/code-auditor && node dist/cli.js audit --path -f json -o * * Total violations: 10 * - complex-query: 1 (line 12 in complex-query.ts — 9 tables) * - loop-query: 2 (loop-query.ts:18 direct, loop-query.ts:30 helper-in-loop) * - missing-org-filter: 5 (complex-query.ts:12 AND :32, loop-query.ts:18/24, * missing-org-filter.ts:12). The :12 entry is the join-heavy query itself: * `complex-query` (perf) and `missing-org-filter` (security) are independent * concerns, so a 9-table join that reads `users`+`projects` with no * org predicate fires BOTH — the perf/security priority that lets * `complex-query` win over `unfiltered-query` does not extend to the * tenant-isolation rule. * - unfiltered-query: 2 (unfiltered-query.ts:16 — the unfiltered UPDATE write; * missing-org-filter.ts:12 — the A1.4 tenant-scoped *read* case, a filterless * full-table SELECT of `projects`) */ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { mkdtemp } from 'node:fs/promises'; import { rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { execSync } from 'node:child_process'; import { runCli } from '../cli-integration.spec'; describe('data-access-rules fixture', () => { let testDir: string; beforeEach(async () => { testDir = await mkdtemp(join(tmpdir(), 'ca-da-')); const fixtureDir = join(__dirname, '..', '..', 'tests', 'fixtures', 'data-access-rules'); execSync(`cp -r "${fixtureDir}/." "${testDir}/"`, { encoding: 'utf-8' }); }); afterEach(() => { try { rmSync(testDir, { recursive: true, force: true }); } catch { /* ignore */ } }); /** * Run audit and return violations keyed by `src/` for easy lookup. */ function runAndGetViolations(testDir: string): any[] { const runResult = runCli( `audit --path "${testDir}" -f json -o "${testDir}"`, testDir ); expect(runResult.exitCode).toBe(0); const reportPath = join(testDir, 'audit-report.json'); const reportRaw = execSync(`cat "${reportPath}"`, { encoding: 'utf-8' }); const report = JSON.parse(reportRaw); // Spec 62 Amendment B — missing-org-filter now emits from the Stage-4 // `data-access-org-filter` reducer, so its findings live in a sibling // bucket rather than the Stage-2 `data-access` bucket. Merge the two so the // baseline counts (8 total, 4 missing-org-filter) stay a single assertion // over the data-access rule family. const results = report?.analyzerResults ?? {}; return [ ...(results['data-access']?.violations ?? []), ...(results['data-access-org-filter']?.violations ?? []), ]; } /** * Filter violations for a specific source file (short name, e.g. 'unfiltered-query.ts'). */ function fileViolations(violations: any[], fileName: string): any[] { return violations.filter((v: any) => v.file.endsWith(`/${fileName}`)); } /** * Count violations matching a specific rule within a file. */ function ruleCount(violations: any[], fileName: string, rule: string): number { return fileViolations(violations, fileName).filter((v: any) => v.rule === rule).length; } it('total violations match baseline', () => { const violations = runAndGetViolations(testDir); expect(violations.length).toBe(10); }); // ══════════════════════════════════════════════════════════════════ // unfiltered-query rule // ══════════════════════════════════════════════════════════════════ describe('unfiltered-query rule', () => { it('true positive: unfiltered UPDATE (no WHERE/HAVING/LIMIT) triggers unfiltered-query', () => { const violations = runAndGetViolations(testDir); expect(ruleCount(violations, 'unfiltered-query.ts', 'unfiltered-query')).toBe(1); }); it('near-miss negative: filtered UPDATE (WHERE id = ?) does NOT trigger unfiltered-query', () => { const violations = runAndGetViolations(testDir); // The near-miss function at line 22 uses `UPDATE audit_log SET archived = 1 WHERE id = ?`. // The WHERE clause is a real row-limiting predicate, so it is not "unfiltered". // The only unfiltered-query in this file is the true-positive UPDATE at line 16. const fileV = fileViolations(violations, 'unfiltered-query.ts'); const ufViolations = fileV.filter((v: any) => v.rule === 'unfiltered-query'); // Only 1 unfiltered-query violation — from true positive, not near-miss expect(ufViolations.length).toBe(1); expect(ufViolations[0].line).toBe(16); }); }); // ══════════════════════════════════════════════════════════════════ // missing-org-filter rule // ══════════════════════════════════════════════════════════════════ describe('missing-org-filter rule', () => { it('true positive: SELECT on projects without org_id triggers missing-org-filter', () => { const violations = runAndGetViolations(testDir); expect(ruleCount(violations, 'missing-org-filter.ts', 'missing-org-filter')).toBe(1); }); it('near-miss negative: SELECT on projects WITH org_id filter does NOT trigger missing-org-filter', () => { const violations = runAndGetViolations(testDir); const fileV = fileViolations(violations, 'missing-org-filter.ts'); const mofViolations = fileV.filter((v: any) => v.rule === 'missing-org-filter'); // Only 1 missing-org-filter violation — from the true positive (line 12); // neither near-miss (org_id = ? at line 18, organization_id = $1 at line 26) fires. expect(mofViolations.length).toBe(1); expect(mofViolations[0].line).toBe(12); }); it('near-miss negative: organization_id = $n (exact hhra-org shape) does NOT trigger missing-org-filter', () => { // The spelling that fooled the old 2-tier predicate: `organization_id` // (long form) with a `$n` positional operand. The Stage-4 tenant predicate // must count this as "has a tenant predicate" and stay quiet. const violations = runAndGetViolations(testDir); const fileV = fileViolations(violations, 'missing-org-filter.ts'); const mofViolations = fileV.filter((v: any) => v.rule === 'missing-org-filter'); // Still exactly one finding (the true positive at line 12); the exact-shape // near-miss at line 26 does not fire. expect(mofViolations.length).toBe(1); expect(mofViolations[0].line).toBe(12); }); it('near-miss negative: fallback-named but un-tenanted table (teams) does NOT trigger missing-org-filter', () => { // `teams` was in the old dishonest English fallback list but is not // tenant-scoped (no org/tenant column, not in orgFilterTables). The old // proxy would have fired on its name alone; the honest predicate must not. const violations = runAndGetViolations(testDir); expect(ruleCount(violations, 'untenanted-table.ts', 'missing-org-filter')).toBe(0); }); }); // ══════════════════════════════════════════════════════════════════ // loop-query rule // ══════════════════════════════════════════════════════════════════ describe('loop-query rule', () => { it('true positive: db.prepare() inside for loop triggers loop-query', () => { const violations = runAndGetViolations(testDir); expect(ruleCount(violations, 'loop-query.ts', 'loop-query')).toBe(2); }); it('true positive: loop calling a local helper that queries per iteration triggers loop-query', () => { const violations = runAndGetViolations(testDir); const fileV = fileViolations(violations, 'loop-query.ts'); const loopViolations = fileV.filter((v: any) => v.rule === 'loop-query'); expect(loopViolations.length).toBe(2); // One finding anchors to the direct db.prepare in the loop body (line 18); // the other to the helper call inside the loop (line 30) — a helper that // queries per iteration is still an N+1. expect(loopViolations.map((v: any) => v.line).sort((a: number, b: number) => a - b)) .toEqual([18, 30]); }); it('near-miss negative: batched query outside the loop does NOT trigger loop-query', () => { const violations = runAndGetViolations(testDir); // findMissingIds issues one query OUTSIDE the loop and only accumulates in // the loop body, so there is no per-iteration query to flag. The two // loop-query findings are both from the true-positive functions. const fileV = fileViolations(violations, 'loop-query.ts'); const loopViolations = fileV.filter((v: any) => v.rule === 'loop-query'); expect(loopViolations.length).toBe(2); }); }); // ══════════════════════════════════════════════════════════════════ // complex-query rule // ══════════════════════════════════════════════════════════════════ describe('complex-query rule', () => { it('true positive: query referencing 9 tables triggers complex-query', () => { const violations = runAndGetViolations(testDir); expect(ruleCount(violations, 'complex-query.ts', 'complex-query')).toBe(1); }); it('near-miss negative: simple COUNT(*) query does NOT trigger complex-query', () => { const violations = runAndGetViolations(testDir); const fileV = fileViolations(violations, 'complex-query.ts'); const complexViolations = fileV.filter((v: any) => v.rule === 'complex-query'); // Only 1 complex-query violation — from true positive (line 12), not near-miss (line 32) expect(complexViolations.length).toBe(1); expect(complexViolations[0].line).toBe(12); }); }); // ══════════════════════════════════════════════════════════════════ // non-db-receiver guard — pool.length array regression guard // ══════════════════════════════════════════════════════════════════ // // Regression guard: variable named 'pool' that is NOT a database // connection pool must NOT be flagged as a DB operation. // pool.length, pool.push(), and pool.length = 0 are array operations // on `const pool: number[] = [1, 2, 3]` — not DB calls. describe('non-db-receiver guard', () => { it('pool.length array property access is NOT flagged as a data-access violation', () => { const violations = runAndGetViolations(testDir); const poolViolations = fileViolations(violations, 'non-db-receiver.ts'); expect(poolViolations.length).toBe(0); }); it('pool.push() array method is NOT flagged as a data-access violation', () => { const violations = runAndGetViolations(testDir); const poolViolations = fileViolations(violations, 'non-db-receiver.ts'); expect(poolViolations.length).toBe(0); }); it('pool.length = 0 array truncation is NOT flagged as a data-access violation', () => { const violations = runAndGetViolations(testDir); const poolViolations = fileViolations(violations, 'non-db-receiver.ts'); expect(poolViolations.length).toBe(0); }); it('baseline total is unchanged by non-db-receiver.ts (10 violations)', () => { const violations = runAndGetViolations(testDir); expect(violations.length).toBe(10); }); }); });