Skip to content

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

feat(pam): wire-level row limiting via pg-cursor + libpg-query

bernie-g084ee7e29ba4
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 6c2085b037..4b1403a93b 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -102,6 +102,7 @@
"knex": "^3.0.1",
"ldapjs": "^3.0.7",
"ldif": "0.5.1",
+ "libpg-query": "^17.7.3",
"libsodium-wrappers": "^0.7.13",
"lodash.isequal": "^4.5.0",
"mongodb": "^6.8.1",
@@ -126,6 +127,7 @@
"passport-ldapauth": "^3.0.1",
"passport-oauth2": "^1.8.0",
"pg": "^8.11.3",
+ "pg-cursor": "^2.19.0",
"pg-query-stream": "^4.5.3",
"pg-types": "^2.2.0",
"picomatch": "^3.0.1",
@@ -5681,9 +5683,6 @@
"arm"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5701,9 +5700,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5721,9 +5717,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5741,9 +5734,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5761,9 +5751,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5781,9 +5768,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5801,9 +5785,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5821,9 +5802,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -5841,9 +5819,6 @@
"arm"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -5867,9 +5842,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -5893,9 +5865,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -5919,9 +5888,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -5945,9 +5911,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -5971,9 +5934,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -5997,9 +5957,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -6023,9 +5980,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -7131,9 +7085,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -7151,9 +7102,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -7171,9 +7119,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -7191,9 +7136,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -8866,6 +8808,12 @@
"tsyringe": "^4.10.0"
}
},
+ "node_modules/@pgsql/types": {
+ "version": "17.6.2",
+ "resolved": "https://registry.npmjs.org/@pgsql/types/-/types-17.6.2.tgz",
+ "integrity": "sha512-1UtbELdbqNdyOShhrVfSz3a1gDi0s9XXiQemx+6QqtsrXe62a6zOGU+vjb2GRfG5jeEokI1zBBcfD42enRv0Rw==",
+ "license": "MIT"
+ },
"node_modules/@phc/format": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@phc/format/-/format-1.0.0.tgz",
@@ -9945,9 +9893,6 @@
"arm"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -9962,9 +9907,6 @@
"arm"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -9979,9 +9921,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -9996,9 +9935,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10013,9 +9949,6 @@
"loong64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10030,9 +9963,6 @@
"loong64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10047,9 +9977,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10064,9 +9991,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10081,9 +10005,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10098,9 +10019,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10115,9 +10033,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10132,9 +10047,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -10149,9 +10061,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -19419,6 +19328,15 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/libpg-query": {
+ "version": "17.7.3",
+ "resolved": "https://registry.npmjs.org/libpg-query/-/libpg-query-17.7.3.tgz",
+ "integrity": "sha512-lHKBvoWRsXt/9bJxpAeFxkLu0CA6tELusqy3o1z6/DwGXSETxhKJDaNlNdrNV8msvXDLBhpg/4RE/fKKs5rYFA==",
+ "license": "MIT",
+ "dependencies": {
+ "@pgsql/types": "^17.6.2"
+ }
+ },
"node_modules/libsodium": {
"version": "0.7.13",
"resolved": "https://registry.npmjs.org/libsodium/-/libsodium-0.7.13.tgz",
@@ -21962,9 +21880,10 @@
"integrity": "sha512-w6ZzNu6oMmIzEAYVw+RLK0+nqHPt8K3ZnknKi+g48Ak2pr3dtljJW3o+D/n2zzCG07Zoe9VOX3aiKpj+BN0pjg=="
},
"node_modules/pg-cursor": {
- "version": "2.10.3",
- "resolved": "https://registry.npmjs.org/pg-cursor/-/pg-cursor-2.10.3.tgz",
- "integrity": "sha512-rDyBVoqPVnx/PTmnwQAYgusSeAKlTL++gmpf5klVK+mYMFEqsOc6VHHZnPKc/4lOvr4r6fiMuoxSFuBF1dx4FQ==",
+ "version": "2.19.0",
+ "resolved": "https://registry.npmjs.org/pg-cursor/-/pg-cursor-2.19.0.tgz",
+ "integrity": "sha512-J5cF1MUz7LRJ9emOqF/06QjabMHMZy587rSPF0UuA8rCwKeeYl2co8Pp+6k5UU9YrAYHMzWkLxilfZB0hqsWWw==",
+ "license": "MIT",
"peerDependencies": {
"pg": "^8"
}
diff --git a/backend/package.json b/backend/package.json
index f598a02d5f..d61682cf78 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -224,6 +224,7 @@
"knex": "^3.0.1",
"ldapjs": "^3.0.7",
"ldif": "0.5.1",
+ "libpg-query": "^17.7.3",
"libsodium-wrappers": "^0.7.13",
"lodash.isequal": "^4.5.0",
"mongodb": "^6.8.1",
@@ -248,6 +249,7 @@
"passport-ldapauth": "^3.0.1",
"passport-oauth2": "^1.8.0",
"pg": "^8.11.3",
+ "pg-cursor": "^2.19.0",
"pg-query-stream": "^4.5.3",
"pg-types": "^2.2.0",
"picomatch": "^3.0.1",
diff --git a/backend/src/@types/pg-cursor.d.ts b/backend/src/@types/pg-cursor.d.ts
new file mode 100644
index 0000000000..11415e9fae
--- /dev/null
+++ b/backend/src/@types/pg-cursor.d.ts
@@ -0,0 +1,27 @@
+declare module "pg-cursor" {
+ import type { Connection } from "pg";
+
+ interface CursorConfig {
+ types?: {
+ getTypeParser: (oid: number) => (val: string | Buffer) => unknown;
+ };
+ }
+
+ class Cursor<TRow extends Record<string, unknown> = Record<string, unknown>> {
+ // Internal result object populated after read() completes.
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ _result: {
+ fields: { name: string }[];
+ command: string | null;
+ rowCount: number | null;
+ };
+
+ constructor(text: string, values?: unknown[] | null, config?: CursorConfig);
+
+ submit(connection: Connection): void;
+ read(rows: number): Promise<TRow[]>;
+ close(): Promise<void>;
+ }
+
+ export = Cursor;
+}
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
index 2fa159d98d..185a02c804 100644
--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
@@ -1,4 +1,6 @@
+import { parse as parseSql } from "libpg-query";
import pg from "pg";
+import Cursor from "pg-cursor";
import {
TPostgresAccountCredentials,
@@ -35,6 +37,22 @@ export const handlePostgresSession = async (
ctx;
const { connectionDetails, credentials } = params;
+ // Type parser shared between the pg.Client and pg-cursor instances so all
+ // results — whether fetched via the simple query path or cursor — apply the
+ // same normalisation rules.
+ const pgTypes = {
+ getTypeParser: (oid: number) => {
+ // Boolean (OID 16): Postgres wire protocol sends 't'/'f' — expand to 'true'/'false'
+ // so the Data Explorer UI displays human-readable literals.
+ if (oid === 16)
+ return (val: string | Buffer) => {
+ const raw = typeof val === "string" ? val : val.toString("utf8");
+ return raw === "t" ? "true" : "false";
+ };
+ return (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"));
+ }
+ };
+
const pgClient = new pg.Client({
host: "localhost",
port: relayPort,
@@ -44,18 +62,7 @@ export const handlePostgresSession = async (
ssl: false,
connectionTimeoutMillis: 30_000,
statement_timeout: 30_000,
- types: {
- getTypeParser: (oid: number) => {
- // Boolean (OID 16): Postgres wire protocol sends 't'/'f' — expand to 'true'/'false'
- // so the Data Explorer UI displays human-readable literals.
- if (oid === 16)
- return (val: string | Buffer) => {
- const raw = typeof val === "string" ? val : val.toString("utf8");
- return raw === "t" ? "true" : "false";
- };
- return (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"));
- }
- }
+ types: pgTypes
});
await pgClient.connect();
@@ -234,36 +241,61 @@ export const handlePostgresSession = async (
case PostgresClientMessageType.Query: {
try {
- // node-postgres returns an array of QueryResult objects when the SQL contains
- // multiple statements (simple query protocol). We take the last result so the
- // caller always sees a single consistent response — same behaviour as psql.
const startTime = performance.now();
- const rawResult = (await pgClient.query(message.sql)) as
- | pg.QueryResult<Record<string, unknown>>
- | pg.QueryResult<Record<string, unknown>>[];
- const executionTimeMs = Math.round(performance.now() - startTime);
const MAX_ROWS = 1000;
- // Scan all results to track transaction state accurately for multi-statement SQL.
- // e.g. "BEGIN; INSERT INTO foo VALUES (1);" — last command is INSERT, not BEGIN,
- // so checking only the last result would leave isInTransaction false incorrectly.
- const allResults = Array.isArray(rawResult) ? rawResult : [rawResult];
- for (const r of allResults) {
- const cmd = (r.command ?? "").toUpperCase();
+
+ // Split the SQL into individual statements using the real PostgreSQL C parser
+ // (via libpg-query WASM). Each statement is then run through a pg-cursor with
+ // an explicit row cap — the server sends at most MAX_ROWS+1 rows at the wire
+ // level regardless of result set size, so memory usage is bounded.
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ const parsed = await parseSql(message.sql);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const stmtTexts = (parsed.stmts as Array<{ stmt_location?: number; stmt_len?: number }>).map((s) => {
+ const location = s.stmt_location ?? 0;
+ return s.stmt_len !== undefined
+ ? message.sql.slice(location, location + s.stmt_len)
+ : message.sql.slice(location).trimEnd().replace(/;+$/, "").trim();
+ });
+
+ let lastRows: Record<string, unknown>[] = [];
+ let lastFields: { name: string }[] = [];
+ let lastRowCount: number | null = null;
+ let lastCommand = "";
+ let lastIsTruncated = false;
+
+ for (const stmtSql of stmtTexts) {
+ const cursor = pgClient.query(new Cursor(stmtSql.trim(), null, { types: pgTypes }));
+ // eslint-disable-next-line no-await-in-loop
+ const stmtRows = await cursor.read(MAX_ROWS + 1);
+ const stmtIsTruncated = stmtRows.length > MAX_ROWS;
+ if (stmtIsTruncated) stmtRows.splice(MAX_ROWS);
+ // eslint-disable-next-line no-await-in-loop
+ await cursor.close();
+
+ // eslint-disable-next-line no-underscore-dangle
+ const cursorResult = cursor._result;
+ const cmd = (cursorResult.command ?? "").toUpperCase();
if (cmd === "BEGIN" || cmd === "START") isInTransaction = true;
if (cmd === "COMMIT" || cmd === "ROLLBACK") isInTransaction = false;
+
+ lastRows = stmtRows;
+ lastFields = (cursorResult.fields ?? []).map((f) => ({ name: f.name }));
+ lastRowCount = cursorResult.rowCount;
+ lastCommand = cursorResult.command ?? "";
+ lastIsTruncated = stmtIsTruncated;
}
- const result = allResults[allResults.length - 1];
- const allRows = result.rows ?? [];
- const isTruncated = allRows.length > MAX_ROWS;
+
+ const executionTimeMs = Math.round(performance.now() - startTime);
sendResponse({
type: PostgresServerMessageType.QueryResult,
id: message.id,
- rows: allRows.slice(0, MAX_ROWS),
- fields: (result.fields ?? []).map((f) => ({ name: f.name })),
- rowCount: result.rowCount,
- isTruncated,
+ rows: lastRows,
+ fields: lastFields,
+ rowCount: lastRowCount,
+ isTruncated: lastIsTruncated,
transactionOpen: isInTransaction,
- command: result.command ?? "",
+ command: lastCommand,
executionTimeMs
});
} catch (err) {