Skip to content

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

fix(pam): harden MySQL data explorer from second review pass

bernie-g17cecb0cbd6a
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.test.ts b/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
index 36eca54695..a6ed569152 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
@@ -13,13 +13,15 @@ import {
// These assertions exercise the Zod-introspection path (buildPamAccountTypeMetadata reads schema internals to derive field descriptors)
describe("buildPamAccountTypeMetadata", () => {
- const metadata = buildPamAccountTypeMetadata(new Set([PamAccountType.Postgres, PamAccountType.SSH]));
+ const metadata = buildPamAccountTypeMetadata(
+ new Set([PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.SSH])
+ );
const byType = new Map(metadata.map((m) => [m.type, m]));
test("flags web-access support from the provided supported-types set", () => {
expect(byType.get(PamAccountType.Postgres)?.supportsWebAccess).toBe(true);
expect(byType.get(PamAccountType.SSH)?.supportsWebAccess).toBe(true);
- expect(byType.get(PamAccountType.MySQL)?.supportsWebAccess).toBe(false);
+ expect(byType.get(PamAccountType.MySQL)?.supportsWebAccess).toBe(true);
expect(byType.get(PamAccountType.Kubernetes)?.supportsWebAccess).toBe(false);
});
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 90006c6603..3df161033e 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
@@ -2,28 +2,30 @@ import mysql from "mysql2/promise";
import { logger } from "@app/lib/logger";
+import { type ControllerParams } from "../pam-data-explorer-session-handler";
import {
DataExplorerClientMessageType,
DataExplorerServerMessageType,
type TConnectionController,
- type TDataExplorerServerMessage,
type TTabScopedMessage
} from "../pam-data-explorer-ws-types";
-import { getTableDetailQuery } from "./pam-mysql-data-explorer-metadata";
import { extractCommand, splitMysqlStatements } from "./pam-mysql-data-explorer-fns";
-
-type ControllerParams = {
- relayPort: number;
- username: string;
- database?: string;
- sessionId: string;
- connectionId: string;
- sendResponse: (msg: TDataExplorerServerMessage) => void;
- onUnexpectedTermination: (reason: string) => void;
-};
+import { getTableDetailQuery } from "./pam-mysql-data-explorer-metadata";
const MAX_ROWS = 1000;
+const IMPLICIT_COMMIT_COMMANDS = new Set([
+ "CREATE",
+ "ALTER",
+ "DROP",
+ "TRUNCATE",
+ "RENAME",
+ "GRANT",
+ "REVOKE",
+ "LOCK",
+ "UNLOCK"
+]);
+
export const createMysqlConnectionController = async (params: ControllerParams): Promise<TConnectionController> => {
const { relayPort, username, database, sessionId, connectionId, sendResponse, onUnexpectedTermination } = params;
@@ -53,7 +55,7 @@ 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]);
+ await conn.query(`SET SESSION max_execution_time = 30000, sql_select_limit = ${MAX_ROWS + 1}`);
let isInTransaction = false;
let disposing = false;
@@ -180,9 +182,9 @@ export const createMysqlConnectionController = async (params: ControllerParams):
const [rawRows, rawFields] = await conn.query<mysql.RowDataPacket[] | mysql.ResultSetHeader>(stmtSql);
const cmd = extractCommand(stmtSql);
- const upperCmd = cmd.toUpperCase();
- if (upperCmd === "BEGIN" || upperCmd === "START") isInTransaction = true;
- if (upperCmd === "COMMIT" || upperCmd === "ROLLBACK") isInTransaction = false;
+ if (cmd === "BEGIN" || cmd === "START") isInTransaction = true;
+ else if (cmd === "COMMIT" || cmd === "ROLLBACK") isInTransaction = false;
+ else if (IMPLICIT_COMMIT_COMMANDS.has(cmd)) isInTransaction = false;
if (Array.isArray(rawRows)) {
lastIsTruncated = rawRows.length > MAX_ROWS;
diff --git a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts
index 3c525b2d67..a0ac0046d1 100644
--- a/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts
+++ b/backend/src/ee/services/pam-web-access/mysql/pam-mysql-data-explorer-fns.test.ts
@@ -96,6 +96,32 @@ describe("splitMysqlStatements", () => {
"SELECT 2"
]);
});
+
+ test("doubled-quote escape in single-quoted string", () => {
+ expect(splitMysqlStatements("SELECT 'it''s here; still one'; SELECT 2")).toEqual([
+ "SELECT 'it''s here; still one'",
+ "SELECT 2"
+ ]);
+ });
+
+ test("doubled-quote escape in double-quoted string", () => {
+ expect(splitMysqlStatements('SELECT "a""b;c"; SELECT 2')).toEqual(['SELECT "a""b;c"', "SELECT 2"]);
+ });
+
+ test("doubled backtick in identifier", () => {
+ expect(splitMysqlStatements("SELECT `col``; name` FROM t; SELECT 2")).toEqual([
+ "SELECT `col``; name` FROM t",
+ "SELECT 2"
+ ]);
+ });
+
+ test("unterminated single-quoted string", () => {
+ expect(splitMysqlStatements("SELECT 'abc")).toEqual(["SELECT 'abc"]);
+ });
+
+ test("unterminated block comment", () => {
+ expect(splitMysqlStatements("SELECT 1 /* oops")).toEqual(["SELECT 1 /* oops"]);
+ });
});
describe("extractCommand", () => {
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 ef40dbb682..9c9c0caede 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
@@ -1,9 +1,19 @@
const skipQuoted = (sql: string, pos: number, quote: string): number => {
let i = pos + 1;
- while (i < sql.length && sql[i] !== quote) {
- i += sql[i] === "\\" ? 2 : 1;
+ while (i < sql.length) {
+ if (sql[i] === "\\") {
+ i += 2;
+ } else if (sql[i] === quote) {
+ if (i + 1 < sql.length && sql[i + 1] === quote) {
+ i += 2;
+ } else {
+ return i + 1;
+ }
+ } else {
+ i += 1;
+ }
}
- return i + 1;
+ return sql.length;
};
const skipLineComment = (sql: string, pos: number): number => {
@@ -21,7 +31,7 @@ const skipHashComment = (sql: string, pos: number): number => {
const skipBlockComment = (sql: string, pos: number): number => {
let i = pos + 2;
while (i + 1 < sql.length && !(sql[i] === "*" && sql[i + 1] === "/")) i += 1;
- return i + 2;
+ return Math.min(i + 2, sql.length);
};
const isLineComment = (sql: string, pos: number) => sql[pos] === "-" && sql[pos + 1] === "-";
@@ -81,7 +91,7 @@ export const extractCommand = (sql: string): string => {
} else if (isBlockComment(sql, pos)) {
pos += 2;
while (pos + 1 < len && !(sql[pos] === "*" && sql[pos + 1] === "/")) pos += 1;
- pos += 2;
+ pos = Math.min(pos + 2, len);
} else {
break;
}
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 f23412c5fd..e73b65074a 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
@@ -31,28 +31,35 @@ export const getTableDetailQuery = (schema: string, table: string) => ({
'columns', COALESCE((
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
- 'name', c.COLUMN_NAME,
- 'type', c.COLUMN_TYPE,
- 'nullable', IF(c.IS_NULLABLE = 'YES', TRUE, FALSE),
+ 'name', sub.COLUMN_NAME,
+ 'type', sub.COLUMN_TYPE,
+ 'nullable', CAST(IF(sub.IS_NULLABLE = 'YES', TRUE, FALSE) AS JSON),
'identityGeneration', CASE
- WHEN c.EXTRA LIKE '%auto_increment%' THEN 'AUTO_INCREMENT'
+ WHEN sub.EXTRA LIKE '%auto_increment%' THEN 'AUTO_INCREMENT'
ELSE NULL
END
)
- ORDER BY c.ORDINAL_POSITION
)
- FROM information_schema.COLUMNS c
- WHERE c.TABLE_SCHEMA = ? AND c.TABLE_NAME = ?
+ FROM (
+ SELECT c.COLUMN_NAME, c.COLUMN_TYPE, c.IS_NULLABLE, c.EXTRA
+ FROM information_schema.COLUMNS c
+ WHERE c.TABLE_SCHEMA = ? AND c.TABLE_NAME = ?
+ ORDER BY c.ORDINAL_POSITION
+ ) sub
), JSON_ARRAY()),
'primaryKeys', COALESCE((
- 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
- AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
- AND tc.TABLE_NAME = kcu.TABLE_NAME
- WHERE kcu.TABLE_SCHEMA = ? AND kcu.TABLE_NAME = ?
- AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
+ SELECT JSON_ARRAYAGG(sub.COLUMN_NAME)
+ FROM (
+ SELECT kcu.COLUMN_NAME
+ FROM information_schema.KEY_COLUMN_USAGE kcu
+ JOIN information_schema.TABLE_CONSTRAINTS tc
+ ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
+ AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
+ 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
+ ) sub
), JSON_ARRAY()),
'foreignKeys', COALESCE((
SELECT JSON_ARRAYAGG(
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 85dec82442..434a21c643 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
@@ -25,7 +25,7 @@ export type OneShotOptions = {
database?: string;
};
-type ControllerParams = {
+export type ControllerParams = {
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 c8c8642ab2..343bf030c3 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
@@ -4,25 +4,15 @@ import Cursor from "pg-cursor";
import { logger } from "@app/lib/logger";
+import { type ControllerParams } from "../pam-data-explorer-session-handler";
import {
DataExplorerClientMessageType,
DataExplorerServerMessageType,
type TConnectionController,
- type TDataExplorerServerMessage,
type TTabScopedMessage
} from "../pam-data-explorer-ws-types";
import { getTableDetailQuery } from "./pam-postgres-data-explorer-metadata";
-type ControllerParams = {
- relayPort: number;
- username: string;
- database?: string;
- sessionId: string;
- connectionId: string;
- sendResponse: (msg: TDataExplorerServerMessage) => void;
- onUnexpectedTermination: (reason: string) => void;
-};
-
const pgTypes = {
getTypeParser: (oid: number) => {
if (oid === 16)
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
index bc80c03ffc..4911531e82 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
@@ -512,6 +512,7 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {
cancelQuery={cancelQuery}
onSqlChange={(sql) => updateTabSql(tab.id, sql)}
onTransactionStateChange={(open) => setTabTransactionOpen(tab.id, open)}
+ dialect={dialect}
/>
);
}
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
index d952d2ea47..bcebe139f9 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
@@ -281,7 +281,7 @@ export const DataExplorerGrid = ({
setIsDataLoading(false);
}
},
- [tableDetail, schema, table, primaryKeys, executeQuery, connectionId]
+ [tableDetail, schema, table, primaryKeys, executeQuery, connectionId, dialect]
);
// Fetch data when filters/sorts/pagination change.
@@ -438,8 +438,8 @@ export const DataExplorerGrid = ({
primaryKeys,
schema,
table,
- connectionId,
- executeQuery,
+ dialect,
+ executeStatements,
fetchData,
offset,
pageSize,
@@ -543,8 +543,8 @@ export const DataExplorerGrid = ({
primaryKeys,
schema,
table,
- connectionId,
- executeQuery,
+ dialect,
+ executeStatements,
fetchData,
offset,
pageSize,
@@ -685,8 +685,8 @@ export const DataExplorerGrid = ({
schema,
table,
primaryKeys,
- connectionId,
- executeQuery,
+ dialect,
+ executeStatements,
fetchData,
offset,
pageSize,
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx
index 9f5b74cbb3..0eaea57f33 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx
@@ -30,7 +30,10 @@ function getFilterPlaceholder(columnType: string, operator: FilterOperator): str
break;
}
- const t = columnType.toLowerCase().replace("[]", "");
+ const t = columnType
+ .toLowerCase()
+ .replace("[]", "")
+ .replace(/\(\d+\)/g, "");
switch (t) {
case "int2":
case "int4":
@@ -41,6 +44,9 @@ function getFilterPlaceholder(columnType: string, operator: FilterOperator): str
case "integer":
case "bigint":
case "smallint":
+ case "tinyint":
+ case "mediumint":
+ case "int":
return "42";
case "float4":
case "float8":
@@ -49,6 +55,8 @@ function getFilterPlaceholder(columnType: string, operator: FilterOperator): str
case "real":
case "double precision":
case "money":
+ case "float":
+ case "double":
return "3.14";
case "bool":
case "boolean":
@@ -59,6 +67,7 @@ function getFilterPlaceholder(columnType: string, operator: FilterOperator): str
return "2024-01-15";
case "timestamp":
case "timestamptz":
+ case "datetime":
return "2024-01-15 09:30:00";
case "time":
case "timetz":
@@ -75,6 +84,10 @@ function getFilterPlaceholder(columnType: string, operator: FilterOperator): str
case "bpchar":
case "name":
case "citext":
+ case "tinytext":
+ case "mediumtext":
+ case "longtext":
+ case "enum":
return "some text";
default:
return "Value";
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx
index 1436612e2c..99b9b96b22 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx
@@ -32,6 +32,7 @@ type Props = {
cancelQuery: (connectionId: string) => void;
onSqlChange: (sql: string) => void;
onTransactionStateChange: (open: boolean) => void;
+ dialect?: "postgres" | "mysql";
};
export function QueryPanel({
@@ -39,7 +40,8 @@ export function QueryPanel({
executeQuery,
cancelQuery,
onSqlChange,
- onTransactionStateChange
+ onTransactionStateChange,
+ dialect = "postgres"
}: Props) {
const [isRunning, setIsRunning] = useState(false);
const [result, setResult] = useState<QueryResult | null>(null);
@@ -142,6 +144,7 @@ export function QueryPanel({
onSqlToRunChange={(s) => {
sqlToRunRef.current = s;
}}
+ sqlDialect={dialect}
/>
</div>
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx
index 87b36729cd..e5044f2a39 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef } from "react";
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
-import { PostgreSQL, sql } from "@codemirror/lang-sql";
+import { MySQL, PostgreSQL, sql } from "@codemirror/lang-sql";
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
import { EditorState, type Transaction } from "@codemirror/state";
import { EditorView, keymap, placeholder, type ViewUpdate } from "@codemirror/view";
@@ -69,6 +69,7 @@ type Props = {
onExecute: (sql: string) => void;
onSelectionChange: (hasSelection: boolean) => void;
onSqlToRunChange: (sql: string) => void;
+ sqlDialect?: "postgres" | "mysql";
};
export function SqlEditor({
@@ -76,7 +77,8 @@ export function SqlEditor({
onChange,
onExecute,
onSelectionChange,
- onSqlToRunChange
+ onSqlToRunChange,
+ sqlDialect = "postgres"
}: Props) {
const containerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
@@ -114,7 +116,7 @@ export function SqlEditor({
]),
maxSqlLength,
placeholder("Start writing SQL..."),
- sql({ dialect: PostgreSQL }),
+ sql({ dialect: sqlDialect === "mysql" ? MySQL : PostgreSQL }),
infisicalTheme,
syntaxHighlighting(infisicalHighlight),
EditorView.updateListener.of((update: ViewUpdate) => {
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts
index 0c423f56a5..d0e4e36aa5 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts
+++ b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts
@@ -1,7 +1,7 @@
-// WebSocket message types for the Postgres Data Explorer
+// WebSocket message types for the Data Explorer
export type DataExplorerClientMessage =
- // Metadata (no connectionId) — served by short-lived BE pg.Clients
+ // Metadata (no connectionId) -- served by short-lived BE database connections
| { type: "get-schemas"; id: string }
| { type: "get-tables"; id: string; schema: string }
// Tab-scoped — routed to a specific BE controller
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
index f48679e4bb..307d25f05c 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
+++ b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
@@ -19,7 +19,9 @@ export function quoteLiteral(value: unknown, dialect: SqlDialect = "postgres"):
if (dialect === "postgres" && str.includes("'") && !str.includes("$")) {
return `$$${str}$$`;
}
- return `'${str.replace(/'/g, "''")}'`;
+ const escaped =
+ dialect === "mysql" ? str.replace(/\\/g, "\\\\").replace(/'/g, "''") : str.replace(/'/g, "''");
+ return `'${escaped}'`;
}
export type FilterCondition = {
@@ -90,7 +92,16 @@ export function buildSelectQuery(params: {
primaryKeys?: string[];
dialect?: SqlDialect;
}): string {
- const { schema, table, filters, sorts, limit, offset, primaryKeys, dialect = "postgres" } = params;
+ const {
+ schema,
+ table,
+ filters,
+ sorts,
+ limit,
+ offset,
+ primaryKeys,
+ dialect = "postgres"
+ } = params;
const tableName = `${quoteIdent(schema, dialect)}.${quoteIdent(table, dialect)}`;
const where = buildWhereClause(filters, dialect);
@@ -179,8 +190,7 @@ export function buildDeleteQuery(params: {
return `DELETE FROM ${tableName} WHERE ${whereClauses}`;
}
-// Note: RETURNING * in individual INSERT/UPDATE statements is harmless but unused when
-// wrapped here -- pgClient.query() returns only the last statement's result (COMMIT).
+// RETURNING * in individual INSERT/UPDATE is harmless but unused when wrapped here.
// The frontend re-fetches data after save anyway.
export function wrapInTransaction(statements: string[]): string {
return `BEGIN;\n${statements.join(";\n")};\nCOMMIT;`;