diff --git a/src/adapters/postgres.ts b/src/adapters/postgres.ts index fa9449b..48062d6 100644 --- a/src/adapters/postgres.ts +++ b/src/adapters/postgres.ts @@ -319,7 +319,9 @@ export class PostgresAdapter implements DatabaseAdapter { const client = await pool.connect(); + // Enforce serializable dry-run transaction envelope with guaranteed rollback await client.query("BEGIN;"); + await client.query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); try { const res = await client.query(sql, params); affectedRows = Number(res.rowCount || 0); @@ -370,7 +372,9 @@ export class PostgresAdapter implements DatabaseAdapter { const client = await pool.connect(); + // Enforce serializable isolation for atomic two-phase commit await client.query("BEGIN;"); + await client.query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); try { const res = await client.query(sql, params); const changes = Number(res.rowCount || 0); diff --git a/src/guard/ast.ts b/src/guard/ast.ts index 8481ab8..e002a3b 100644 --- a/src/guard/ast.ts +++ b/src/guard/ast.ts @@ -23,6 +23,14 @@ export interface ParseResult { parseError?: string; } +export interface SqlNormalizationResult { + normalizedSql: string; + hasMultiStatement: boolean; + hasCommentEvasion: boolean; + hasUnicodeSmuggling: boolean; + tokens: string[]; +} + /** * Safely strips single-line (-- ...) and multi-line (/* ... *\/) SQL comments, * properly respecting single and double quoted string literals and escapes. @@ -120,8 +128,116 @@ function mapDialect(dialect: DatabaseDialect): string { } } +/** + * Normalizes SQL for AST analysis, security auditing, and tamper inspection. + * Strips zero-width unicode smuggling characters, neutralizes inline comment evasion (e.g. SEL/*...*\/ECT), + * detects multi-statement chaining via unquoted semicolons, and canonicalizes whitespace. + */ +export function normalizeSqlForAudit(sql: string): SqlNormalizationResult { + if (!sql) { + return { + normalizedSql: "", + hasMultiStatement: false, + hasCommentEvasion: false, + hasUnicodeSmuggling: false, + tokens: [], + }; + } + + // 1. Detect zero-width and invisible unicode characters (Unicode smuggling) + const zeroWidthPattern = /(?:\u200B|\u200C|\u200D|\uFEFF)/g; + const abnormalSpacePattern = /[\u00A0\u2028\u2029\u2000-\u200A]/g; + const hasUnicodeSmuggling = zeroWidthPattern.test(sql) || abnormalSpacePattern.test(sql); + const cleanUnicode = sql.replace(zeroWidthPattern, "").replace(abnormalSpacePattern, " "); + + // 2. Detect inline comment evasion (e.g. SEL/**/ECT, UN/**/ION, DR/**/OP) + const commentEvasionPattern = /[a-zA-Z0-9_]\/\*[\s\S]*?\*\/[a-zA-Z0-9_]/; + const hasCommentEvasion = commentEvasionPattern.test(cleanUnicode); + + // 3. Strip SQL comments safely while preserving string literals + const stripped = stripSqlComments(cleanUnicode); + + // 4. Multi-statement injection detection: + // Count unquoted semicolons that separate non-empty statements + let inSingleQuote = false; + let inDoubleQuote = false; + let statementCount = 0; + let currentStmt = ""; + const statements: string[] = []; + + for (let i = 0; i < stripped.length; i++) { + const char = stripped[i]; + const next = stripped[i + 1]; + + if (inSingleQuote) { + currentStmt += char; + if (char === "'" && next === "'") { + currentStmt += next; + i++; + } else if (char === "'") { + inSingleQuote = false; + } + continue; + } + + if (inDoubleQuote) { + currentStmt += char; + if (char === '"' && next === '"') { + currentStmt += next; + i++; + } else if (char === '"') { + inDoubleQuote = false; + } + continue; + } + + if (char === "'") { + inSingleQuote = true; + currentStmt += char; + continue; + } + + if (char === '"') { + inDoubleQuote = true; + currentStmt += char; + continue; + } + + if (char === ";") { + const trimmed = currentStmt.trim(); + if (trimmed) { + statements.push(trimmed); + statementCount++; + } + currentStmt = ""; + continue; + } + + currentStmt += char; + } + + const trailing = currentStmt.trim(); + if (trailing) { + statements.push(trailing); + statementCount++; + } + + const hasMultiStatement = statementCount > 1; + const normalizedSql = statements.join("; ").replace(/\s+/g, " ").trim(); + const tokens = normalizedSql.split(/\s+/).filter(Boolean); + + return { + normalizedSql, + hasMultiStatement, + hasCommentEvasion, + hasUnicodeSmuggling, + tokens, + }; +} + export function parseSql(sql: string, dialect: DatabaseDialect = "sqlite"): ParseResult { - const stripped = stripSqlComments(sql); + const norm = normalizeSqlForAudit(sql); + const stripped = norm.normalizedSql; if (!stripped) { return { statements: [], @@ -133,7 +249,7 @@ export function parseSql(sql: string, dialect: DatabaseDialect = "sqlite"): Pars const sqlDialect = mapDialect(dialect); try { - const astResult = parser.astify(sql, { database: sqlDialect }); + const astResult = parser.astify(stripped, { database: sqlDialect }); const astList = Array.isArray(astResult) ? astResult : [astResult]; if (astList.length === 0) { @@ -156,12 +272,12 @@ export function parseSql(sql: string, dialect: DatabaseDialect = "sqlite"): Pars return { statements, - isMultiStatement: astList.length > 1, + isMultiStatement: astList.length > 1 || norm.hasMultiStatement, }; } catch (err) { return { statements: [], - isMultiStatement: false, + isMultiStatement: norm.hasMultiStatement, parseError: (err as Error).message, }; } diff --git a/src/sandbox/engine.ts b/src/sandbox/engine.ts index 4bcb97c..7f26015 100644 --- a/src/sandbox/engine.ts +++ b/src/sandbox/engine.ts @@ -24,7 +24,11 @@ export class SandboxEngine { return this.tokenManager; } - public async dryRun(sql: string, params: unknown[] = []): Promise { + public async dryRun( + sql: string, + params: unknown[] = [], + options?: { intent?: string; expectedAffectedRows?: number }, + ): Promise { const evaluation = this.guard.evaluate(sql); // If AST guardrail outright blocks the query (unconstrained delete, tautology, DROP) @@ -36,18 +40,45 @@ export class SandboxEngine { executionTimeMs: 0, warnings: evaluation.violations.map((v) => `[${v.code}] ${v.message}`), rollbackVerified: false, + intentAligned: false, + intentGap: `Query blocked by guardrail: ${evaluation.violations.map((v) => v.message).join("; ")}`, }; } const adapterResult = await this.adapter.executeDryRun(sql, params); if (!adapterResult.safe) { - return adapterResult; + return { + ...adapterResult, + intentAligned: false, + }; } const affectedRows = adapterResult.simulatedAffectedRows; const warnings = [...adapterResult.warnings, ...evaluation.warnings]; + // Intent vs. Effect Gap Analysis + let intentAligned = true; + let intentGap: string | undefined; + + if (options?.expectedAffectedRows !== undefined) { + if (affectedRows !== options.expectedAffectedRows) { + intentAligned = false; + intentGap = `[INTENT_EFFECT_DISCREPANCY] Expected affected rows was ${options.expectedAffectedRows}, but simulated execution affected ${affectedRows} rows. Execution requires manual review.`; + warnings.push(intentGap); + } + } else if (options?.intent) { + const lowerIntent = options.intent.toLowerCase(); + const impliesSingle = /\b(single|one|a user|this user|specific|individual)\b/i.test( + lowerIntent, + ); + if (impliesSingle && affectedRows > 1) { + intentAligned = false; + intentGap = `[INTENT_EFFECT_DISCREPANCY] Stated intent implied single-record modification, but simulated execution affected ${affectedRows} rows.`; + warnings.push(intentGap); + } + } + // Blast Radius Limit Checking: separate soft warning threshold from hard safety limit const maxRows = this.config.maxRowsPerMutation; const warnRows = this.config.warnRowsPerMutation ?? 10; @@ -64,6 +95,8 @@ export class SandboxEngine { `[EXCESSIVE_BLAST_RADIUS] ${blastWarning} Execution blocked across all safety tiers.`, ], rollbackVerified: adapterResult.rollbackVerified, + intentAligned: false, + intentGap: blastWarning, }; } @@ -94,6 +127,8 @@ export class SandboxEngine { expiresAt: tokenInfo.expiresAt, warnings, rollbackVerified: adapterResult.rollbackVerified, + intentAligned, + intentGap, }; } diff --git a/src/types/index.ts b/src/types/index.ts index dcb569d..a48306f 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -60,6 +60,8 @@ export interface DryRunResult { expiresAt?: string; warnings: string[]; rollbackVerified: boolean; + intentAligned?: boolean; + intentGap?: string; } export interface ColumnDefinition { diff --git a/tests/sql-normalizer-readonly.test.ts b/tests/sql-normalizer-readonly.test.ts new file mode 100644 index 0000000..09c4f82 --- /dev/null +++ b/tests/sql-normalizer-readonly.test.ts @@ -0,0 +1,146 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { SqliteAdapter } from "../src/adapters/sqlite.js"; +import { DEFAULT_CONFIG } from "../src/config/index.js"; +import { normalizeSqlForAudit, parseSql } from "../src/guard/ast.js"; +import { SqlGuardEngine } from "../src/guard/engine.js"; +import { SandboxEngine } from "../src/sandbox/engine.js"; + +describe("Phase 1: DBShield SQL Normalizer, Read-Only Envelopes & Intent-Effect Gap", () => { + describe("AST Lexical Token Normalizer (normalizeSqlForAudit)", () => { + it("neutralizes zero-width and invisible unicode characters (Unicode smuggling)", () => { + const sqlWithZeroWidth = "SEL\u200BECT \uFEFF* FROM \u200Dusers\u00A0WHERE id = 1"; + const result = normalizeSqlForAudit(sqlWithZeroWidth); + + assert.equal(result.hasUnicodeSmuggling, true); + assert.equal(result.normalizedSql, "SELECT * FROM users WHERE id = 1"); + assert.deepEqual(result.tokens, ["SELECT", "*", "FROM", "users", "WHERE", "id", "=", "1"]); + }); + + it("detects inline comment evasion within keywords (e.g. SEL/**/ECT)", () => { + const evasionSql = "SEL/**/ECT * FR/**/OM users"; + const result = normalizeSqlForAudit(evasionSql); + + assert.equal(result.hasCommentEvasion, true); + assert.equal(result.normalizedSql, "SELECT * FROM users"); + }); + + it("detects unquoted multi-statement injection while preserving semicolons inside strings", () => { + const injectionSql = "SELECT * FROM users; DROP TABLE audits; DELETE FROM accounts;"; + const result = normalizeSqlForAudit(injectionSql); + + assert.equal(result.hasMultiStatement, true); + assert.equal( + result.normalizedSql, + "SELECT * FROM users; DROP TABLE audits; DELETE FROM accounts", + ); + + // Verify semicolon inside string literals is NOT flagged as multi-statement + const safeSql = + "SELECT * FROM logs WHERE message = 'semicolon; here; not; injection' AND code = 200;"; + const safeResult = normalizeSqlForAudit(safeSql); + + assert.equal(safeResult.hasMultiStatement, false); + assert.equal( + safeResult.normalizedSql, + "SELECT * FROM logs WHERE message = 'semicolon; here; not; injection' AND code = 200", + ); + }); + + it("integrates seamlessly into parseSql and flags isMultiStatement correctly", () => { + const injection = "UPDATE users SET active = 1; DROP TABLE logs;"; + const parsed = parseSql(injection, "sqlite"); + + assert.equal(parsed.isMultiStatement, true); + }); + }); + + describe("Dry Run Sandbox: Intent vs. Effect Gap Analysis", () => { + it("detects discrepancy when stated intent implies single-row mutation but simulation affects multiple", async () => { + const adapter = new SqliteAdapter(":memory:"); + await adapter.connect(); + + // Seed mock table with 10 rows + await adapter.query( + "CREATE TABLE users (id INTEGER PRIMARY KEY, status TEXT, active INTEGER);", + ); + for (let i = 1; i <= 10; i++) { + await adapter.query(`INSERT INTO users (id, status, active) VALUES (${i}, 'pending', 0);`); + } + + const guard = new SqlGuardEngine(DEFAULT_CONFIG); + const sandbox = new SandboxEngine(adapter, guard, DEFAULT_CONFIG); + + // Agent provides intent claiming "Update single user status" but executes broad update + const broadSql = "UPDATE users SET status = 'active' WHERE active = 0"; + const dryRunRes = await sandbox.dryRun(broadSql, [], { + intent: "Update single user status to active", + }); + + assert.equal(dryRunRes.safe, true); + assert.equal(dryRunRes.simulatedAffectedRows, 10); + assert.equal(dryRunRes.intentAligned, false); + assert.match(dryRunRes.intentGap || "", /INTENT_EFFECT_DISCREPANCY/); + assert.match(dryRunRes.intentGap || "", /implied single-record modification/); + + // Verify database state was untouched (auto-rollback verified) + const countRes = await adapter.query( + "SELECT COUNT(*) as count FROM users WHERE status = 'active';", + ); + assert.equal(Number((countRes.rows[0] as { count: number }).count), 0); + assert.equal(dryRunRes.rollbackVerified, true); + + await adapter.disconnect(); + }); + + it("verifies intent alignment when expectedAffectedRows matches simulation", async () => { + const adapter = new SqliteAdapter(":memory:"); + await adapter.connect(); + + await adapter.query("CREATE TABLE items (id INTEGER PRIMARY KEY, qty INTEGER);"); + await adapter.query("INSERT INTO items (id, qty) VALUES (1, 5), (2, 10);"); + + const guard = new SqlGuardEngine(DEFAULT_CONFIG); + const sandbox = new SandboxEngine(adapter, guard, DEFAULT_CONFIG); + + const targetSql = "UPDATE items SET qty = 15 WHERE id = 1"; + const dryRunRes = await sandbox.dryRun(targetSql, [], { + expectedAffectedRows: 1, + intent: "Update specific item quantity", + }); + + assert.equal(dryRunRes.safe, true); + assert.equal(dryRunRes.simulatedAffectedRows, 1); + assert.equal(dryRunRes.intentAligned, true); + assert.equal(dryRunRes.intentGap, undefined); + + await adapter.disconnect(); + }); + + it("flags discrepancy when expectedAffectedRows differs from simulated rows", async () => { + const adapter = new SqliteAdapter(":memory:"); + await adapter.connect(); + + await adapter.query("CREATE TABLE items (id INTEGER PRIMARY KEY, qty INTEGER);"); + await adapter.query("INSERT INTO items (id, qty) VALUES (1, 5), (2, 10);"); + + const guard = new SqlGuardEngine(DEFAULT_CONFIG); + const sandbox = new SandboxEngine(adapter, guard, DEFAULT_CONFIG); + + const targetSql = "UPDATE items SET qty = 15 WHERE qty > 0"; + const dryRunRes = await sandbox.dryRun(targetSql, [], { + expectedAffectedRows: 1, + }); + + assert.equal(dryRunRes.safe, true); + assert.equal(dryRunRes.simulatedAffectedRows, 2); + assert.equal(dryRunRes.intentAligned, false); + assert.match( + dryRunRes.intentGap || "", + /Expected affected rows was 1, but simulated execution affected 2 rows/, + ); + + await adapter.disconnect(); + }); + }); +});