feat(safety): add production environment safeguards

This commit is contained in:
wuxiemian authored and GitHub committed 2026-07-12 10:02:27 +08:00
1 parent be66d6f46b
commit 1be66fb115
80 files changed
+4220 -234

No files matched your search

@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { buildAiAgentPlan } from "../aiAgentPlan";
import { classifyAiSqlExecution } from "../aiSqlExecutionPolicy";
import type { ConnectionConfig } from "@/types/database";
const productionConnection: ConnectionConfig = {
id: "conn-1",
name: "Operations",
db_type: "mysql",
host: "db.internal",
port: 3306,
username: "readonly",
password: "",
production_databases: ["prod_app"],
};
describe("AI production SQL policy", () => {
it("requires confirmation for a scoped production write", () => {
expect(classifyAiSqlExecution("UPDATE users SET active = 1 WHERE id = 7", productionConnection, "prod_app")).toMatchObject({
action: "confirm",
environment: "production",
reasons: ["production_write"],
});
});
it("hands production write SQL back to the operator instead of auto-executing", () => {
const plan = buildAiAgentPlan({
mode: "agent",
action: "generate",
instruction: "execute the update",
assistantContent: "```sql\nUPDATE users SET active = 1 WHERE id = 7\n```",
connection: productionConnection,
database: "prod_app",
});
expect(plan.executableSql).toBeUndefined();
expect(plan.handoffSql).toContain("UPDATE users");
expect(plan.steps).toContainEqual({ kind: "execute_sql", status: "skipped", reason: "requires_confirmation" });
});
});
+2 -1
View File
@@ -22,6 +22,7 @@ export interface AiAgentPlanInput {
instruction: string;
assistantContent: string;
connection?: ConnectionConfig;
database?: string;
}
export interface AiAgentPlan {
@@ -61,7 +62,7 @@ export function buildAiAgentPlan(input: AiAgentPlanInput): AiAgentPlan {
return { steps };
}
const decision = classifyAiSqlExecution(sql, input.connection);
const decision = classifyAiSqlExecution(sql, input.connection, input.database);
steps.push({ kind: "risk_check", status: "done", ...decision });
if (decision.action === "auto_execute") {
+25 -27
View File
@@ -1,4 +1,6 @@
import type { ConnectionConfig } from "@/types/database";
import { assessProductionSql, productionContextForDatabase } from "@/lib/database/productionSafety";
import { classifySqlStatementRisk, splitSqlStatementsForSafety, sqlSafetyText } from "@/lib/sql/sqlRisk";
export type ConnectionEnvironment = "production" | "non_production" | "unknown";
export type AiSqlExecutionAction = "auto_execute" | "confirm" | "block";
@@ -11,40 +13,29 @@ export interface AiSqlExecutionDecision {
reasons: string[];
}
const READ_RE = /^(SELECT|WITH|SHOW|DESCRIBE|DESC|EXPLAIN)\b/i;
const INSERT_RE = /^INSERT\b/i;
const UPDATE_RE = /^UPDATE\b/i;
const DELETE_RE = /^DELETE\b/i;
const CONFIRM_WRITE_RE = /^(MERGE|REPLACE)\b/i;
const BLOCK_RE = /^(DROP|TRUNCATE|ALTER|RENAME)\b/i;
const SCHEMA_RE = /^(CREATE)\b/i;
const PRODUCTION_RE = /\b(prod|prd|production)\b|生产|正式/i;
const NON_PRODUCTION_RE = /\b(local|localhost|dev|develop|development|test|testing|stage|staging|sandbox|demo)\b|本地|开发|测试|预发/i;
const LOCAL_HOST_RE = /^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|::1)$/i;
const NEGATIVE_EXECUTION_RE = /(不要|别|不用|禁止|只生成|仅生成|只写|仅写).{0,12}(执行|运行|跑)|do\s+not\s+execute|don't\s+execute|dont\s+execute|without\s+executing|only\s+(generate|write|return)/i;
export function stripAiSqlComments(sql: string): string {
return sql
.replace(/\/\*[\s\S]*?\*\//g, " ")
.replace(/--.*$/gm, " ")
.replace(/#.*$/gm, " ");
return sqlSafetyText(sql);
}
function sqlStatements(sql: string): string[] {
return stripAiSqlComments(sql)
.split(";")
.map((stmt) => stmt.trim())
.filter(Boolean);
return splitSqlStatementsForSafety(sql);
}
function classifyStatement(statement: string): AiSqlExecutionCategory {
if (READ_RE.test(statement)) return "read";
if (BLOCK_RE.test(statement)) return "dangerous";
if (SCHEMA_RE.test(statement)) return "schema_change";
if (INSERT_RE.test(statement)) return "low_risk_write";
if (UPDATE_RE.test(statement)) return isScopedUpdate(statement) ? "low_risk_write" : "dangerous";
if (DELETE_RE.test(statement) || CONFIRM_WRITE_RE.test(statement)) return "write";
function classifyStatement(statement: string, connection?: ConnectionConfig): AiSqlExecutionCategory {
const risk = classifySqlStatementRisk(statement, { dialect: connection?.db_type });
if (risk.risk === "read") return "read";
if (risk.risk === "unknown") return "unknown";
if (risk.risk === "transaction" || risk.risk === "ddl") {
return risk.firstKeyword === "create" ? "schema_change" : "dangerous";
}
if (risk.firstKeyword === "insert") return "low_risk_write";
if (risk.firstKeyword === "update") return isScopedUpdate(statement) ? "low_risk_write" : "dangerous";
if (risk.firstKeyword === "delete" || risk.firstKeyword === "merge" || risk.firstKeyword === "replace") return "write";
return "unknown";
}
@@ -56,8 +47,9 @@ function isScopedUpdate(statement: string): boolean {
return /\b[\w"`.[\]]*(?:id|_id|uuid|key)[\w"`.[\]]*\s*=\s*(?:'[^']+'|"[^"]+"|`[^`]+`|[\w.-]+)/i.test(where);
}
export function classifyConnectionEnvironment(connection?: ConnectionConfig): ConnectionEnvironment {
export function classifyConnectionEnvironment(connection?: ConnectionConfig, database?: string): ConnectionEnvironment {
if (!connection) return "unknown";
if (productionContextForDatabase(connection, database).active) return "production";
const parts = [connection.name, connection.host, connection.database, connection.connection_string].filter(Boolean);
const signal = parts.join(" ");
@@ -66,8 +58,8 @@ export function classifyConnectionEnvironment(connection?: ConnectionConfig): Co
return "unknown";
}
export function classifyAiSqlExecution(sql: string, connection?: ConnectionConfig): AiSqlExecutionDecision {
const environment = classifyConnectionEnvironment(connection);
export function classifyAiSqlExecution(sql: string, connection?: ConnectionConfig, database?: string): AiSqlExecutionDecision {
const environment = classifyConnectionEnvironment(connection, database);
const statements = sqlStatements(sql);
const reasons: string[] = [];
@@ -75,9 +67,10 @@ export function classifyAiSqlExecution(sql: string, connection?: ConnectionConfi
return { action: "block", environment, category: "unknown", reasons: ["empty_sql"] };
}
const categories = statements.map(classifyStatement);
const categories = statements.map((statement) => classifyStatement(statement, connection));
const hasMultipleStatements = statements.length > 1;
if (hasMultipleStatements) reasons.push("multi_statement");
const productionAssessment = assessProductionSql(sql, connection, database);
if (categories.includes("dangerous")) {
return { action: "block", environment, category: "dangerous", reasons };
@@ -91,6 +84,11 @@ export function classifyAiSqlExecution(sql: string, connection?: ConnectionConfi
return { action: "auto_execute", environment, category: "read", reasons };
}
if (productionAssessment.active && productionAssessment.isMutation) {
reasons.push("production_write");
return { action: "confirm", environment: "production", category: categories[0] ?? "unknown", reasons };
}
if (hasMultipleStatements) {
return { action: "confirm", environment, category: "write", reasons };
}
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import { executeWithProductionSqlGuard } from "../productionExecutionGuard";
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import type { ConnectionConfig } from "@/types/database";
function connection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
return {
id: "conn-1",
name: "Operations",
db_type: "mysql",
host: "db.internal",
port: 3306,
username: "operator",
password: "",
production_databases: ["prod_app"],
...overrides,
};
}
describe("production SQL execution guard", () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it("waits for confirmation before executing production SQL", async () => {
const execute = vi.fn().mockResolvedValue("done");
const pendingExecution = executeWithProductionSqlGuard({
connection: connection(),
database: "prod_app",
sql: "DELETE FROM users WHERE id = 1",
source: "Schema diff",
execute,
});
await Promise.resolve();
const store = useProductionSafetyStore();
expect(store.pending).toMatchObject({
sql: "DELETE FROM users WHERE id = 1",
database: "prod_app",
productionDatabases: ["prod_app"],
source: "Schema diff",
});
expect(execute).not.toHaveBeenCalled();
store.confirm();
await expect(pendingExecution).resolves.toBe("done");
expect(execute).toHaveBeenCalledTimes(1);
});
it("cancels production SQL without executing the callback", async () => {
const execute = vi.fn().mockResolvedValue("done");
const pendingExecution = executeWithProductionSqlGuard({
connection: connection(),
database: "prod_app",
sql: "TRUNCATE TABLE users",
source: "Object tree",
execute,
});
await Promise.resolve();
useProductionSafetyStore().cancel();
await expect(pendingExecution).resolves.toBeUndefined();
expect(execute).not.toHaveBeenCalled();
});
it("queues concurrent production confirmations", async () => {
const firstExecute = vi.fn().mockResolvedValue("first");
const secondExecute = vi.fn().mockResolvedValue("second");
const firstSql = "DELETE FROM prod_app.users WHERE id = 1";
const secondSql = "DELETE FROM prod_app.audit_log WHERE id = 2";
const firstExecution = executeWithProductionSqlGuard({
connection: connection(),
database: "staging",
sql: firstSql,
source: "Schema diff",
execute: firstExecute,
});
const secondExecution = executeWithProductionSqlGuard({
connection: connection(),
database: "staging",
sql: secondSql,
source: "Data compare",
execute: secondExecute,
});
await Promise.resolve();
const store = useProductionSafetyStore();
expect(store.pending?.sql).toBe(firstSql);
expect(firstExecute).not.toHaveBeenCalled();
expect(secondExecute).not.toHaveBeenCalled();
store.confirm();
await expect(firstExecution).resolves.toBe("first");
expect(firstExecute).toHaveBeenCalledTimes(1);
expect(store.pending?.sql).toBe(secondSql);
store.cancel();
await expect(secondExecution).resolves.toBeUndefined();
expect(secondExecute).not.toHaveBeenCalled();
});
it("executes non-production SQL immediately", async () => {
const execute = vi.fn().mockResolvedValue("done");
await expect(
executeWithProductionSqlGuard({
connection: connection(),
database: "staging",
sql: "UPDATE staging.users SET active = 1 WHERE id = 1",
source: "Data compare",
execute,
}),
).resolves.toBe("done");
expect(useProductionSafetyStore().pending).toBeUndefined();
expect(execute).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { assessProductionSql, isProductionMutation, productionContextForDatabase } from "../productionSafety";
import type { ConnectionConfig, DatabaseType } from "@/types/database";
interface ProductionSafetyCorpusCase {
name: string;
dialect: DatabaseType;
productionDatabases: string[];
activeDatabase: string;
sql: string;
active: boolean;
isMutation: boolean;
databases: string[];
}
const productionSafetyCorpus = JSON.parse(readFileSync(new URL("../../../../../../tests/fixtures/production-safety-corpus.json", import.meta.url), "utf8")) as ProductionSafetyCorpusCase[];
function connection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
return {
id: "conn-1",
name: "Operations",
db_type: "mysql",
host: "db.internal",
port: 3306,
username: "readonly",
password: "",
production_databases: ["prod_app"],
...overrides,
};
}
describe("production SQL safety", () => {
it("marks an explicitly production connection regardless of database", () => {
expect(productionContextForDatabase(connection({ is_production: true }), "scratch").active).toBe(true);
});
it("marks only configured production databases for multi-database connections", () => {
expect(productionContextForDatabase(connection(), "PROD_APP").active).toBe(true);
expect(productionContextForDatabase(connection(), "staging").active).toBe(false);
});
it("detects a write after a USE production switch despite comments", () => {
const assessment = assessProductionSql("-- install\nUSE `prod_app`; /* migration */ DELETE FROM users", connection(), "staging");
expect(assessment).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
});
it("detects qualified production targets in multi-statement SQL", () => {
const assessment = assessProductionSql("SELECT ';' AS literal; DELETE FROM `prod_app`.`orders`; UPDATE staging.users SET active = 1", connection(), "staging");
expect(assessment).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
});
it("detects production database DDL without a selected production database", () => {
expect(assessProductionSql("DROP DATABASE IF EXISTS prod_app", connection(), "staging")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
});
it("detects production writes hidden behind parser-sensitive SQL forms", () => {
for (const sql of ["EXPLAIN ANALYZE DELETE FROM prod_app.users WHERE id = 1", "/*! DELETE FROM prod_app.users WHERE id = 1 */", "COPY prod_app.users FROM '/tmp/users.csv'", "SELECT * INTO prod_app.backup_users FROM users", "SELECT * FROM prod_app.users INTO OUTFILE '/tmp/users.csv'"]) {
expect(assessProductionSql(sql, connection(), "staging")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
}
});
it("matches the shared SQL target safety corpus", () => {
for (const corpusCase of productionSafetyCorpus) {
const assessment = assessProductionSql(
corpusCase.sql,
connection({
db_type: corpusCase.dialect,
production_databases: corpusCase.productionDatabases,
}),
corpusCase.activeDatabase,
);
expect(
{
active: assessment.active,
isMutation: assessment.isMutation,
databases: assessment.databases,
},
corpusCase.name,
).toEqual({
active: corpusCase.active,
isMutation: corpusCase.isMutation,
databases: corpusCase.databases,
});
}
});
it("detects qualified procedure calls and privilege targets", () => {
for (const sql of ["CALL prod_app.purge_users()", "CALL `prod_app`.`purge_users`()", "GRANT ALL ON prod_app.* TO 'u'@'%'", "GRANT EXECUTE ON PROCEDURE prod_app.purge_users TO 'u'@'%'"]) {
expect(assessProductionSql(sql, connection(), "staging")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
}
});
it("allows resolved non-production procedure and privilege targets", () => {
expect(assessProductionSql("CALL staging.purge_users()", connection(), "staging")).toMatchObject({ active: false, isMutation: true });
expect(assessProductionSql("GRANT ALL ON staging.* TO 'u'@'%'", connection(), "staging")).toMatchObject({ active: false, isMutation: true });
});
it("conservatively confirms ambiguous production targets", () => {
for (const sql of ["CALL purge_users()", "GRANT PROCESS ON *.* TO 'u'@'%'", "GRANT ALL ON users TO 'u'@'%'", "CREATE USER 'u'@'%'"]) {
expect(assessProductionSql(sql, connection(), "staging")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
}
});
it("does not treat read-only qualified references as write targets", () => {
expect(assessProductionSql("SELECT * FROM prod_app.orders; DELETE FROM staging.users WHERE id = 1", connection(), "staging")).toMatchObject({ active: false, isMutation: true });
});
it("treats unrecognized SQL as a production mutation until proven read-only", () => {
expect(isProductionMutation("MAINTAIN UNKNOWN THING")).toBe(true);
expect(assessProductionSql("MAINTAIN UNKNOWN THING", connection(), "prod_app")).toMatchObject({ active: true, isMutation: true });
});
it("does not require a production confirmation for reads", () => {
expect(assessProductionSql("SELECT * FROM prod_app.orders", connection(), "staging")).toMatchObject({ active: false, isMutation: false });
});
});
@@ -0,0 +1,28 @@
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import { assessProductionSql } from "@/lib/database/productionSafety";
import type { ConnectionConfig } from "@/types/database";
export interface ProductionSqlExecutionGuardOptions<T> {
connection?: ConnectionConfig;
database?: string | null;
sql: string;
source?: string;
execute: () => Promise<T>;
}
export async function executeWithProductionSqlGuard<T>(options: ProductionSqlExecutionGuardOptions<T>): Promise<T | undefined> {
const assessment = assessProductionSql(options.sql, options.connection, options.database);
if (assessment.active && assessment.isMutation) {
// Centralize production write confirmation so secondary tool surfaces cannot
// bypass the same explicit review step used by the SQL editor.
const confirmed = await useProductionSafetyStore().requestConfirmation({
sql: options.sql,
connectionName: options.connection?.name,
database: options.database ?? undefined,
productionDatabases: assessment.databases,
source: options.source,
});
if (!confirmed) return undefined;
}
return options.execute();
}
@@ -0,0 +1,347 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { classifySqlRisk, isSqlRiskMutation } from "@/lib/sql/sqlRisk";
export type ProductionContextReason = "connection" | "database" | "sql_target";
export interface ProductionContext {
active: boolean;
reason?: ProductionContextReason;
databases: string[];
}
export interface ProductionSqlAssessment extends ProductionContext {
isMutation: boolean;
}
const IDENTIFIER_PATTERN = String.raw`[A-Za-z0-9_@$#-]*[A-Za-z_@$#][A-Za-z0-9_@$#-]*`;
const TARGET_NAME_PATTERN = String.raw`${IDENTIFIER_PATTERN}(?:\s*\.\s*(?:\*|${IDENTIFIER_PATTERN})){0,2}`;
const QUALIFIED_NAME_PATTERN = String.raw`${IDENTIFIER_PATTERN}\s*\.\s*(?:\*|${IDENTIFIER_PATTERN})(?:\s*\.\s*(?:\*|${IDENTIFIER_PATTERN}))?`;
const USE_RE = new RegExp(String.raw`^\s*USE\s+(${IDENTIFIER_PATTERN})`, "i");
const DML_TARGET_RE = new RegExp(String.raw`\b(?:FROM|JOIN|UPDATE|INTO|REFERENCES)\s+(${TARGET_NAME_PATTERN})`, "gi");
const DDL_OBJECT_TARGET_RE = new RegExp(String.raw`\b(?:CREATE|ALTER|DROP)\s+(?:OR\s+REPLACE\s+)?(?:TABLE|VIEW|MATERIALIZED\s+VIEW|INDEX|SEQUENCE|FUNCTION|PROCEDURE|ROUTINE|TRIGGER|EVENT|TYPE|SYNONYM)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?:ONLY\s+)?(${TARGET_NAME_PATTERN})`, "gi");
const INDEX_ON_TARGET_RE = new RegExp(String.raw`\b(?:CREATE|ALTER|DROP)\s+(?:UNIQUE\s+)?INDEX\b[\s\S]*?\bON\s+(${TARGET_NAME_PATTERN})`, "gi");
const DATABASE_TARGET_RE = new RegExp(String.raw`\b(?:CREATE|ALTER|DROP)\s+(DATABASE|SCHEMA|CATALOG)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(${IDENTIFIER_PATTERN})`, "gi");
const COPY_TARGET_RE = new RegExp(String.raw`^\s*COPY\s+(${TARGET_NAME_PATTERN})\s+FROM\b`, "i");
const TRUNCATE_TARGET_RE = new RegExp(String.raw`\bTRUNCATE\s+(?:TABLE\s+)?(${TARGET_NAME_PATTERN})`, "gi");
const RENAME_TABLE_TARGET_RE = new RegExp(String.raw`\bRENAME\s+TABLE\s+(${TARGET_NAME_PATTERN})\s+TO\s+(${TARGET_NAME_PATTERN})`, "gi");
const MAINTENANCE_TABLE_TARGET_RE = new RegExp(String.raw`\b(?:ANALYZE|OPTIMIZE|REPAIR|CHECK)\s+(?:NO_WRITE_TO_BINLOG\s+|LOCAL\s+)?TABLE\s+(${TARGET_NAME_PATTERN})`, "gi");
const COMMENT_TARGET_RE = new RegExp(String.raw`\bCOMMENT\s+ON\s+(?:TABLE|VIEW|COLUMN|INDEX|SEQUENCE|FUNCTION|PROCEDURE|TYPE)\s+(${TARGET_NAME_PATTERN})`, "gi");
const ROUTINE_CALL_TARGET_RE = new RegExp(String.raw`\b(?:CALL|EXEC|EXECUTE)\s+(${QUALIFIED_NAME_PATTERN})`, "gi");
const PRIVILEGE_TARGET_RE = new RegExp(String.raw`\b(?:GRANT|REVOKE|DENY)\b[\s\S]*?\bON\s+(?:(?:TABLE|SEQUENCE|FUNCTION|PROCEDURE|ROUTINE|OBJECT)\s+|OBJECT\s*::\s*)?(${QUALIFIED_NAME_PATTERN})`, "gi");
const PRIVILEGE_DATABASE_TARGET_RE = new RegExp(String.raw`\b(?:GRANT|REVOKE|DENY)\b[\s\S]*?\bON\s+(?:DATABASE|CATALOG)(?:::|\s+)\s*(${IDENTIFIER_PATTERN})`, "gi");
const GLOBAL_PRIVILEGE_TARGET_RE = /\b(?:GRANT|REVOKE|DENY)\b[\s\S]*?\bON\s+\*\s*\.\s*\*/i;
const GLOBAL_DDL_TARGET_RE = /^\s*(?:CREATE|ALTER|DROP)\s+(?:USER|ROLE|LOGIN|SERVER|TABLESPACE|RESOURCE|PROFILE|ACCOUNT)\b/i;
const MULTI_TARGET_MUTATION_RE = /^\s*(?:DROP\s+(?:TEMPORARY\s+)?TABLE\b[\s\S]*,|RENAME\s+TABLE\b[\s\S]*,)/i;
const THREE_PART_DATABASE_QUALIFIER_TYPES = new Set<DatabaseType>(["sqlserver", "snowflake", "trino", "prestosql", "databricks", "bigquery"]);
const TRANSACTION_KEYWORDS = new Set(["begin", "start", "commit", "rollback", "abort", "savepoint", "release"]);
const SCHEMA_FIRST_QUALIFIER_TYPES = new Set<DatabaseType>([
"postgres",
"redshift",
"gaussdb",
"kwdb",
"opengauss",
"kingbase",
"highgo",
"vastbase",
"yashandb",
"oracle",
"oceanbase-oracle",
"dameng",
"firebird",
"exasol",
"teradata",
"vertica",
"db2",
"informix",
"h2",
"iris",
"xugu",
"oscar",
"gbase",
"saphana",
"sqlserver",
"snowflake",
"trino",
"prestosql",
"databricks",
"bigquery",
]);
interface ReferencedDatabaseAssessment {
databases: string[];
uncertain: boolean;
}
interface SqlTargetSafetyText {
text: string;
quotedIdentifiers: Map<string, string>;
}
/**
* Normalize database identifiers for safety matching while retaining the
* original display value separately. Safety comparisons intentionally ignore
* identifier quoting and case so a quoted MySQL production database cannot
* bypass its marker.
*/
export function normalizeProductionDatabase(value: string | undefined | null): string {
return String(value ?? "")
.trim()
.replace(/^[`"[]|[`"\]]$/g, "")
.toLowerCase();
}
export function productionDatabases(connection: ConnectionConfig | undefined): string[] {
if (!connection?.production_databases?.length) return [];
return [...new Set(connection.production_databases.map(normalizeProductionDatabase).filter(Boolean))];
}
export function productionContextForDatabase(connection: ConnectionConfig | undefined, database: string | undefined | null): ProductionContext {
if (!connection) return { active: false, databases: [] };
if (connection.is_production) return { active: true, reason: "connection", databases: [] };
const normalizedDatabase = normalizeProductionDatabase(database);
const marked = productionDatabases(connection);
if (normalizedDatabase && marked.includes(normalizedDatabase)) {
return { active: true, reason: "database", databases: [String(database)] };
}
return { active: false, databases: [] };
}
export function isProductionMutation(sql: string): boolean {
return isSqlRiskMutation(classifySqlRisk(sql).risk);
}
/**
* Resolves production scope for the SQL about to run. The active database is
* authoritative for ordinary statements; MySQL-style USE and qualified names
* additionally protect production databases referenced from another context.
*/
export function assessProductionSql(sql: string, connection: ConnectionConfig | undefined, activeDatabase: string | undefined | null): ProductionSqlAssessment {
const activeContext = productionContextForDatabase(connection, activeDatabase);
const targetText = sqlTargetSafetyText(sql);
const statements = splitTargetStatements(targetText.text);
const risk = classifySqlRisk(sql, { dialect: connection?.db_type });
const isMutation = isSqlRiskMutation(risk.risk);
if (!isMutation || !connection) return { ...activeContext, isMutation };
if (connection.is_production) return { active: true, reason: "connection", databases: [], isMutation };
if (activeContext.active) return { ...activeContext, isMutation };
const marked = productionDatabases(connection);
if (!marked.length) return { active: false, databases: [], isMutation };
const targets = referencedDatabases(statements, connection.db_type, activeDatabase, targetText.quotedIdentifiers);
const matched = targets.databases.filter((database) => marked.includes(normalizeProductionDatabase(database)));
if (matched.length) return { active: true, reason: "sql_target", databases: matched, isMutation };
if (targets.uncertain) return { active: true, reason: "sql_target", databases: marked, isMutation };
return { active: false, databases: [], isMutation };
}
function referencedDatabases(statements: string[], dbType: DatabaseType, activeDatabase: string | undefined | null, quotedIdentifiers: Map<string, string>): ReferencedDatabaseAssessment {
const databases = new Set<string>();
let uncertain = false;
let useDatabase = "";
const normalizedActiveDatabase = normalizeProductionDatabase(activeDatabase);
for (const statement of statements) {
const statementDatabases = new Set<string>();
const statementAssessment = classifySqlRisk(statement, { dialect: dbType });
const statementIsMutation = isSqlRiskMutation(statementAssessment.risk);
const useMatch = statement.match(USE_RE);
if (useMatch?.[1]) {
useDatabase = normalizeTargetDatabase(useMatch[1], quotedIdentifiers);
continue;
}
if (!statementIsMutation) continue;
const currentDatabase = useDatabase || normalizedActiveDatabase;
collectQualifiedTargetDatabases(statement, dbType, quotedIdentifiers, currentDatabase, statementDatabases, DML_TARGET_RE, DDL_OBJECT_TARGET_RE, INDEX_ON_TARGET_RE, TRUNCATE_TARGET_RE, MAINTENANCE_TABLE_TARGET_RE, COMMENT_TARGET_RE, ROUTINE_CALL_TARGET_RE, PRIVILEGE_TARGET_RE);
collectQualifiedTargetDatabaseGroups(statement, dbType, quotedIdentifiers, currentDatabase, statementDatabases, RENAME_TABLE_TARGET_RE, [1, 2]);
for (const match of statement.matchAll(DATABASE_TARGET_RE)) {
const database = databaseTargetKindMeansDatabase(match[1], dbType) ? normalizeTargetDatabase(match[2], quotedIdentifiers) : "";
if (database) statementDatabases.add(database);
}
for (const match of statement.matchAll(PRIVILEGE_DATABASE_TARGET_RE)) {
const database = normalizeTargetDatabase(match[1], quotedIdentifiers);
if (database) statementDatabases.add(database);
}
const copyTarget = statement.match(COPY_TARGET_RE);
if (copyTarget?.[1]) {
const database = databaseFromQualifiedName(copyTarget[1], dbType, quotedIdentifiers, currentDatabase);
if (database) statementDatabases.add(database);
}
for (const database of statementDatabases) databases.add(database);
// The target regexes intentionally extract one object at a time. Until all
// list forms are parsed, never let a resolved first target disable fallback.
uncertain = uncertain || GLOBAL_PRIVILEGE_TARGET_RE.test(statement) || MULTI_TARGET_MUTATION_RE.test(statement) || isAmbiguousProductionTargetStatement(statement, statementAssessment, statementDatabases.size > 0);
}
return { databases: [...databases], uncertain };
}
function collectQualifiedTargetDatabases(statement: string, dbType: DatabaseType, quotedIdentifiers: Map<string, string>, currentDatabase: string, databases: Set<string>, ...patterns: RegExp[]): void {
for (const pattern of patterns) {
collectQualifiedTargetDatabaseGroups(statement, dbType, quotedIdentifiers, currentDatabase, databases, pattern, [1]);
}
}
function collectQualifiedTargetDatabaseGroups(statement: string, dbType: DatabaseType, quotedIdentifiers: Map<string, string>, currentDatabase: string, databases: Set<string>, pattern: RegExp, captureIndexes: number[]): void {
pattern.lastIndex = 0;
for (const match of statement.matchAll(pattern)) {
for (const captureIndex of captureIndexes) {
const database = databaseFromQualifiedName(match[captureIndex], dbType, quotedIdentifiers, currentDatabase);
if (database) databases.add(database);
}
}
}
function databaseFromQualifiedName(qualifiedName: string | undefined, dbType: DatabaseType, quotedIdentifiers: Map<string, string>, currentDatabase: string): string {
const parts = String(qualifiedName ?? "")
.split(".")
.map((part) => normalizeTargetDatabase(part, quotedIdentifiers))
.filter(Boolean);
if (parts.length < 2) return currentDatabase;
if (qualifiedFirstPartIsDatabase(dbType, parts.length)) return parts[0] ?? "";
return currentDatabase;
}
function normalizeTargetDatabase(value: string | undefined, quotedIdentifiers: Map<string, string>): string {
const normalized = normalizeProductionDatabase(value);
const quoted = quotedIdentifiers.get(normalized);
return quoted === undefined ? normalized : normalizeProductionDatabase(quoted);
}
function qualifiedFirstPartIsDatabase(dbType: DatabaseType, partCount: number): boolean {
if (partCount >= 3 && THREE_PART_DATABASE_QUALIFIER_TYPES.has(dbType)) return true;
if (SCHEMA_FIRST_QUALIFIER_TYPES.has(dbType)) return false;
return partCount >= 2;
}
function databaseTargetKindMeansDatabase(kind: string | undefined, dbType: DatabaseType): boolean {
const normalizedKind = String(kind ?? "").toLowerCase();
if (normalizedKind === "database" || normalizedKind === "catalog") return true;
if (normalizedKind !== "schema") return false;
return !SCHEMA_FIRST_QUALIFIER_TYPES.has(dbType);
}
function isAmbiguousProductionTargetStatement(statement: string, assessment: ReturnType<typeof classifySqlRisk>, hasResolvedTarget: boolean): boolean {
if (!isSqlRiskMutation(assessment.risk)) return false;
if (assessment.risk === "transaction") return false;
const firstKeyword = assessment.firstKeyword;
if (firstKeyword && TRANSACTION_KEYWORDS.has(firstKeyword)) return false;
return GLOBAL_DDL_TARGET_RE.test(statement) || !hasResolvedTarget;
}
function splitTargetStatements(sql: string): string[] {
return sql
.split(";")
.map((statement) => statement.trim())
.filter(Boolean);
}
function sqlTargetSafetyText(sql: string, quotedIdentifiers = new Map<string, string>()): SqlTargetSafetyText {
let output = "";
let index = 0;
while (index < sql.length) {
const char = sql[index] ?? "";
const next = sql[index + 1] ?? "";
if (char === "-" && next === "-") {
index += 2;
while (index < sql.length && sql[index] !== "\n" && sql[index] !== "\r") index += 1;
output += " ";
continue;
}
if (char === "#") {
index += 1;
while (index < sql.length && sql[index] !== "\n" && sql[index] !== "\r") index += 1;
output += " ";
continue;
}
if (char === "/" && next === "*") {
const close = sql.indexOf("*/", index + 2);
if (close < 0) return { text: output, quotedIdentifiers };
const executablePrefixLength = mysqlExecutableCommentPrefixLength(sql, index);
if (executablePrefixLength > 0) {
const bodyStart = skipExecutableCommentVersion(sql, index + executablePrefixLength);
output += ` ${sqlTargetSafetyText(sql.slice(bodyStart, close), quotedIdentifiers).text} `;
} else {
output += " ";
}
index = close + 2;
continue;
}
const dollarQuote = dollarQuoteTagAt(sql, index);
if (dollarQuote) {
const close = sql.indexOf(dollarQuote, index + dollarQuote.length);
index = close < 0 ? sql.length : close + dollarQuote.length;
output += " ";
continue;
}
if (char === "'") {
index = readQuotedEnd(sql, index, "'", "'");
output += " ";
continue;
}
if (char === '"' || char === "`" || char === "[") {
const close = char === "[" ? "]" : char;
const end = readQuotedEnd(sql, index, char, close);
const identifier = unquoteIdentifier(sql.slice(index, end), char, close).replace(/[;]/g, " ");
const token = `__dbxq${quotedIdentifiers.size}__`;
quotedIdentifiers.set(token.toLowerCase(), identifier);
output += ` ${token} `;
index = end;
continue;
}
output += char;
index += 1;
}
return { text: output, quotedIdentifiers };
}
function mysqlExecutableCommentPrefixLength(sql: string, index: number): number {
if (sql[index] !== "/" || sql[index + 1] !== "*") return 0;
if (sql[index + 2] === "!") return 3;
if (sql[index + 2] === "M" && sql[index + 3] === "!") return 4;
return 0;
}
function skipExecutableCommentVersion(sql: string, index: number): number {
let cursor = index;
while (cursor < sql.length && /[0-9\s]/.test(sql[cursor] ?? "")) cursor += 1;
return cursor;
}
function dollarQuoteTagAt(sql: string, index: number): string | undefined {
return sql.slice(index).match(/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/)?.[0];
}
function readQuotedEnd(sql: string, start: number, open: string, close: string): number {
let index = start + open.length;
while (index < sql.length) {
if (sql[index] === "\\" && (open === "'" || open === '"')) {
index += 2;
continue;
}
if (sql.startsWith(close, index)) {
if (sql.startsWith(close + close, index)) {
index += close.length * 2;
continue;
}
return index + close.length;
}
index += 1;
}
return sql.length;
}
function unquoteIdentifier(value: string, open: string, close: string): string {
if (!value.startsWith(open) || !value.endsWith(close)) return value;
return value.slice(open.length, value.length - close.length).replaceAll(close + close, close);
}
+276
View File
@@ -0,0 +1,276 @@
import type { DatabaseType } from "@/types/database";
export type SqlRiskLevel = "read" | "write" | "ddl" | "transaction" | "unknown";
export interface SqlRiskStatementAssessment {
risk: SqlRiskLevel;
firstKeyword?: string;
}
export interface SqlRiskAssessment extends SqlRiskStatementAssessment {
statements: SqlRiskStatementAssessment[];
}
interface SqlRiskOptions {
dialect?: DatabaseType | string;
}
interface SqlRiskToken {
text: string;
normalized: string;
}
const READ_KEYWORDS = new Set(["select", "show", "describe", "desc", "values", "table"]);
const WRITE_KEYWORDS = new Set(["insert", "update", "delete", "merge", "replace", "upsert", "load", "call", "exec", "execute", "flush"]);
const DDL_KEYWORDS = new Set(["create", "alter", "drop", "truncate", "rename", "grant", "revoke", "deny", "comment", "reindex", "vacuum", "optimize"]);
const TRANSACTION_KEYWORDS = new Set(["begin", "start", "commit", "rollback", "abort", "savepoint", "release"]);
const EXPLAIN_OPTION_KEYWORDS = new Set(["explain", "analyze", "analyse", "verbose", "query", "plan", "format", "type", "costs", "buffers", "timing", "summary", "settings", "wal", "generic_plan"]);
const PRIMARY_STATEMENT_KEYWORDS = new Set([...READ_KEYWORDS, ...WRITE_KEYWORDS, ...DDL_KEYWORDS, ...TRANSACTION_KEYWORDS, "with", "copy", "pragma", "use", "set"]);
const SAFE_READ_PRAGMA_NAMES = new Set(["table_info", "table_xinfo", "index_list", "index_info", "foreign_key_list", "database_list", "compile_options", "data_version"]);
const RISK_ORDER: Record<SqlRiskLevel, number> = {
read: 0,
write: 1,
ddl: 2,
transaction: 3,
unknown: 4,
};
export function splitSqlStatementsForSafety(sql: string): string[] {
return sqlSafetyText(sql)
.split(";")
.map((statement) => statement.trim())
.filter(Boolean);
}
export function classifySqlRisk(sql: string, options: SqlRiskOptions = {}): SqlRiskAssessment {
const statements = splitSqlStatementsForSafety(sql).map((statement) => classifySqlStatementRisk(statement, options));
if (!statements.length) return { risk: "unknown", statements: [] };
const highest = statements.reduce<SqlRiskStatementAssessment>((current, statement) => (RISK_ORDER[statement.risk] > RISK_ORDER[current.risk] ? statement : current), { risk: "read" });
return { ...highest, statements };
}
export function classifySqlStatementRisk(sql: string, _options: SqlRiskOptions = {}): SqlRiskStatementAssessment {
return classifyTokens(tokenizeSqlForRisk(sql));
}
export function isSqlRiskMutation(risk: SqlRiskLevel): boolean {
return risk !== "read";
}
export function sqlSafetyText(sql: string): string {
let output = "";
let index = 0;
while (index < sql.length) {
const char = sql[index] ?? "";
const next = sql[index + 1] ?? "";
if (char === "-" && next === "-") {
index += 2;
while (index < sql.length && sql[index] !== "\n" && sql[index] !== "\r") index += 1;
output += " ";
continue;
}
if (char === "#") {
index += 1;
while (index < sql.length && sql[index] !== "\n" && sql[index] !== "\r") index += 1;
output += " ";
continue;
}
if (char === "/" && next === "*") {
const close = sql.indexOf("*/", index + 2);
if (close < 0) return output;
const executablePrefixLength = mysqlExecutableCommentPrefixLength(sql, index);
if (executablePrefixLength > 0) {
const bodyStart = skipExecutableCommentVersion(sql, index + executablePrefixLength);
output += ` ${sqlSafetyText(sql.slice(bodyStart, close))} `;
} else {
output += " ";
}
index = close + 2;
continue;
}
const dollarQuote = dollarQuoteTagAt(sql, index);
if (dollarQuote) {
const close = sql.indexOf(dollarQuote, index + dollarQuote.length);
index = close < 0 ? sql.length : close + dollarQuote.length;
output += " ";
continue;
}
if (char === "'") {
index = readQuotedEnd(sql, index, "'", "'");
output += " ";
continue;
}
if (char === '"' || char === "`" || char === "[") {
const close = char === "[" ? "]" : char;
const end = readQuotedEnd(sql, index, char, close);
output += ` ${unquoteIdentifier(sql.slice(index, end), char, close).replace(/[;]/g, " ")} `;
index = end;
continue;
}
output += char;
index += 1;
}
return output;
}
function tokenizeSqlForRisk(sql: string): SqlRiskToken[] {
const tokens: SqlRiskToken[] = [];
const re = /[A-Za-z_@$#][A-Za-z0-9_@$#-]*|[0-9]+|[(),.;*]|\S/g;
for (const match of sql.matchAll(re)) {
const text = match[0];
tokens.push({ text, normalized: /^[A-Za-z_@$#]/.test(text) ? text.toLowerCase() : text });
}
return tokens;
}
function classifyTokens(tokens: SqlRiskToken[]): SqlRiskStatementAssessment {
const useful = trimWrappingParentheses(tokens);
const firstKeyword = useful.find((token) => /^[a-z_]/i.test(token.text))?.normalized;
if (!firstKeyword) return { risk: "unknown" };
if (READ_KEYWORDS.has(firstKeyword)) {
return { risk: firstKeyword === "select" && hasTopLevelSelectInto(useful) ? "write" : "read", firstKeyword };
}
if (firstKeyword === "with") {
return { risk: highestRiskInTokens(useful) ?? "read", firstKeyword };
}
if (firstKeyword === "explain") {
return classifyExplainTokens(useful);
}
if (firstKeyword === "copy") {
return { risk: classifyCopyTokens(useful), firstKeyword };
}
if (firstKeyword === "pragma") {
return { risk: classifyPragmaTokens(useful), firstKeyword };
}
if (firstKeyword === "use") return { risk: "read", firstKeyword };
if (WRITE_KEYWORDS.has(firstKeyword)) return { risk: "write", firstKeyword };
if (DDL_KEYWORDS.has(firstKeyword)) return { risk: "ddl", firstKeyword };
if (TRANSACTION_KEYWORDS.has(firstKeyword)) return { risk: "transaction", firstKeyword };
// Unknown statements are treated as unsafe until a dialect-aware parser can
// prove they are read-only.
return { risk: "unknown", firstKeyword };
}
function classifyExplainTokens(tokens: SqlRiskToken[]): SqlRiskStatementAssessment {
const analyze = tokens.some((token) => token.normalized === "analyze" || token.normalized === "analyse");
const innerIndex = tokens.findIndex((token, index) => index > 0 && PRIMARY_STATEMENT_KEYWORDS.has(token.normalized) && !EXPLAIN_OPTION_KEYWORDS.has(token.normalized));
if (innerIndex < 0) return { risk: "read", firstKeyword: "explain" };
const inner = classifyTokens(tokens.slice(innerIndex));
if (!analyze) return { risk: inner.risk === "unknown" ? "unknown" : "read", firstKeyword: "explain" };
return { risk: inner.risk, firstKeyword: inner.firstKeyword ?? "explain" };
}
function classifyCopyTokens(tokens: SqlRiskToken[]): SqlRiskLevel {
if (tokens.some((token) => token.normalized === "from")) return "write";
if (tokens.some((token) => token.normalized === "to")) return "read";
return "unknown";
}
function classifyPragmaTokens(tokens: SqlRiskToken[]): SqlRiskLevel {
const name = tokens.find((token, index) => index > 0 && /^[a-z_]/i.test(token.text))?.normalized;
if (name && SAFE_READ_PRAGMA_NAMES.has(name) && !tokens.some((token) => token.text === "=")) return "read";
return "write";
}
function highestRiskInTokens(tokens: SqlRiskToken[]): SqlRiskLevel | undefined {
let result: SqlRiskLevel | undefined;
for (const token of tokens) {
const risk = WRITE_KEYWORDS.has(token.normalized) ? "write" : DDL_KEYWORDS.has(token.normalized) ? "ddl" : TRANSACTION_KEYWORDS.has(token.normalized) ? "transaction" : undefined;
if (risk && (!result || RISK_ORDER[risk] > RISK_ORDER[result])) result = risk;
}
return result;
}
function hasTopLevelSelectInto(tokens: SqlRiskToken[]): boolean {
let depth = 0;
for (let index = 0; index < tokens.length; index += 1) {
const token = tokens[index];
if (!token) continue;
if (token.text === "(") depth += 1;
if (token.text === ")") depth = Math.max(0, depth - 1);
if (depth !== 0) continue;
if (token.normalized === "into") return true;
}
return false;
}
function trimWrappingParentheses(tokens: SqlRiskToken[]): SqlRiskToken[] {
let start = 0;
let end = tokens.length;
while (tokens[start]?.text === "(" && matchingParenIndex(tokens, start) === end - 1) {
start += 1;
end -= 1;
}
return tokens.slice(start, end);
}
function matchingParenIndex(tokens: readonly SqlRiskToken[], openIndex: number): number {
let depth = 0;
for (let index = openIndex; index < tokens.length; index += 1) {
if (tokens[index]?.text === "(") depth += 1;
if (tokens[index]?.text === ")") {
depth -= 1;
if (depth === 0) return index;
}
}
return -1;
}
function mysqlExecutableCommentPrefixLength(sql: string, index: number): number {
if (sql[index] !== "/" || sql[index + 1] !== "*") return 0;
if (sql[index + 2] === "!") return 3;
if (sql[index + 2] === "M" && sql[index + 3] === "!") return 4;
return 0;
}
function skipExecutableCommentVersion(sql: string, index: number): number {
let cursor = index;
while (cursor < sql.length && /[0-9\s]/.test(sql[cursor] ?? "")) cursor += 1;
return cursor;
}
function dollarQuoteTagAt(sql: string, index: number): string | undefined {
const match = sql.slice(index).match(/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/);
return match?.[0];
}
function readQuotedEnd(sql: string, start: number, open: string, close: string): number {
let index = start + open.length;
while (index < sql.length) {
if (sql[index] === "\\" && (open === "'" || open === '"')) {
index += 2;
continue;
}
if (sql.startsWith(close, index)) {
if (sql.startsWith(close + close, index)) {
index += close.length * 2;
continue;
}
return index + close.length;
}
index += 1;
}
return sql.length;
}
function unquoteIdentifier(value: string, open: string, close: string): string {
if (!value.startsWith(open) || !value.endsWith(close)) return value;
return value.slice(open.length, value.length - close.length).replaceAll(close + close, close);
}