-
Notifications
You must be signed in to change notification settings - Fork 2k
feat(pam): add MySQL web access data explorer #7022
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bernie-g
merged 17 commits into
pam-revamp
from
bernie/pam-291-add-support-for-mysql-web-access
Jun 26, 2026
Merged
Changes from 11 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
f9dd351
feat(pam): add MySQL web access data explorer
bernie-g b2e5dd4
fix(pam): harden MySQL data explorer from review findings
bernie-g 17cecb0
fix(pam): harden MySQL data explorer from second review pass
bernie-g 4892e40
fix(pam): MySQL line comment requires trailing space, disable backsla…
bernie-g 7da56d6
fix(pam): add application-level DML/DDL timeout for MySQL queries
bernie-g d492a75
Merge remote-tracking branch 'origin/pam-revamp' into bernie/pam-291-…
bernie-g 5c26085
fix(pam): remove UNLOCK from implicit commit set, add explicit multip…
bernie-g 0d03b56
chore(pam): lint fixes
bernie-g 5de4cd6
fix(pam): use DO 0 server status for MySQL transaction detection
bernie-g d5ac73d
fix(pam): re-apply sql_select_limit before each MySQL statement
bernie-g c7d0f36
fix(pam): preserve MySQL BIGINT and date values as strings
bernie-g ac0a5bc
fix(pam): rename backendPid to nativeConnectionId, add mysql metadata…
bernie-g e24b91d
fix(pam): use SqlDialect type and make dialect required across data e…
bernie-g a428653
fix(pam): add dialect TODO to FilterPopover, unexport quoteIdent/quot…
bernie-g f1c8cfa
fix(pam): prettier formatting for connection-opened type
bernie-g a9e0ea2
merge: resolve pam-revamp conflicts in FilterPopover
bernie-g 24db70e
fix: restore linted SecretSharing route file overwritten by TanStack …
bernie-g File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
283 changes: 283 additions & 0 deletions
283
backend/src/ee/services/pam-web-access/mysql/pam-mysql-connection-controller.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,283 @@ | ||
| 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 TTabScopedMessage | ||
| } from "../pam-data-explorer-ws-types"; | ||
| import { extractCommand, splitMysqlStatements } from "./pam-mysql-data-explorer-fns"; | ||
| import { getTableDetailQuery } from "./pam-mysql-data-explorer-metadata"; | ||
|
|
||
| const MAX_ROWS = 1000; | ||
|
|
||
| export const createMysqlConnectionController = async (params: ControllerParams): Promise<TConnectionController> => { | ||
| const { relayPort, username, database, sessionId, connectionId, sendResponse, onUnexpectedTermination } = params; | ||
|
|
||
| const conn = await mysql.createConnection({ | ||
| host: "localhost", | ||
| port: relayPort, | ||
| user: username, | ||
| database: database || undefined, | ||
| password: "", | ||
| connectTimeout: 30_000, | ||
|
bernie-g marked this conversation as resolved.
|
||
| multipleStatements: false, | ||
| supportBigNumbers: true, | ||
| bigNumberStrings: true, | ||
| dateStrings: true, | ||
| typeCast: (field, next) => { | ||
| if (field.type === "JSON") { | ||
| return field.string(); | ||
| } | ||
| if (field.type === "BIT" && field.length === 1) { | ||
| const buf = field.buffer(); | ||
| if (!buf) return null; | ||
| return buf[0] === 1 ? "true" : "false"; | ||
| } | ||
| if (field.type === "TINY" && field.length === 1) { | ||
| return field.string(); | ||
| } | ||
| return next(); | ||
| } | ||
| }); | ||
|
|
||
| const [pidRows] = await conn.execute<mysql.RowDataPacket[]>("SELECT CONNECTION_ID() AS pid"); | ||
| const backendPid = (pidRows[0]?.pid as number) ?? null; | ||
|
|
||
| await conn.query(`SET SESSION max_execution_time = 30000, sql_select_limit = ${MAX_ROWS + 1}`); | ||
|
bernie-g marked this conversation as resolved.
|
||
|
|
||
| let isInTransaction = false; | ||
| let disposing = false; | ||
|
|
||
| const queryTransactionState = async () => { | ||
| try { | ||
| const [result] = await conn.query<mysql.ResultSetHeader>("DO 0"); | ||
| // eslint-disable-next-line no-bitwise | ||
| isInTransaction = (result.serverStatus & 1) === 1; | ||
| } catch { | ||
| isInTransaction = false; | ||
| } | ||
| }; | ||
|
|
||
| const sendQueryError = async (id: string, err: unknown) => { | ||
| const mysqlErr = err as { message?: string; sqlMessage?: string; code?: string }; | ||
|
|
||
| try { | ||
| await conn.execute("ROLLBACK"); | ||
| } catch { | ||
| // ROLLBACK fails if there was no active transaction | ||
| } | ||
|
|
||
| await queryTransactionState(); | ||
|
|
||
| sendResponse({ | ||
| type: DataExplorerServerMessageType.Error, | ||
| id, | ||
| connectionId, | ||
| transactionOpen: isInTransaction, | ||
| error: mysqlErr.sqlMessage ?? mysqlErr.message ?? "Query execution failed", | ||
| detail: mysqlErr.code | ||
| }); | ||
| }; | ||
|
|
||
| const cancelRunningQuery = async () => { | ||
| if (!backendPid) return; | ||
| let cancelConn: mysql.Connection | null = null; | ||
| try { | ||
| cancelConn = await mysql.createConnection({ | ||
| host: "localhost", | ||
| port: relayPort, | ||
| user: username, | ||
| database: database || undefined, | ||
| 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}]`); | ||
| } finally { | ||
| if (cancelConn) await cancelConn.end().catch(() => {}); | ||
| } | ||
| }; | ||
|
|
||
| // max_execution_time only covers SELECTs; this guards DML/DDL with KILL QUERY on a timer | ||
| const queryWithTimeout = async <T>(fn: () => Promise<T>, timeoutMs = 30_000): Promise<T> => { | ||
| const timer = setTimeout(() => { | ||
| void cancelRunningQuery(); | ||
| }, timeoutMs); | ||
| try { | ||
| return await fn(); | ||
| } finally { | ||
| clearTimeout(timer); | ||
| } | ||
| }; | ||
|
|
||
| let processingPromise: Promise<void> = Promise.resolve(); | ||
|
|
||
| const handleMessage = (message: TTabScopedMessage) => { | ||
| if (message.type === DataExplorerClientMessageType.Cancel) { | ||
| if (disposing) return; | ||
| void cancelRunningQuery(); | ||
| return; | ||
| } | ||
|
|
||
| processingPromise = processingPromise | ||
| .then(async () => { | ||
| if (disposing) return; | ||
|
|
||
| switch (message.type) { | ||
| case DataExplorerClientMessageType.GetTableDetail: { | ||
| try { | ||
| const query = getTableDetailQuery(message.schema, message.table); | ||
| const [rows] = await conn.execute<mysql.RowDataPacket[]>(query.sql, query.values); | ||
| // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | ||
| const rawDetail = rows[0]?.result; | ||
| if (!rawDetail) { | ||
| sendResponse({ | ||
| type: DataExplorerServerMessageType.Error, | ||
| id: message.id, | ||
| connectionId, | ||
| transactionOpen: isInTransaction, | ||
| error: "Table not found or no metadata available" | ||
| }); | ||
| break; | ||
| } | ||
| const detail = | ||
| typeof rawDetail === "string" | ||
| ? (JSON.parse(rawDetail) as Record<string, unknown>) | ||
| : (rawDetail as unknown as Record<string, unknown>); | ||
| sendResponse({ | ||
| type: DataExplorerServerMessageType.TableDetail, | ||
| id: message.id, | ||
| connectionId, | ||
| transactionOpen: isInTransaction, | ||
| data: detail as { | ||
| columns: { | ||
| name: string; | ||
| type: string; | ||
| nullable: boolean; | ||
| identityGeneration: string | null; | ||
| }[]; | ||
| primaryKeys: string[]; | ||
| foreignKeys: { | ||
| constraintName: string; | ||
| columns: string[]; | ||
| targetSchema: string; | ||
| targetTable: string; | ||
| targetColumns: string[]; | ||
| }[]; | ||
| } | ||
| }); | ||
| } catch (err) { | ||
| await sendQueryError(message.id, err); | ||
| } | ||
| break; | ||
| } | ||
|
|
||
| case DataExplorerClientMessageType.Query: { | ||
| try { | ||
| const startTime = performance.now(); | ||
|
|
||
| const stmts = splitMysqlStatements(message.sql); | ||
|
|
||
| let lastRows: Record<string, unknown>[] = []; | ||
| let lastFields: { name: string }[] = []; | ||
| let lastRowCount: number | null = null; | ||
| let lastCommand = ""; | ||
| let lastIsTruncated = false; | ||
|
|
||
| for (const stmtSql of stmts) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| await conn.query(`SET SESSION sql_select_limit = ${MAX_ROWS + 1}`); | ||
| // eslint-disable-next-line no-await-in-loop | ||
| const [result, fields] = await queryWithTimeout(() => conn.query(stmtSql)); | ||
|
|
||
| if (Array.isArray(result)) { | ||
| const rows = result as mysql.RowDataPacket[]; | ||
| lastIsTruncated = rows.length > MAX_ROWS; | ||
| lastRows = lastIsTruncated ? rows.slice(0, MAX_ROWS) : rows; | ||
| lastFields = (fields ?? []).map((f) => ({ name: f.name })); | ||
| lastRowCount = rows.length; | ||
| lastCommand = "SELECT"; | ||
| } else { | ||
| const header = result as mysql.ResultSetHeader; | ||
| lastRowCount = header.affectedRows; | ||
| lastCommand = extractCommand(stmtSql); | ||
| lastRows = []; | ||
| lastFields = []; | ||
| lastIsTruncated = false; | ||
| } | ||
| } | ||
|
|
||
| // eslint-disable-next-line no-await-in-loop | ||
| await queryTransactionState(); | ||
|
|
||
| const safeRows = lastRows.map((row) => { | ||
| const out: Record<string, unknown> = {}; | ||
| for (const [k, v] of Object.entries(row)) { | ||
| out[k] = Buffer.isBuffer(v) ? `\\x${v.toString("hex")}` : v; | ||
| } | ||
| return out; | ||
| }); | ||
|
|
||
| const executionTimeMs = Math.round(performance.now() - startTime); | ||
| sendResponse({ | ||
| type: DataExplorerServerMessageType.QueryResult, | ||
| id: message.id, | ||
| connectionId, | ||
| rows: safeRows, | ||
| fields: lastFields, | ||
| rowCount: lastRowCount, | ||
| isTruncated: lastIsTruncated, | ||
| transactionOpen: isInTransaction, | ||
| command: lastCommand, | ||
| executionTimeMs | ||
| }); | ||
| } catch (err) { | ||
| await sendQueryError(message.id, err); | ||
| } | ||
| break; | ||
| } | ||
|
|
||
| default: | ||
| break; | ||
| } | ||
| }) | ||
| .catch((err) => { | ||
| logger.error(err, `Error processing MySQL message [sessionId=${sessionId}] [connectionId=${connectionId}]`); | ||
| }); | ||
| }; | ||
|
|
||
| conn.on("error" as never, (err: Error) => { | ||
| if (disposing) return; | ||
| logger.error(err, `MySQL tab connection error [sessionId=${sessionId}] [connectionId=${connectionId}]`); | ||
| disposing = true; | ||
| 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; | ||
| void conn.end().catch((err) => { | ||
| logger.debug(err, `Error closing MySQL connection [sessionId=${sessionId}] [connectionId=${connectionId}]`); | ||
| }); | ||
| }; | ||
|
|
||
| return { | ||
| connectionId, | ||
| backendPid, | ||
| handleMessage, | ||
| dispose, | ||
| isDisposing: () => disposing | ||
| }; | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.