Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(pam): harden MySQL data explorer from review findings

bernie-gb2e5dd4eb787
diff --git a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.ts b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.ts
index 1dfc9469de..90006c6603 100644
--- a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.ts
+++ b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.ts
@@ -53,6 +53,8 @@ export const createMysqlConnectionController = async (params: ControllerParams):
const [pidRows] = await conn.execute<mysql.RowDataPacket[]>("SELECT CONNECTION_ID() AS pid");
const backendPid = (pidRows[0]?.pid as number) ?? null;
+ await conn.execute("SET SESSION max_execution_time = 30000, sql_select_limit = ?", [MAX_ROWS + 1]);
+
let isInTransaction = false;
let disposing = false;
@@ -89,6 +91,7 @@ export const createMysqlConnectionController = async (params: ControllerParams):
password: "",
connectTimeout: 5_000
});
+ cancelConn.on("error" as never, () => {});
await cancelConn.execute("KILL QUERY ?", [backendPid]);
} catch (err) {
logger.debug(err, `Failed to cancel MySQL query [sessionId=${sessionId}] [connectionId=${connectionId}]`);
@@ -239,6 +242,12 @@ export const createMysqlConnectionController = async (params: ControllerParams):
onUnexpectedTermination(err.message || "Database connection error");
});
+ conn.on("end" as never, () => {
+ if (disposing) return;
+ disposing = true;
+ onUnexpectedTermination("Database connection ended");
+ });
+
const dispose = () => {
if (disposing) return;
disposing = true;
diff --git a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.test.ts b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts
similarity index 66%
rename from backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.test.ts
rename to backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts
index a2092eb45c..3c525b2d67 100644
--- a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.test.ts
+++ b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
-import { splitMysqlStatements } from "./pam-mysql-data-explorer-fns";
+import { extractCommand, splitMysqlStatements } from "./pam-mysql-data-explorer-fns";
describe("splitMysqlStatements", () => {
test("single statement without semicolon", () => {
@@ -53,6 +53,13 @@ describe("splitMysqlStatements", () => {
]);
});
+ test("semicolon inside hash comment", () => {
+ expect(splitMysqlStatements("SELECT 1 # ; not a split\n; SELECT 2")).toEqual([
+ "SELECT 1 # ; not a split",
+ "SELECT 2"
+ ]);
+ });
+
test("semicolon inside block comment", () => {
expect(splitMysqlStatements("SELECT 1 /* ; still one */ ; SELECT 2")).toEqual([
"SELECT 1 /* ; still one */",
@@ -90,3 +97,41 @@ describe("splitMysqlStatements", () => {
]);
});
});
+
+describe("extractCommand", () => {
+ test("simple SELECT", () => {
+ expect(extractCommand("SELECT 1")).toBe("SELECT");
+ });
+
+ test("leading whitespace", () => {
+ expect(extractCommand(" \n INSERT INTO t VALUES (1)")).toBe("INSERT");
+ });
+
+ test("leading line comment", () => {
+ expect(extractCommand("-- comment\nBEGIN")).toBe("BEGIN");
+ });
+
+ test("leading hash comment", () => {
+ expect(extractCommand("# comment\nCOMMIT")).toBe("COMMIT");
+ });
+
+ test("leading block comment", () => {
+ expect(extractCommand("/* note */ ROLLBACK")).toBe("ROLLBACK");
+ });
+
+ test("multiple leading comments", () => {
+ expect(extractCommand("-- first\n/* second */ # third\nDELETE FROM t")).toBe("DELETE");
+ });
+
+ test("START TRANSACTION", () => {
+ expect(extractCommand("START TRANSACTION")).toBe("START");
+ });
+
+ test("empty input", () => {
+ expect(extractCommand("")).toBe("");
+ });
+
+ test("only comments", () => {
+ expect(extractCommand("-- just a comment\n")).toBe("");
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.ts b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.ts
index 4f11d04f8a..ef40dbb682 100644
--- a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.ts
+++ b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.ts
@@ -12,6 +12,12 @@ const skipLineComment = (sql: string, pos: number): number => {
return i;
};
+const skipHashComment = (sql: string, pos: number): number => {
+ let i = pos + 1;
+ while (i < sql.length && sql[i] !== "\n") i += 1;
+ return i;
+};
+
const skipBlockComment = (sql: string, pos: number): number => {
let i = pos + 2;
while (i + 1 < sql.length && !(sql[i] === "*" && sql[i + 1] === "/")) i += 1;
@@ -35,6 +41,8 @@ export const splitMysqlStatements = (sql: string): string[] => {
pos = skipQuoted(sql, pos, ch);
} else if (isLineComment(sql, pos)) {
pos = skipLineComment(sql, pos);
+ } else if (ch === "#") {
+ pos = skipHashComment(sql, pos);
} else if (isBlockComment(sql, pos)) {
pos = skipBlockComment(sql, pos);
} else if (ch === ";") {
@@ -54,10 +62,34 @@ export const splitMysqlStatements = (sql: string): string[] => {
};
export const extractCommand = (sql: string): string => {
- const trimmed = sql.trimStart();
- let i = 0;
- while (i < trimmed.length && trimmed[i] !== " " && trimmed[i] !== "\t" && trimmed[i] !== "\n" && trimmed[i] !== "\r") {
- i += 1;
+ let pos = 0;
+ const len = sql.length;
+
+ // Skip leading whitespace and comments
+ while (pos < len) {
+ // Skip whitespace
+ if (sql[pos] === " " || sql[pos] === "\t" || sql[pos] === "\n" || sql[pos] === "\r") {
+ pos += 1;
+ } else if (isLineComment(sql, pos)) {
+ pos += 2;
+ while (pos < len && sql[pos] !== "\n") pos += 1;
+ if (pos < len) pos += 1;
+ } else if (sql[pos] === "#") {
+ pos += 1;
+ while (pos < len && sql[pos] !== "\n") pos += 1;
+ if (pos < len) pos += 1;
+ } else if (isBlockComment(sql, pos)) {
+ pos += 2;
+ while (pos + 1 < len && !(sql[pos] === "*" && sql[pos + 1] === "/")) pos += 1;
+ pos += 2;
+ } else {
+ break;
+ }
+ }
+
+ const start = pos;
+ while (pos < len && sql[pos] !== " " && sql[pos] !== "\t" && sql[pos] !== "\n" && sql[pos] !== "\r") {
+ pos += 1;
}
- return trimmed.slice(0, i).toUpperCase();
+ return sql.slice(start, pos).toUpperCase();
};
diff --git a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-metadata.ts b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-metadata.ts
index 01a3714863..f23412c5fd 100644
--- a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-metadata.ts
+++ b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-metadata.ts
@@ -39,13 +39,13 @@ export const getTableDetailQuery = (schema: string, table: string) => ({
ELSE NULL
END
)
+ ORDER BY c.ORDINAL_POSITION
)
FROM information_schema.COLUMNS c
WHERE c.TABLE_SCHEMA = ? AND c.TABLE_NAME = ?
- ORDER BY c.ORDINAL_POSITION
), JSON_ARRAY()),
'primaryKeys', COALESCE((
- SELECT JSON_ARRAYAGG(kcu.COLUMN_NAME)
+ SELECT JSON_ARRAYAGG(kcu.COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION)
FROM information_schema.KEY_COLUMN_USAGE kcu
JOIN information_schema.TABLE_CONSTRAINTS tc
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
@@ -53,7 +53,6 @@ export const getTableDetailQuery = (schema: string, table: string) => ({
AND tc.TABLE_NAME = kcu.TABLE_NAME
WHERE kcu.TABLE_SCHEMA = ? AND kcu.TABLE_NAME = ?
AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
- ORDER BY kcu.ORDINAL_POSITION
), JSON_ARRAY()),
'foreignKeys', COALESCE((
SELECT JSON_ARRAYAGG(
diff --git a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-metadata.ts b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-metadata.ts
index b7ca86fcea..500dfcb6a2 100644
--- a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-metadata.ts
+++ b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-metadata.ts
@@ -2,14 +2,9 @@ import mysql from "mysql2/promise";
import { logger } from "@app/lib/logger";
+import { type OneShotOptions } from "../pam-data-explorer-session-handler";
import { getSchemasQuery, getTablesQuery } from "./pam-mysql-data-explorer-metadata";
-type OneShotOptions = {
- relayPort: number;
- username: string;
- database?: string;
-};
-
const buildConnection = async ({ relayPort, username, database }: OneShotOptions): Promise<mysql.Connection> => {
const conn = await mysql.createConnection({
host: "localhost",
diff --git a/backend/src/ee/services/pam-web-access/pam-data-explorer-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-data-explorer-session-handler.ts
index bc068f1d4b..85dec82442 100644
--- a/backend/src/ee/services/pam-web-access/pam-data-explorer-session-handler.ts
+++ b/backend/src/ee/services/pam-web-access/pam-data-explorer-session-handler.ts
@@ -19,7 +19,7 @@ import {
const MAX_CONNECTIONS_PER_WS = 20;
-type OneShotOptions = {
+export type OneShotOptions = {
relayPort: number;
username: string;
database?: string;
diff --git a/backend/src/ee/services/pam-web-access/postgres/pam-postgres-connection-controller.ts b/backend/src/ee/services/pam-web-access/postgres/pam-postgres-connection-controller.ts
index e70cec9d4a..c8c8642ab2 100644
--- a/backend/src/ee/services/pam-web-access/postgres/pam-postgres-connection-controller.ts
+++ b/backend/src/ee/services/pam-web-access/postgres/pam-postgres-connection-controller.ts
@@ -16,7 +16,7 @@ import { getTableDetailQuery } from "./pam-postgres-data-explorer-metadata";
type ControllerParams = {
relayPort: number;
username: string;
- database: string;
+ database?: string;
sessionId: string;
connectionId: string;
sendResponse: (msg: TDataExplorerServerMessage) => void;
diff --git a/backend/src/ee/services/pam-web-access/postgres/pam-postgres-metadata.ts b/backend/src/ee/services/pam-web-access/postgres/pam-postgres-metadata.ts
index fd5e603250..0ecb07bb00 100644
--- a/backend/src/ee/services/pam-web-access/postgres/pam-postgres-metadata.ts
+++ b/backend/src/ee/services/pam-web-access/postgres/pam-postgres-metadata.ts
@@ -2,14 +2,9 @@ import pg from "pg";
import { logger } from "@app/lib/logger";
+import { type OneShotOptions } from "../pam-data-explorer-session-handler";
import { getSchemasQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";
-type OneShotOptions = {
- relayPort: number;
- username: string;
- database: string;
-};
-
const buildClient = ({ relayPort, username, database }: OneShotOptions): pg.Client => {
const client = new pg.Client({
host: "localhost",
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
index 6bdce92f16..d952d2ea47 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
@@ -188,16 +188,9 @@ export const DataExplorerGrid = ({
}: DataExplorerGridProps) => {
const executeStatements = useCallback(
async (statements: string[]) => {
- if (dialect === "mysql") {
- await statements.reduce(
- (chain, stmt) => chain.then(() => executeQuery(connectionId, stmt)),
- Promise.resolve() as Promise<unknown>
- );
- } else {
- await executeQuery(connectionId, wrapInTransaction(statements));
- }
+ await executeQuery(connectionId, wrapInTransaction(statements));
},
- [dialect, executeQuery, connectionId]
+ [executeQuery, connectionId]
);
const [originalData, setOriginalData] = useState<Record<string, unknown>[]>([]);