feat(grid): support binary cell downloads
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
binaryCellDownloadFileName,
|
||||
binaryCellDownloadPayload,
|
||||
canDownloadBinaryCellValue,
|
||||
isBinaryCellColumnType,
|
||||
parseBinaryCellHexValue,
|
||||
} from "../../apps/desktop/src/lib/binaryCellDownload.ts";
|
||||
|
||||
test("parseBinaryCellHexValue accepts 0x and \\x prefixed hex values", () => {
|
||||
assert.deepEqual(Array.from(parseBinaryCellHexValue("0X48656c6c6f") ?? []), [72, 101, 108, 108, 111]);
|
||||
assert.deepEqual(Array.from(parseBinaryCellHexValue("\\x00 ff") ?? []), [0, 255]);
|
||||
});
|
||||
|
||||
test("parseBinaryCellHexValue rejects non-hex and odd-length payloads", () => {
|
||||
assert.equal(parseBinaryCellHexValue("hello"), null);
|
||||
assert.equal(parseBinaryCellHexValue("0x123"), null);
|
||||
assert.equal(parseBinaryCellHexValue(null), null);
|
||||
});
|
||||
|
||||
test("binary cell download detects common blob column types", () => {
|
||||
assert.equal(isBinaryCellColumnType("BLOB"), true);
|
||||
assert.equal(isBinaryCellColumnType("RAW(2000)"), true);
|
||||
assert.equal(isBinaryCellColumnType("long raw"), true);
|
||||
assert.equal(isBinaryCellColumnType("varchar"), false);
|
||||
});
|
||||
|
||||
test("canDownloadBinaryCellValue allows displayed binary hex strings", () => {
|
||||
assert.equal(canDownloadBinaryCellValue("0x89504e47", "BLOB"), true);
|
||||
assert.equal(canDownloadBinaryCellValue("0x89504e47"), true);
|
||||
assert.equal(canDownloadBinaryCellValue("89504e47", "BLOB"), false);
|
||||
});
|
||||
|
||||
test("binaryCellDownloadPayload builds raw and decoded payloads", () => {
|
||||
const binary = binaryCellDownloadPayload("0x4869", "binary");
|
||||
assert.equal(binary.mimeType, "application/octet-stream");
|
||||
assert.equal(binary.extension, "bin");
|
||||
assert.deepEqual(Array.from(binary.data as Uint8Array), [72, 105]);
|
||||
|
||||
const text = binaryCellDownloadPayload("0x4869", "utf8");
|
||||
assert.equal(text.mimeType, "text/plain;charset=utf-8");
|
||||
assert.equal(text.extension, "txt");
|
||||
assert.equal(text.data, "Hi");
|
||||
});
|
||||
|
||||
test("binaryCellDownloadPayload decodes GBK text bytes", () => {
|
||||
const payload = binaryCellDownloadPayload("0xd6d0cec4", "gbk");
|
||||
assert.equal(payload.data, "中文");
|
||||
});
|
||||
|
||||
test("binaryCellDownloadFileName sanitizes column names", () => {
|
||||
assert.equal(
|
||||
binaryCellDownloadFileName({ column: "avatar/blob", rowNumber: 7, mode: "gbk", extension: "txt" }),
|
||||
"avatar-blob-row-7-gbk.txt",
|
||||
);
|
||||
});
|
||||
@@ -92,7 +92,7 @@ See the [DBX CLI README](../cli/README.md) for command details.
|
||||
|
||||
## SQL Safety
|
||||
|
||||
`dbx_execute_query` is read-only by default. To allow write statements such as `INSERT` or `UPDATE`, set:
|
||||
`dbx_execute_query` accepts multiple SQL statements and executes them one at a time after checking each statement. It is read-only by default. To allow write statements such as `INSERT` or `UPDATE`, set:
|
||||
|
||||
```bash
|
||||
DBX_MCP_ALLOW_WRITES=1
|
||||
@@ -213,7 +213,7 @@ dbx query local "select 1" --json
|
||||
|
||||
### SQL 安全
|
||||
|
||||
`dbx_execute_query` 默认只读。若要允许 `INSERT`、`UPDATE` 等写操作,设置:
|
||||
`dbx_execute_query` 支持多条 SQL 语句,会逐条完成安全检查并依次执行。默认只读。若要允许 `INSERT`、`UPDATE` 等写操作,设置:
|
||||
|
||||
```bash
|
||||
DBX_MCP_ALLOW_WRITES=1
|
||||
|
||||
@@ -16,8 +16,10 @@ import {
|
||||
parseMongoAggregateCommand,
|
||||
postBridge,
|
||||
sqlSafetyFromEnv,
|
||||
splitSqlStatements,
|
||||
type Backend,
|
||||
type ConnectionConfig,
|
||||
type QueryResult,
|
||||
} from "@dbx-app/node-core";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
@@ -36,6 +38,13 @@ function withDatabase(config: ConnectionConfig, database?: string): ConnectionCo
|
||||
return database === undefined ? config : { ...config, database };
|
||||
}
|
||||
|
||||
function formatQueryToolResult(result: QueryResult, title?: string) {
|
||||
const prefix = title ? `${title}\n` : "";
|
||||
if (result.columns.length === 0) return text(`${prefix}Query executed. ${result.row_count} row(s) affected.`);
|
||||
const rows = result.rows.map((r) => result.columns.map((c) => formatCell(r[c])));
|
||||
return text(`${prefix}${mdTable(result.columns, rows)}\n\n${result.row_count} row(s)`);
|
||||
}
|
||||
|
||||
export const DBX_CONNECTION_TYPE_DESCRIPTION =
|
||||
"Database type: postgres, mysql, sqlite, redis, duckdb, clickhouse, sqlserver, mongodb, oracle, elasticsearch, doris, starrocks, redshift, dameng, kingbase, highgo, vastbase, goldendb, gaussdb, yashandb, databricks, saphana, teradata, vertica, firebird, exasol, opengauss, oceanbase-oracle, gbase, h2, snowflake, trino, hive, db2, informix, neo4j, cassandra, bigquery, kylin, sundb, tdengine, xugu, jdbc, access";
|
||||
|
||||
@@ -108,16 +117,19 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
||||
const config = await backend.findConnection(connection_name);
|
||||
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
||||
if (config.db_type !== "mongodb") {
|
||||
const safety = evaluateSqlSafety(sql, sqlSafetyFromEnv());
|
||||
const safety = evaluateSqlSafety(sql, { ...sqlSafetyFromEnv(), allowMultipleStatements: true });
|
||||
if (!safety.allowed) return toolError("SQL_BLOCKED", safety.reason ?? "SQL blocked.");
|
||||
}
|
||||
// MongoDB shell commands don't fit the SQL safety evaluator; the backend
|
||||
// (node-core executeQuery) applies command-aware read/write gating.
|
||||
try {
|
||||
const result = await backend.executeQuery(withDatabase(config, database), sql);
|
||||
if (result.columns.length === 0) return text(`Query executed. ${result.row_count} row(s) affected.`);
|
||||
const rows = result.rows.map((r) => result.columns.map((c) => formatCell(r[c])));
|
||||
return text(`${mdTable(result.columns, rows)}\n\n${result.row_count} row(s)`);
|
||||
const statements = config.db_type === "mongodb" ? [sql] : splitSqlStatements(sql);
|
||||
const results = [];
|
||||
for (const statement of statements) {
|
||||
results.push(await backend.executeQuery(withDatabase(config, database), statement));
|
||||
}
|
||||
if (results.length === 1) return formatQueryToolResult(results[0]);
|
||||
return text(results.map((result, index) => formatQueryToolResult(result, `Statement ${index + 1}`).content[0].text).join("\n\n"));
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
return toolError("QUERY_ERROR", msg);
|
||||
@@ -235,7 +247,7 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
||||
if (!safety.allowed) return toolError("SQL_BLOCKED", safety.reason ?? "Query blocked.");
|
||||
}
|
||||
} else {
|
||||
const safety = evaluateSqlSafety(sql, safetyOptions);
|
||||
const safety = evaluateSqlSafety(sql, { ...safetyOptions, allowMultipleStatements: true });
|
||||
if (!safety.allowed) return toolError("SQL_BLOCKED", safety.reason ?? "SQL blocked.");
|
||||
}
|
||||
// MongoDB shell commands bypass the SQL safety evaluator; pass MCP
|
||||
|
||||
@@ -74,6 +74,48 @@ test("execute query scopes the connection to the requested database", async () =
|
||||
assert.equal(usedDatabase, "stores_demo");
|
||||
});
|
||||
|
||||
test("execute query runs safe multi-statement SQL one statement at a time", async () => {
|
||||
const executed: string[] = [];
|
||||
const scopedBackend: Backend = {
|
||||
...backend,
|
||||
executeQuery: async (_config, sql) => {
|
||||
executed.push(sql);
|
||||
return { columns: ["value"], rows: [{ value: executed.length }], row_count: 1 };
|
||||
},
|
||||
};
|
||||
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||
|
||||
const result = await (server as any)._registeredTools.dbx_execute_query.handler({
|
||||
connection_name: "local",
|
||||
sql: "select 1; select 2;",
|
||||
});
|
||||
|
||||
assert.deepEqual(executed, ["select 1", "select 2"]);
|
||||
assert.match(result.content[0].text, /Statement 1/);
|
||||
assert.match(result.content[0].text, /Statement 2/);
|
||||
});
|
||||
|
||||
test("execute query reports the blocked statement number for unsafe multi-statement SQL", async () => {
|
||||
const oldAllowWrites = process.env.DBX_MCP_ALLOW_WRITES;
|
||||
process.env.DBX_MCP_ALLOW_WRITES = "1";
|
||||
const server = createDbxMcpServer(backend, { isWebMode: true });
|
||||
|
||||
try {
|
||||
const result = await (server as any)._registeredTools.dbx_execute_query.handler({
|
||||
connection_name: "local",
|
||||
sql: "select 1; delete from users;",
|
||||
});
|
||||
|
||||
assert.equal(result.isError, true);
|
||||
assert.match(result.content[0].text, /SQL_BLOCKED:/);
|
||||
assert.match(result.content[0].text, /Statement 2/);
|
||||
assert.match(result.content[0].text, /WHERE/);
|
||||
} finally {
|
||||
if (oldAllowWrites === undefined) delete process.env.DBX_MCP_ALLOW_WRITES;
|
||||
else process.env.DBX_MCP_ALLOW_WRITES = oldAllowWrites;
|
||||
}
|
||||
});
|
||||
|
||||
test("mongodb list tables returns collections from the selected database", async () => {
|
||||
let usedDatabase = "";
|
||||
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb", database: "admin" };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export interface SqlSafetyOptions {
|
||||
allowWrites?: boolean;
|
||||
allowDangerous?: boolean;
|
||||
allowMultipleStatements?: boolean;
|
||||
}
|
||||
|
||||
export interface SqlSafetyDecision {
|
||||
@@ -14,9 +15,26 @@ const DANGEROUS_KEYWORDS = new Set(["drop", "truncate", "alter"]);
|
||||
export function evaluateSqlSafety(sql: string, options: SqlSafetyOptions = {}): SqlSafetyDecision {
|
||||
const statements = splitSqlStatements(sql);
|
||||
if (statements.length === 0) return { allowed: false, reason: "SQL is empty." };
|
||||
if (statements.length > 1) return { allowed: false, reason: "Only one SQL statement is allowed per MCP query." };
|
||||
if (statements.length > 1 && !options.allowMultipleStatements) {
|
||||
return { allowed: false, reason: "Only one SQL statement is allowed per query." };
|
||||
}
|
||||
|
||||
const normalized = stripSqlCommentsAndStrings(statements[0]).trim();
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const decision = evaluateSingleSqlStatementSafety(statements[i], options);
|
||||
if (!decision.allowed && statements.length > 1) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Statement ${i + 1}: ${decision.reason ?? "SQL blocked."}`,
|
||||
};
|
||||
}
|
||||
if (!decision.allowed) return decision;
|
||||
}
|
||||
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
function evaluateSingleSqlStatementSafety(sql: string, options: SqlSafetyOptions = {}): SqlSafetyDecision {
|
||||
const normalized = stripSqlCommentsAndStrings(sql).trim();
|
||||
const firstKeyword = normalized.match(/^[a-zA-Z_]+/)?.[0]?.toLowerCase();
|
||||
if (!firstKeyword) return { allowed: false, reason: "SQL statement is not recognized." };
|
||||
|
||||
@@ -52,7 +70,7 @@ export function sqlSafetyFromEnv(env: NodeJS.ProcessEnv = process.env): SqlSafet
|
||||
};
|
||||
}
|
||||
|
||||
function splitSqlStatements(sql: string): string[] {
|
||||
export function splitSqlStatements(sql: string): string[] {
|
||||
const statements: string[] = [];
|
||||
let current = "";
|
||||
let quote: "'" | '"' | "`" | null = null;
|
||||
|
||||
@@ -29,3 +29,26 @@ test("blocks update without where when writes are enabled", () => {
|
||||
assert.match(decision.reason ?? "", /WHERE/i);
|
||||
});
|
||||
|
||||
test("blocks multiple SQL statements unless explicitly allowed", () => {
|
||||
const decision = evaluateSqlSafety("select 1; select 2");
|
||||
|
||||
assert.equal(decision.allowed, false);
|
||||
assert.match(decision.reason ?? "", /Only one SQL statement/);
|
||||
});
|
||||
|
||||
test("allows multiple read-only SQL statements when enabled", () => {
|
||||
const decision = evaluateSqlSafety("select 1; show tables", { allowMultipleStatements: true });
|
||||
|
||||
assert.equal(decision.allowed, true);
|
||||
});
|
||||
|
||||
test("checks every statement in a multi-statement SQL string", () => {
|
||||
const decision = evaluateSqlSafety("select 1; delete from users", {
|
||||
allowMultipleStatements: true,
|
||||
allowWrites: true,
|
||||
});
|
||||
|
||||
assert.equal(decision.allowed, false);
|
||||
assert.match(decision.reason ?? "", /Statement 2/i);
|
||||
assert.match(decision.reason ?? "", /WHERE/i);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user