Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/adapters/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
124 changes: 120 additions & 4 deletions src/guard/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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: [],
Expand All @@ -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) {
Expand All @@ -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,
};
}
Expand Down
39 changes: 37 additions & 2 deletions src/sandbox/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ export class SandboxEngine {
return this.tokenManager;
}

public async dryRun(sql: string, params: unknown[] = []): Promise<DryRunResult> {
public async dryRun(
sql: string,
params: unknown[] = [],
options?: { intent?: string; expectedAffectedRows?: number },
): Promise<DryRunResult> {
const evaluation = this.guard.evaluate(sql);

// If AST guardrail outright blocks the query (unconstrained delete, tautology, DROP)
Expand All @@ -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;
Expand All @@ -64,6 +95,8 @@ export class SandboxEngine {
`[EXCESSIVE_BLAST_RADIUS] ${blastWarning} Execution blocked across all safety tiers.`,
],
rollbackVerified: adapterResult.rollbackVerified,
intentAligned: false,
intentGap: blastWarning,
};
}

Expand Down Expand Up @@ -94,6 +127,8 @@ export class SandboxEngine {
expiresAt: tokenInfo.expiresAt,
warnings,
rollbackVerified: adapterResult.rollbackVerified,
intentAligned,
intentGap,
};
}

Expand Down
2 changes: 2 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export interface DryRunResult {
expiresAt?: string;
warnings: string[];
rollbackVerified: boolean;
intentAligned?: boolean;
intentGap?: string;
}

export interface ColumnDefinition {
Expand Down
Loading
Loading