Skip to content

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

feat(pam): snowflake account

Andreyd40e6ab48f8c
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
index 2d7eb2510c..cabed82f63 100644
--- a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
@@ -21,6 +21,7 @@ import {
} from "../pam-account/pam-account-connection-test";
import { TPamAccountDALFactory, TPamAccountDetail } from "../pam-account/pam-account-dal";
import {
+ collectCredentialSecrets,
parseInternalMetadata,
validateConnectionDetails,
validateCredentials
@@ -145,10 +146,7 @@ export const pamAccountHeartbeatServiceFactory = ({
accountType,
await decrypt(projectId, account.encryptedCredentials)
) as Record<string, unknown>;
- for (const field of ["password", "privateKey", "serviceAccountKeyJson", "clientSecret", "serviceAccountToken"]) {
- const value = credentials[field];
- if (typeof value === "string" && value) usedSecrets.push(value);
- }
+ usedSecrets.push(...collectCredentialSecrets(accountType, credentials));
const validateCloud = CLOUD_CONNECTION_VALIDATORS[accountType];
if (validateCloud) {
diff --git a/backend/src/ee/services/pam-account/pam-account-connection-test.ts b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
index 6667443f6b..60764c4314 100644
--- a/backend/src/ee/services/pam-account/pam-account-connection-test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
@@ -17,6 +17,7 @@ export enum TestConnectionMode {
LDAP = "ldap",
Kubernetes = "kubernetes",
SSH = "ssh",
+ Snowflake = "snowflake",
Tcp = "tcp"
}
@@ -80,6 +81,20 @@ export type TestConnectionRequest =
privateKey?: string;
certificate?: string;
}
+ | {
+ mode: TestConnectionMode.Snowflake;
+ account: string;
+ authMethod: string;
+ username: string;
+ password?: string;
+ token?: string;
+ privateKey?: string;
+ privateKeyPassphrase?: string;
+ warehouse?: string;
+ database?: string;
+ schema?: string;
+ role?: string;
+ }
| { mode: TestConnectionMode.Tcp };
const SQL_DIALECTS = {
@@ -300,6 +315,42 @@ export const buildGatewayConnectionTest = async (
}
};
}
+ case PamAccountType.Snowflake: {
+ const cd = connectionDetails as {
+ account: string;
+ warehouse?: string;
+ database?: string;
+ schema?: string;
+ role?: string;
+ };
+ const c = creds as {
+ authMethod: string;
+ username: string;
+ password?: string;
+ token?: string;
+ privateKey?: string;
+ privateKeyPassphrase?: string;
+ } | null;
+ if (!c) return tcp(host, port);
+ return {
+ host,
+ port,
+ request: {
+ mode: TestConnectionMode.Snowflake,
+ account: cd.account,
+ authMethod: c.authMethod,
+ username: c.username,
+ password: c.password,
+ token: c.token,
+ privateKey: c.privateKey,
+ privateKeyPassphrase: c.privateKeyPassphrase,
+ warehouse: cd.warehouse,
+ database: cd.database,
+ schema: cd.schema,
+ role: cd.role
+ }
+ };
+ }
case PamAccountType.Windows:
return tcp(host, port);
default:
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 692b8d9cc1..c3641a5859 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
@@ -1,10 +1,11 @@
import { describe, expect, test } from "vitest";
-import { PamAccountType, PamPostgresAuthMethod } from "../pam/pam-enums";
+import { PamAccountType, PamPostgresAuthMethod, PamSnowflakeAuthMethod } from "../pam/pam-enums";
import {
accountTypeRequiresRecording,
applyForcedFields,
buildPamAccountTypeMetadata,
+ collectCredentialSecrets,
getAccountAccessibilityIssues,
isCredentialConfigured,
PamAccountAccessibilityIssue,
@@ -12,6 +13,7 @@ import {
PamFieldDescriptorSchema,
sanitizeCredentials,
suppliesCredentialSecret,
+ validateConnectionDetails,
validateCredentials
} from "./pam-account-schemas";
@@ -232,6 +234,54 @@ describe("buildPamAccountTypeMetadata", () => {
});
});
+describe("collectCredentialSecrets", () => {
+ test("returns every stored secret for the account type's auth method", () => {
+ expect(
+ collectCredentialSecrets(PamAccountType.Snowflake, {
+ authMethod: PamSnowflakeAuthMethod.KeyPair,
+ username: "svc",
+ privateKey: "pem-body",
+ privateKeyPassphrase: "phrase"
+ })
+ ).toEqual(expect.arrayContaining(["pem-body", "phrase"]));
+
+ expect(
+ collectCredentialSecrets(PamAccountType.Snowflake, {
+ authMethod: PamSnowflakeAuthMethod.ProgrammaticAccessToken,
+ username: "svc",
+ token: "pat-value"
+ })
+ ).toEqual(["pat-value"]);
+ });
+});
+
+describe("Snowflake accounts", () => {
+ test("require a secret for the selected auth method", () => {
+ expect(
+ isCredentialConfigured(PamAccountType.Snowflake, {
+ authMethod: PamSnowflakeAuthMethod.KeyPair,
+ username: "svc",
+ privateKey: "pem-body"
+ })
+ ).toBe(true);
+ expect(
+ isCredentialConfigured(PamAccountType.Snowflake, {
+ authMethod: PamSnowflakeAuthMethod.KeyPair,
+ username: "svc"
+ })
+ ).toBe(false);
+ });
+
+ test("reject an account identifier carrying the Snowflake domain", () => {
+ expect(() =>
+ validateConnectionDetails(PamAccountType.Snowflake, {
+ account: "myorg-myaccount.snowflakecomputing.com",
+ database: "analytics"
+ })
+ ).toThrow();
+ });
+});
+
describe("isCredentialConfigured", () => {
test("Postgres/MySQL require a non-empty password", () => {
expect(isCredentialConfigured(PamAccountType.Postgres, { username: "u", password: "p" })).toBe(true);
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
index dc20691b96..82befe0bfe 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -8,7 +8,13 @@ import { z } from "zod";
import { BadRequestError } from "@app/lib/errors";
import { netbiosFromDomainFqdn } from "@app/lib/ldap/ldap-search-fns";
-import { GcpServiceAccountAuthMethod, PamAccountType, PamPostgresAuthMethod, PamSshAuthMethod } from "../pam/pam-enums";
+import {
+ GcpServiceAccountAuthMethod,
+ PamAccountType,
+ PamPostgresAuthMethod,
+ PamSnowflakeAuthMethod,
+ PamSshAuthMethod
+} from "../pam/pam-enums";
import { getApplicablePolicies, PamPolicyDescriptorSchema } from "../pam/pam-policies";
import {
PamAccountSettingsOverridesSchema,
@@ -33,6 +39,14 @@ const optionalTrimmedString = z
.transform((v) => v || undefined)
.optional();
+const boundedOptionalString = (max: number) =>
+ z
+ .string()
+ .trim()
+ .max(max)
+ .transform((v) => v || undefined)
+ .optional();
+
const normalizeDelimitedStringList = (value: unknown): unknown => {
if (Array.isArray(value)) return value;
if (typeof value !== "string") return value;
@@ -45,6 +59,7 @@ const normalizeDelimitedStringList = (value: unknown): unknown => {
};
export const hostPattern = new RE2(/^[A-Za-z0-9.:_-]+$/);
+const snowflakeAccountPattern = new RE2(/^[A-Za-z0-9][A-Za-z0-9._-]*$/);
const delimitedStringList = z.preprocess(
normalizeDelimitedStringList,
z.array(z.string().trim().min(1).max(255).regex(hostPattern, "Must be a valid hostname or IP address")).min(1)
@@ -437,6 +452,86 @@ export const ACCOUNT_TYPE_CONFIGS = {
}
},
+ [PamAccountType.Snowflake]: {
+ name: "Snowflake",
+ icon: "Snowflake.png",
+ connectionDetails: z.object({
+ account: z
+ .string()
+ .trim()
+ .min(1)
+ .max(255)
+ .regex(snowflakeAccountPattern, "Must be a valid Snowflake account identifier")
+ .refine((val) => !val.toLowerCase().includes("snowflakecomputing.com"), {
+ message: "Enter the account identifier only, without the snowflakecomputing.com suffix"
+ }),
+ warehouse: boundedOptionalString(255),
+ database: z.string().trim().min(1).max(255),
+ schema: boundedOptionalString(255),
+ role: boundedOptionalString(255)
+ }),
+ credentials: z.discriminatedUnion("authMethod", [
+ z.object({
+ authMethod: z.literal(PamSnowflakeAuthMethod.KeyPair),
+ username: z.string().trim().min(1).max(255),
+ privateKey: boundedOptionalString(8192),
+ privateKeyPassphrase: boundedOptionalString(256)
+ }),
+ z.object({
+ authMethod: z.literal(PamSnowflakeAuthMethod.ProgrammaticAccessToken),
+ username: z.string().trim().min(1).max(255),
+ token: boundedOptionalString(2048)
+ }),
+ z.object({
+ authMethod: z.literal(PamSnowflakeAuthMethod.Password),
+ username: z.string().trim().min(1).max(255),
+ password: boundedOptionalString(256)
+ })
+ ]),
+ sanitizedCredentials: z.object({
+ authMethod: z.string(),
+ username: z.string()
+ }),
+ ui: {
+ account: {
+ label: "Account Identifier",
+ tooltip:
+ "The account identifier from the Snowflake URL, without the snowflakecomputing.com suffix (e.g. myorg-myaccount)."
+ },
+ warehouse: { tooltip: "The warehouse sessions run their queries on. Snowflake charges for its compute." },
+ database: { tooltip: "The database sessions open. The explorer lists the schemas and tables inside it." },
+ schema: { tooltip: "The schema sessions open by default." },
+ role: {
+ tooltip: "The role sessions activate. Leave empty to use the user's default role."
+ },
+ authMethod: {
+ label: "Auth Method",
+ defaultValue: PamSnowflakeAuthMethod.KeyPair,
+ tooltip:
+ "Snowflake blocks single-factor password sign-in for human users, so key pair or a programmatic access token is required for most accounts.",
+ options: [
+ { label: "Key Pair (Recommended)", value: PamSnowflakeAuthMethod.KeyPair },
+ { label: "Programmatic Access Token", value: PamSnowflakeAuthMethod.ProgrammaticAccessToken },
+ { label: "Password", value: PamSnowflakeAuthMethod.Password }
+ ]
+ },
+ privateKey: {
+ label: "Private Key",
+ widget: PamFieldWidget.Textarea,
+ secret: true,
+ tooltip: "The PKCS#8 private key whose public key is set on the Snowflake user (RSA_PUBLIC_KEY)."
+ },
+ privateKeyPassphrase: {
+ label: "Private Key Passphrase",
+ widget: PamFieldWidget.Password,
+ secret: true,
+ optional: true
+ },
+ token: { label: "Programmatic Access Token", widget: PamFieldWidget.Password, secret: true },
+ password: { widget: PamFieldWidget.Password, secret: true }
+ }
+ },
+
[PamAccountType.SSH]: {
name: "SSH",
icon: "SSH.png",
@@ -896,6 +991,8 @@ export const extractGatewayTarget = async (
return { host: "googleapis.com", port: 443 };
case PamAccountType.AwsIam:
throw new Error("AWS IAM accounts do not use gateway routing");
+ case PamAccountType.Snowflake:
+ return { host: `${(validated as { account: string }).account}.snowflakecomputing.com`, port: 443 };
case PamAccountType.AzureCli:
return { host: "management.azure.com", port: 443 };
default:
@@ -1329,6 +1426,21 @@ export const suppliesCredentialSecret = (
});
};
+// Redaction inputs for anything a target echoes back
+export const collectCredentialSecrets = (
+ accountType: PamAccountType,
+ rawCredentials: Record<string, unknown>
+): string[] => {
+ const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
+ if (!config) return [];
+
+ const credentials = normalizeCredentialAuthMethod(accountType, rawCredentials);
+ return fieldsFromSchema(config.credentials, config.ui)
+ .filter((field) => field.secret)
+ .map((field) => credentials[field.key])
+ .filter((value): value is string => typeof value === "string" && value.length > 0);
+};
+
export const isCredentialConfigured = (
accountType: PamAccountType,
rawCredentials: Record<string, unknown>
diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.ts
index a8969a3dee..e8c3cc96b9 100644
--- a/backend/src/ee/services/pam-session/pam-session-dal.ts
+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts
@@ -57,6 +57,14 @@ export const pamSessionDALFactory = (db: TDbClient) => {
return updated;
};
+ const isSessionTerminated = async (sessionId: string, tx?: Knex) => {
+ const session = await (tx || db.replicaNode())(TableName.PamSession)
+ .where("id", sessionId)
+ .select("status")
+ .first();
+ return session?.status === PamSessionStatus.Terminated;
+ };
+
const terminateSessionById = async (sessionId: string, tx?: Knex) => {
const [updated] = await (tx || db)(TableName.PamSession)
.where("id", sessionId)
@@ -172,6 +180,7 @@ export const pamSessionDALFactory = (db: TDbClient) => {
countActiveWebSessions,
endExpiredWebSessions,
endSessionById,
+ isSessionTerminated,
terminateSessionById,
activateSession,
findByProjectId,
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 1923c55af8..e8b7319541 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -729,6 +729,11 @@ export const pamSessionServiceFactory = ({
if (rawConnectionDetails.subscriptionId) {
metadata.subscriptionId = rawConnectionDetails.subscriptionId as string;
}
+ } else if (account.accountType === PamAccountType.Snowflake) {
+ for (const key of ["account", "warehouse", "database", "schema", "role"]) {
+ const value = rawConnectionDetails[key];
+ if (typeof value === "string" && value) metadata[key] = value;
+ }
} else if (account.accountType === PamAccountType.Kubernetes) {
metadata.authMethod = rawCredentials.authMethod as string;
if (rawCredentials.namespace) {
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 23a0be3363..1a3d9096d0 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
@@ -23,12 +23,11 @@ export type OneShotOptions = {
relayPort: number;
username: string;
database?: string;
+ // A dialect the gateway serves over HTTP rather than a wire protocol reads its target from here
+ connectionDetails: Record<string, unknown>;
};
-export type ControllerParams = {
- relayPort: number;
- username: string;
- database?: string;
+export type ControllerParams = OneShotOptions & {
sessionId: string;
connectionId: string;
sendResponse: (msg: TDataExplorerServerMessage) => void;
@@ -58,7 +57,8 @@ export const createDataExplorerSessionHandler = (config: TDataExplorerDialectCon
const oneShotOpts: OneShotOptions = {
relayPort,
username: credentials.username,
- database: connectionDetails.database
+ database: connectionDetails.database,
+ connectionDetails: params.connectionDetails
};
await verifyReachability(oneShotOpts);
@@ -98,9 +98,7 @@ export const createDataExplorerSessionHandler = (config: TDataExplorerDialectCon
controllers.set(connectionId, null);
try {
const controller = await createController({
- relayPort,
- username: credentials.username,
- database: connectionDetails.database,
+ ...oneShotOpts,
sessionId,
connectionId,
sendResponse,
diff --git a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts b/backend/src/ee/services/pam-web-access/pam-session-handlers.ts
index eccec6a269..549a54e6b2 100644
--- a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts
+++ b/backend/src/ee/services/pam-web-access/pam-session-handlers.ts
@@ -5,6 +5,7 @@ import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";
import { handlePostgresSession } from "./postgres/pam-postgres-session-handler";
import { handleRdpSession } from "./rdp/pam-rdp-session-handler";
import { handleRedisSession } from "./redis/pam-redis-session-handler";
+import { handleSnowflakeSession } from "./snowflake/pam-snowflake-session-handler";
import { handleSSHSession } from "./ssh/pam-ssh-session-handler";
export type TWebAccessHandler = (
@@ -30,6 +31,10 @@ export const SESSION_HANDLERS: Partial<Record<PamAccountType, TSessionHandlerEnt
gatewayAccountType: PamAccountType.Redis,
handler: handleRedisSession
},
+ [PamAccountType.Snowflake]: {
+ gatewayAccountType: PamAccountType.Snowflake,
+ handler: handleSnowflakeSession
+ },
[PamAccountType.SSH]: {
gatewayAccountType: PamAccountType.SSH,
handler: handleSSHSession
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
index 60f2028b21..afb3f11b9e 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
@@ -66,7 +66,13 @@ type TPamWebAccessServiceFactoryDep = {
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
pamSessionDAL: Pick<
TPamSessionDALFactory,
- "create" | "endSessionById" | "activateSession" | "countActiveWebSessions" | "endExpiredWebSessions" | "updateById"
+ | "create"
+ | "endSessionById"
+ | "activateSession"
+ | "countActiveWebSessions"
+ | "endExpiredWebSessions"
+ | "isSessionTerminated"
+ | "updateById"
>;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId" | "runWithPoolFailover">;
@@ -676,6 +682,18 @@ export const pamWebAccessServiceFactory = ({
if (socket.readyState === socket.OPEN) {
socket.ping();
}
+
+ void (async () => {
+ const sessionId = session?.id;
+ if (!sessionId || cleanedUp) return;
+ try {
+ if (!(await pamSessionDAL.isSessionTerminated(sessionId))) return;
+ await cleanup();
+ sendSessionEndAndClose(socket, SessionEndReason.Terminated);
+ } catch (err) {
+ logger.error(err, `Failed to check session termination [sessionId=${sessionId}]`);
+ }
+ })();
}, WS_PING_INTERVAL_MS);
socket.on("message", () => {
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
index 7544f06601..55dafce42f 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
@@ -12,6 +12,7 @@ export enum SessionEndReason {
IdleTimeout = "Session closed due to inactivity",
SessionLimitReached = "Maximum concurrent sessions reached",
ApprovalRevoked = "Your approved access is no longer active",
+ Terminated = "This session was terminated",
ReplyTooLarge = "The reply was too large to read safely. Use the Infisical CLI for data this size"
}
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-connection-controller.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-connection-controller.ts
new file mode 100644
index 0000000000..f64bd70935
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-connection-controller.ts
@@ -0,0 +1,245 @@
+import snowflake from "snowflake-sdk";
+
+import { logger } from "@app/lib/logger";
+import { executeSnowflakeSql } from "@app/services/app-connection/snowflake";
+
+import { type ControllerParams } from "../pam-data-explorer-session-handler";
+import {
+ DataExplorerClientMessageType,
+ DataExplorerServerMessageType,
+ type TConnectionController,
+ type TTabScopedMessage
+} from "../pam-data-explorer-ws-types";
+import { extractCommand, nextTransactionState, splitSnowflakeStatements } from "./pam-snowflake-data-explorer-fns";
+import {
+ COLUMNS_QUERY,
+ showImportedKeysQuery,
+ showPrimaryKeysQuery,
+ TColumnRow,
+ toColumns,
+ toForeignKeys,
+ toPrimaryKeys
+} from "./pam-snowflake-data-explorer-metadata";
+import { snowflakeAccountOf } from "./pam-snowflake-metadata";
+import { connectThroughRelay } from "./pam-snowflake-relay-client";
+
+const MAX_ROWS = 1000;
+
+const readRows = (
+ statement: snowflake.RowStatement
+): Promise<{ rows: Record<string, unknown>[]; truncated: boolean }> =>
+ new Promise((resolve, reject) => {
+ const rows: Record<string, unknown>[] = [];
+ let truncated = false;
+ const stream = statement.streamRows();
+
+ stream.on("data", (row: Record<string, unknown>) => {
+ if (rows.length < MAX_ROWS) {
+ rows.push(row);
+ return;
+ }
+ truncated = true;
+ stream.destroy();
+ resolve({ rows, truncated });
+ });
+ stream.on("error", (err) => {
+ if (truncated) resolve({ rows, truncated });
+ else reject(err);
+ });
+ stream.on("end", () => resolve({ rows, truncated }));
+ });
+
+export const createSnowflakeConnectionController = async (params: ControllerParams): Promise<TConnectionController> => {
+ const { sessionId, connectionId, sendResponse, onUnexpectedTermination } = params;
+
+ const client = await connectThroughRelay(params.relayPort, snowflakeAccountOf(params));
+
+ let isInTransaction = false;
+ let disposing = false;
+ let runningStatement: snowflake.RowStatement | null = null;
+
+ const execute = (sqlText: string): Promise<snowflake.RowStatement> =>
+ new Promise((resolve, reject) => {
+ runningStatement = client.execute({
+ sqlText,
+ streamResult: true,
+ complete: (err, statement) => {
+ if (err) reject(err);
+ else resolve(statement as snowflake.RowStatement);
+ }
+ }) as snowflake.RowStatement;
+ });
+
+ const cancelRunningStatement = () => {
+ const statement = runningStatement;
+ if (!statement) return;
+ statement.cancel((err) => {
+ if (err) {
+ logger.debug(err, `Failed to cancel Snowflake query [sessionId=${sessionId}] [connectionId=${connectionId}]`);
+ }
+ });
+ };
+
+ const sendQueryError = async (id: string, err: unknown) => {
+ // The tunnel is gone once the session is terminated, so the tab is closed rather than left waiting
+ if (!disposing && !client.isUp()) {
+ disposing = true;
+ onUnexpectedTermination("Session ended");
+ return;
+ }
+
+ // Snowflake leaves a failed statement's transaction open, holding its locks until the session ends
+ if (isInTransaction) {
+ try {
+ await executeSnowflakeSql(client, "ROLLBACK");
+ } catch {
+ // nothing to roll back
+ }
+ isInTransaction = false;
+ }
+
+ sendResponse({
+ type: DataExplorerServerMessageType.Error,
+ id,
+ connectionId,
+ transactionOpen: isInTransaction,
+ error: (err as Error)?.message ?? "Query execution failed",
+ detail: (err as { sqlState?: string })?.sqlState
+ });
+ };
+
+ const runTableDetail = async (schema: string, table: string) => {
+ const columns = await executeSnowflakeSql<TColumnRow>(client, COLUMNS_QUERY, [schema, table]);
+ if (columns.length === 0) return null;
+
+ const primaryKeyRows = await executeSnowflakeSql(client, showPrimaryKeysQuery(schema, table));
+ const importedKeyRows = await executeSnowflakeSql(client, showImportedKeysQuery(schema, table));
+
+ return {
+ columns: toColumns(columns),
+ primaryKeys: toPrimaryKeys(primaryKeyRows),
+ foreignKeys: toForeignKeys(importedKeyRows)
+ };
+ };
+
+ const runQuery = async (sql: string) => {
+ const startTime = performance.now();
+
+ let lastRows: Record<string, unknown>[] = [];
+ let lastFields: { name: string }[] = [];
+ let lastRowCount: number | null = null;
+ let lastCommand = "";
+ let lastIsTruncated = false;
+
+ try {
+ for (const statementSql of splitSnowflakeStatements(sql)) {
+ // eslint-disable-next-line no-await-in-loop
+ const statement = await execute(statementSql);
+ // eslint-disable-next-line no-await-in-loop
+ const { rows, truncated } = await readRows(statement);
+
+ lastCommand = extractCommand(statementSql);
+ isInTransaction = nextTransactionState(lastCommand, isInTransaction);
+ lastRows = rows;
+ lastFields = (statement.getColumns() ?? []).map((column) => ({ name: column.getName() }));
+ // The driver reports -1, not undefined, when nothing was updated, so a SELECT falls through
+ const updatedRows = statement.getNumUpdatedRows();
+ lastRowCount =
+ typeof updatedRows === "number" && updatedRows >= 0 ? updatedRows : (statement.getNumRows() ?? null);
+ lastIsTruncated = truncated;
+ }
+ } finally {
+ runningStatement = null;
+ }
+
+ return {
+ rows: lastRows,
+ fields: lastFields,
+ rowCount: lastRowCount,
+ isTruncated: lastIsTruncated,
+ command: lastCommand,
+ executionTimeMs: Math.round(performance.now() - startTime)
+ };
+ };
+
+ let processingPromise: Promise<void> = Promise.resolve();
+
+ const handleMessage = (message: TTabScopedMessage) => {
+ if (message.type === DataExplorerClientMessageType.Cancel) {
+ if (disposing) return;
+ cancelRunningStatement();
+ return;
+ }
+
+ processingPromise = processingPromise
+ .then(async () => {
+ if (disposing) return;
+
+ switch (message.type) {
+ case DataExplorerClientMessageType.GetTableDetail: {
+ try {
+ const detail = await runTableDetail(message.schema, message.table);
+ if (!detail) {
+ sendResponse({
+ type: DataExplorerServerMessageType.Error,
+ id: message.id,
+ connectionId,
+ transactionOpen: isInTransaction,
+ error: "Table not found or no metadata available"
+ });
+ break;
+ }
+ sendResponse({
+ type: DataExplorerServerMessageType.TableDetail,
+ id: message.id,
+ connectionId,
+ transactionOpen: isInTransaction,
+ data: detail
+ });
+ } catch (err) {
+ await sendQueryError(message.id, err);
+ }
+ break;
+ }
+
+ case DataExplorerClientMessageType.Query: {
+ try {
+ const result = await runQuery(message.sql);
+ sendResponse({
+ type: DataExplorerServerMessageType.QueryResult,
+ id: message.id,
+ connectionId,
+ transactionOpen: isInTransaction,
+ ...result
+ });
+ } catch (err) {
+ await sendQueryError(message.id, err);
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+ })
+ .catch((err) => {
+ logger.error(err, `Error processing Snowflake message [sessionId=${sessionId}] [connectionId=${connectionId}]`);
+ });
+ };
+
+ const dispose = () => {
+ if (disposing) return;
+ disposing = true;
+ cancelRunningStatement();
+ client.destroy(() => {});
+ };
+
+ return {
+ connectionId,
+ // Snowflake has no numeric backend id
+ nativeConnectionId: null,
+ handleMessage,
+ dispose,
+ isDisposing: () => disposing
+ };
+};
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-fns.test.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-fns.test.ts
new file mode 100644
index 0000000000..9109842b0d
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-fns.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, test } from "vitest";
+
+import { extractCommand, nextTransactionState, splitSnowflakeStatements } from "./pam-snowflake-data-explorer-fns";
+
+describe("splitSnowflakeStatements", () => {
+ test("single statement with and without a trailing semicolon", () => {
+ expect(splitSnowflakeStatements("SELECT 1")).toEqual(["SELECT 1"]);
+ expect(splitSnowflakeStatements("SELECT 1;")).toEqual(["SELECT 1"]);
+ });
+
+ test("multiple statements", () => {
+ expect(splitSnowflakeStatements("SELECT 1; SELECT 2; SELECT 3")).toEqual(["SELECT 1", "SELECT 2", "SELECT 3"]);
+ });
+
+ test("drops empty statements and whitespace-only input", () => {
+ expect(splitSnowflakeStatements("SELECT 1;; ;SELECT 2")).toEqual(["SELECT 1", "SELECT 2"]);
+ expect(splitSnowflakeStatements("")).toEqual([]);
+ expect(splitSnowflakeStatements(" \n\t ")).toEqual([]);
+ });
+
+ test("semicolon inside a string literal", () => {
+ expect(splitSnowflakeStatements("SELECT 'a;b'; SELECT 2")).toEqual(["SELECT 'a;b'", "SELECT 2"]);
+ });
+
+ test("semicolon inside a quoted identifier", () => {
+ expect(splitSnowflakeStatements('SELECT "col;name" FROM t; SELECT 2')).toEqual([
+ 'SELECT "col;name" FROM t',
+ "SELECT 2"
+ ]);
+ });
+
+ test("escaped quotes inside a literal", () => {
+ expect(splitSnowflakeStatements("SELECT 'it''s;fine'; SELECT 2")).toEqual(["SELECT 'it''s;fine'", "SELECT 2"]);
+ expect(splitSnowflakeStatements("SELECT 'a\\';b'; SELECT 2")).toEqual(["SELECT 'a\\';b'", "SELECT 2"]);
+ });
+
+ test("semicolons inside a dollar-quoted block", () => {
+ expect(splitSnowflakeStatements("EXECUTE IMMEDIATE $$ BEGIN; SELECT 1; END; $$; SELECT 2")).toEqual([
+ "EXECUTE IMMEDIATE $$ BEGIN; SELECT 1; END; $$",
+ "SELECT 2"
+ ]);
+ });
+
+ test("semicolon inside comments", () => {
+ expect(splitSnowflakeStatements("SELECT 1 -- a;b\n; SELECT 2")).toEqual(["SELECT 1 -- a;b", "SELECT 2"]);
+ expect(splitSnowflakeStatements("SELECT 1 // a;b\n; SELECT 2")).toEqual(["SELECT 1 // a;b", "SELECT 2"]);
+ expect(splitSnowflakeStatements("SELECT 1 /* a;b */; SELECT 2")).toEqual(["SELECT 1 /* a;b */", "SELECT 2"]);
+ });
+
+ test("unterminated literal keeps the rest of the input in one statement", () => {
+ expect(splitSnowflakeStatements("SELECT 'a; SELECT 2")).toEqual(["SELECT 'a; SELECT 2"]);
+ });
+
+ test("a backslash escapes inside a literal but not inside a quoted identifier", () => {
+ expect(splitSnowflakeStatements(String.raw`SELECT 'a\'; b'; SELECT 2`)).toEqual([
+ String.raw`SELECT 'a\'; b'`,
+ "SELECT 2"
+ ]);
+ expect(splitSnowflakeStatements(String.raw`SELECT "a\"; SELECT 2`)).toEqual([String.raw`SELECT "a\"`, "SELECT 2"]);
+ });
+});
+
+describe("extractCommand", () => {
+ test("reads the leading keyword, uppercased", () => {
+ expect(extractCommand("select * from t")).toBe("SELECT");
+ expect(extractCommand(" \n BEGIN")).toBe("BEGIN");
+ });
+
+ test("skips leading comments", () => {
+ expect(extractCommand("-- note\nCOMMIT")).toBe("COMMIT");
+ expect(extractCommand("// note\nROLLBACK")).toBe("ROLLBACK");
+ expect(extractCommand("/* note */ INSERT INTO t VALUES (1)")).toBe("INSERT");
+ });
+
+ test("stops at a delimiter", () => {
+ expect(extractCommand("COMMIT;")).toBe("COMMIT");
+ expect(extractCommand("SELECT(1)")).toBe("SELECT");
+ });
+
+ test("empty input", () => {
+ expect(extractCommand(" ")).toBe("");
+ });
+});
+
+describe("nextTransactionState", () => {
+ test("BEGIN and START open a transaction", () => {
+ expect(nextTransactionState("BEGIN", false)).toBe(true);
+ expect(nextTransactionState("START", false)).toBe(true);
+ });
+
+ test("COMMIT and ROLLBACK close it", () => {
+ expect(nextTransactionState("COMMIT", true)).toBe(false);
+ expect(nextTransactionState("ROLLBACK", true)).toBe(false);
+ });
+
+ test("any other statement leaves the state alone", () => {
+ expect(nextTransactionState("SELECT", true)).toBe(true);
+ expect(nextTransactionState("SELECT", false)).toBe(false);
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-fns.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-fns.ts
new file mode 100644
index 0000000000..7c66766894
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-fns.ts
@@ -0,0 +1,108 @@
+const skipQuoted = (sql: string, pos: number, quote: string): number => {
+ // A backslash escapes inside a string literal, but not inside a quoted identifier
+ const escapes = quote === "'";
+ let i = pos + 1;
+ while (i < sql.length) {
+ if (escapes && 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 sql.length;
+};
+
+// $$ ... $$ carries SQL verbatim, semicolons included
+const skipDollarQuoted = (sql: string, pos: number): number => {
+ const end = sql.indexOf("$$", pos + 2);
+ return end === -1 ? sql.length : end + 2;
+};
+
+const isDollarQuote = (sql: string, pos: number) => sql[pos] === "$" && sql[pos + 1] === "$";
+
+const isLineComment = (sql: string, pos: number) =>
+ (sql[pos] === "-" && sql[pos + 1] === "-") || (sql[pos] === "/" && sql[pos + 1] === "/");
+
+const isBlockComment = (sql: string, pos: number) => sql[pos] === "/" && sql[pos + 1] === "*";
+
+const skipLineComment = (sql: string, pos: number): number => {
+ let i = pos + 2;
+ 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;
+ return Math.min(i + 2, sql.length);
+};
+
+// MULTI_STATEMENT_COUNT would hide each statement's own result, so the session splits on ';' itself
+export const splitSnowflakeStatements = (sql: string): string[] => {
+ const statements: string[] = [];
+ let pos = 0;
+ let statementStart = 0;
+
+ while (pos < sql.length) {
+ const ch = sql[pos];
+
+ if (ch === "'" || ch === '"') {
+ pos = skipQuoted(sql, pos, ch);
+ } else if (isDollarQuote(sql, pos)) {
+ pos = skipDollarQuoted(sql, pos);
+ } else if (isLineComment(sql, pos)) {
+ pos = skipLineComment(sql, pos);
+ } else if (isBlockComment(sql, pos)) {
+ pos = skipBlockComment(sql, pos);
+ } else if (ch === ";") {
+ const statement = sql.slice(statementStart, pos).trim();
+ if (statement.length > 0) statements.push(statement);
+ pos += 1;
+ statementStart = pos;
+ } else {
+ pos += 1;
+ }
+ }
+
+ const tail = sql.slice(statementStart).trim();
+ if (tail.length > 0) statements.push(tail);
+
+ return statements;
+};
+
+export const extractCommand = (sql: string): string => {
+ let pos = 0;
+
+ while (pos < sql.length) {
+ const ch = sql[pos];
+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {
+ pos += 1;
+ } else if (isLineComment(sql, pos)) {
+ pos = skipLineComment(sql, pos);
+ } else if (isBlockComment(sql, pos)) {
+ pos = skipBlockComment(sql, pos);
+ } else {
+ break;
+ }
+ }
+
+ const start = pos;
+ while (pos < sql.length && !" \t\n\r;(".includes(sql[pos])) pos += 1;
+ return sql.slice(start, pos).toUpperCase();
+};
+
+const TRANSACTION_OPENING_COMMANDS = new Set(["BEGIN", "START"]);
+const TRANSACTION_CLOSING_COMMANDS = new Set(["COMMIT", "ROLLBACK"]);
+
+// Snowflake reports no transaction flag on a result, so it is tracked from the statements run
+export const nextTransactionState = (command: string, current: boolean): boolean => {
+ if (TRANSACTION_OPENING_COMMANDS.has(command)) return true;
+ if (TRANSACTION_CLOSING_COMMANDS.has(command)) return false;
+ return current;
+};
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-metadata.test.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-metadata.test.ts
new file mode 100644
index 0000000000..d92167e54f
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-metadata.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, test } from "vitest";
+
+import { toColumns, toForeignKeys, toPrimaryKeys } from "./pam-snowflake-data-explorer-metadata";
+
+describe("toPrimaryKeys", () => {
+ test("orders columns by key sequence", () => {
+ expect(
+ toPrimaryKeys([
+ { column_name: "b", key_sequence: 2 },
+ { column_name: "a", key_sequence: 1 }
+ ])
+ ).toEqual(["a", "b"]);
+ });
+
+ test("reads uppercase column names", () => {
+ expect(toPrimaryKeys([{ COLUMN_NAME: "ID", KEY_SEQUENCE: 1 }])).toEqual(["ID"]);
+ });
+
+ test("no primary key", () => {
+ expect(toPrimaryKeys([])).toEqual([]);
+ });
+});
+
+describe("toForeignKeys", () => {
+ test("groups a composite key into one constraint, ordered by key sequence", () => {
+ expect(
+ toForeignKeys([
+ {
+ fk_name: "FK_ORDER",
+ fk_column_name: "tenant_id",
+ pk_column_name: "id_tenant",
+ pk_schema_name: "PUBLIC",
+ pk_table_name: "TENANT",
+ key_sequence: 2
+ },
+ {
+ fk_name: "FK_ORDER",
+ fk_column_name: "org_id",
+ pk_column_name: "id_org",
+ pk_schema_name: "PUBLIC",
+ pk_table_name: "TENANT",
+ key_sequence: 1
+ }
+ ])
+ ).toEqual([
+ {
+ constraintName: "FK_ORDER",
+ columns: ["org_id", "tenant_id"],
+ targetColumns: ["id_org", "id_tenant"],
+ targetSchema: "PUBLIC",
+ targetTable: "TENANT"
+ }
+ ]);
+ });
+
+ test("keeps separate constraints apart", () => {
+ const result = toForeignKeys([
+ { fk_name: "FK_A", fk_column_name: "a", pk_column_name: "x", pk_schema_name: "S", pk_table_name: "T" },
+ { fk_name: "FK_B", fk_column_name: "b", pk_column_name: "y", pk_schema_name: "S", pk_table_name: "U" }
+ ]);
+ expect(result.map((fk) => fk.constraintName)).toEqual(["FK_A", "FK_B"]);
+ });
+});
+
+describe("toColumns", () => {
+ test("maps nullability and identity generation", () => {
+ expect(
+ toColumns([
+ { name: "id", type: "NUMBER", isNullable: "NO", identityGeneration: "BY DEFAULT" },
+ { name: "note", type: "TEXT", isNullable: "YES", identityGeneration: null }
+ ])
+ ).toEqual([
+ { name: "id", type: "NUMBER", nullable: false, identityGeneration: "BY DEFAULT" },
+ { name: "note", type: "TEXT", nullable: true, identityGeneration: null }
+ ]);
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-metadata.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-metadata.ts
new file mode 100644
index 0000000000..8d1e5a38cc
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-data-explorer-metadata.ts
@@ -0,0 +1,91 @@
+import { quoteSnowflakeIdent } from "@app/services/app-connection/snowflake";
+
+// Unqualified, so it resolves against the database the session already opened
+export const SCHEMAS_QUERY = `SELECT SCHEMA_NAME AS "name"
+ FROM INFORMATION_SCHEMA.SCHEMATA
+ WHERE SCHEMA_NAME <> 'INFORMATION_SCHEMA'
+ ORDER BY SCHEMA_NAME`;
+
+export const TABLES_QUERY = `SELECT TABLE_NAME AS "name", TABLE_TYPE AS "tableType"
+ FROM INFORMATION_SCHEMA.TABLES
+ WHERE TABLE_SCHEMA = ?
+ ORDER BY TABLE_NAME`;
+
+export const COLUMNS_QUERY = `SELECT
+ COLUMN_NAME AS "name",
+ DATA_TYPE AS "type",
+ IS_NULLABLE AS "isNullable",
+ IDENTITY_GENERATION AS "identityGeneration"
+ FROM INFORMATION_SCHEMA.COLUMNS
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
+ ORDER BY ORDINAL_POSITION`;
+
+// Snowflake has no KEY_COLUMN_USAGE view, so keys come from SHOW, which takes an identifier not a bind
+export const showPrimaryKeysQuery = (schema: string, table: string) =>
+ `SHOW PRIMARY KEYS IN TABLE ${quoteSnowflakeIdent(schema)}.${quoteSnowflakeIdent(table)}`;
+
+export const showImportedKeysQuery = (schema: string, table: string) =>
+ `SHOW IMPORTED KEYS IN TABLE ${quoteSnowflakeIdent(schema)}.${quoteSnowflakeIdent(table)}`;
+
+type TShowKeyRow = Record<string, unknown>;
+
+const readCell = (row: TShowKeyRow, key: string): string => {
+ const value = row[key] ?? row[key.toUpperCase()];
+ return typeof value === "string" ? value : String(value ?? "");
+};
+
+const readSequence = (row: TShowKeyRow): number => {
+ const value = row.key_sequence ?? row.KEY_SEQUENCE;
+ return Number(value ?? 0);
+};
+
+export const toPrimaryKeys = (rows: TShowKeyRow[]): string[] =>
+ [...rows]
+ .sort((a, b) => readSequence(a) - readSequence(b))
+ .map((row) => readCell(row, "column_name"))
+ .filter(Boolean);
+
+export type TForeignKey = {
+ constraintName: string;
+ columns: string[];
+ targetSchema: string;
+ targetTable: string;
+ targetColumns: string[];
+};
+
+export const toForeignKeys = (rows: TShowKeyRow[]): TForeignKey[] => {
+ const byConstraint = new Map<string, TForeignKey>();
+
+ for (const row of [...rows].sort((a, b) => readSequence(a) - readSequence(b))) {
+ const constraintName = readCell(row, "fk_name");
+ const existing = byConstraint.get(constraintName);
+ const foreignKey = existing ?? {
+ constraintName,
+ columns: [],
+ targetSchema: readCell(row, "pk_schema_name"),
+ targetTable: readCell(row, "pk_table_name"),
+ targetColumns: []
+ };
+
+ foreignKey.columns.push(readCell(row, "fk_column_name"));
+ foreignKey.targetColumns.push(readCell(row, "pk_column_name"));
+ if (!existing) byConstraint.set(constraintName, foreignKey);
+ }
+
+ return [...byConstraint.values()];
+};
+
+export type TColumnRow = {
+ name: string;
+ type: string;
+ isNullable: string;
+ identityGeneration: string | null;
+};
+
+export const toColumns = (rows: TColumnRow[]) =>
+ rows.map((row) => ({
+ name: row.name,
+ type: row.type,
+ nullable: row.isNullable?.toUpperCase() === "YES",
+ identityGeneration: row.identityGeneration || null
+ }));
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-metadata.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-metadata.ts
new file mode 100644
index 0000000000..734b168fa2
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-metadata.ts
@@ -0,0 +1,34 @@
+import snowflake from "snowflake-sdk";
+
+import { executeSnowflakeSql } from "@app/services/app-connection/snowflake";
+
+import { type OneShotOptions } from "../pam-data-explorer-session-handler";
+import { SCHEMAS_QUERY, TABLES_QUERY } from "./pam-snowflake-data-explorer-metadata";
+import { connectThroughRelay } from "./pam-snowflake-relay-client";
+
+export const snowflakeAccountOf = (opts: OneShotOptions) => (opts.connectionDetails as { account: string }).account;
+
+const withClient = async <T>(opts: OneShotOptions, fn: (client: snowflake.Connection) => Promise<T>): Promise<T> => {
+ const client = await connectThroughRelay(opts.relayPort, snowflakeAccountOf(opts));
+ try {
+ return await fn(client);
+ } finally {
+ client.destroy(() => {});
+ }
+};
+
+export const fetchSchemasOneShot = (opts: OneShotOptions): Promise<{ name: string }[]> =>
+ withClient(opts, (client) => executeSnowflakeSql<{ name: string }>(client, SCHEMAS_QUERY));
+
+export const fetchTablesOneShot = (
+ opts: OneShotOptions,
+ schema: string
+): Promise<{ name: string; tableType: string }[]> =>
+ withClient(opts, (client) =>
+ executeSnowflakeSql<{ name: string; tableType: string }>(client, TABLES_QUERY, [schema])
+ );
+
+export const verifyReachabilityOneShot = (opts: OneShotOptions): Promise<void> =>
+ withClient(opts, async (client) => {
+ await executeSnowflakeSql(client, "SELECT 1");
+ });
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-relay-client.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-relay-client.ts
new file mode 100644
index 0000000000..26ad0edb4c
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-relay-client.ts
@@ -0,0 +1,23 @@
+import snowflake from "snowflake-sdk";
+
+import { BadRequestError } from "@app/lib/errors";
+
+// The gateway answers Snowflake's REST API on the relay port and authenticates for the session
+export const connectThroughRelay = async (relayPort: number, account: string): Promise<snowflake.Connection> => {
+ const client = snowflake.createConnection({
+ account,
+ username: "pam",
+ password: "pam",
+ accessUrl: `http://127.0.0.1:${relayPort}`,
+ application: "Infisical"
+ });
+
+ try {
+ return await client.connectAsync();
+ } catch (err) {
+ client.destroy(() => {});
+ throw new BadRequestError({
+ message: `Unable to reach Snowflake through the gateway: ${(err as Error)?.message ?? "connection failed"}`
+ });
+ }
+};
diff --git a/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-session-handler.ts b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-session-handler.ts
new file mode 100644
index 0000000000..d0fddd8bdc
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/snowflake/pam-snowflake-session-handler.ts
@@ -0,0 +1,15 @@
+import { createDataExplorerSessionHandler } from "../pam-data-explorer-session-handler";
+import { createSnowflakeConnectionController } from "./pam-snowflake-connection-controller";
+import { fetchSchemasOneShot, fetchTablesOneShot, verifyReachabilityOneShot } from "./pam-snowflake-metadata";
+
+export const handleSnowflakeSession = createDataExplorerSessionHandler({
+ dialectName: "Snowflake",
+ createController: createSnowflakeConnectionController,
+ fetchSchemas: fetchSchemasOneShot,
+ fetchTables: fetchTablesOneShot,
+ verifyReachability: verifyReachabilityOneShot,
+ extractErrorFields: (err: unknown) => {
+ const snowflakeErr = err as { message?: string; sqlState?: string };
+ return { message: snowflakeErr.message, detail: snowflakeErr.sqlState };
+ }
+});
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index dd43b886e2..a56b03f0b7 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -129,6 +129,15 @@ metadata; **gateway-injection** (`GcpServiceAccount`, `AzureCli`) proxies the cl
gateway and injects a backend-minted short-lived token so no credential reaches the client. See
`access()` / `getSessionCredentials` and the CLI `packages/pam/handlers/<provider>`.
+**Snowflake is gateway-injection with no wire protocol**: the gateway answers the part of Snowflake's REST
+API that drivers speak and runs each statement through its own client (CLI `packages/pam/handlers/snowflake/`),
+so the client never holds a Snowflake token. The web explorer points `snowflake-sdk` at the relay port
+instead of at Snowflake, which is why `OneShotOptions` carries `connectionDetails`. Two things the REST
+shape costs that are easy to get wrong: a driver cancels on a second connection, so in-flight statements
+live in a process-wide map keyed by the driver's request id rather than on the proxy; and the connection
+test compares the login's `sessionInfo` against what was asked for, because Snowflake accepts a warehouse
+or role the credential can't use and silently leaves it unset.
+
## Policies & Settings
**Policies** are governance controls on a template (MFA, reason, session duration, command-blocking),
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index e6c0590001..4adc1291d1 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -6,6 +6,7 @@ export enum PamAccountType {
OracleDB = "oracledb",
MongoDB = "mongodb",
Redis = "redis",
+ Snowflake = "snowflake",
Kubernetes = "kubernetes",
AwsIam = "aws-iam",
GcpServiceAccount = "gcp-service-account",
@@ -45,6 +46,12 @@ export enum PamSessionEndReason {
Expired = "expired"
}
+export enum PamSnowflakeAuthMethod {
+ KeyPair = "key-pair",
+ ProgrammaticAccessToken = "programmatic-access-token",
+ Password = "password"
+}
+
export enum GcpServiceAccountAuthMethod {
Impersonation = "impersonation",
StaticKey = "static-key"
diff --git a/backend/src/ee/services/pam/pam-policies.ts b/backend/src/ee/services/pam/pam-policies.ts
index c20892d90d..b09d7d7ec5 100644
--- a/backend/src/ee/services/pam/pam-policies.ts
+++ b/backend/src/ee/services/pam/pam-policies.ts
@@ -105,8 +105,13 @@ export const PAM_POLICY_DEFINITIONS: Record<PamPolicyType, TPamPolicyDefinition>
[PamPolicyType.CommandBlocking]: {
label: "Command Blocking",
description: "Matching commands will be rejected (one regex per line).",
- appliesTo: [PamAccountType.SSH],
- schema: patternsStringSchema()
+ appliesTo: [PamAccountType.SSH, PamAccountType.Snowflake],
+ schema: patternsStringSchema(),
+ typeOverrides: {
+ [PamAccountType.Snowflake]: {
+ description: "Matching SQL statements will be rejected (one regex per line)."
+ }
+ }
}
};
diff --git a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt
index 36c743b875..e239986e42 100644
--- a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt
+++ b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt
@@ -623,3 +623,7 @@ iss
# --- Surfaced by the code-signing pages ---
# Vale strips a trailing `'s`, so the possessive needs no separate entry.
MSBuild
+
+# --- Surfaced by the PAM Snowflake page ---
+DBeaver
+snowsql
diff --git a/docs/docs.json b/docs/docs.json
index 0d84571d62..ac2c4ae345 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -700,6 +700,7 @@
"documentation/platform/pam/accounts/mssql",
"documentation/platform/pam/accounts/mongodb",
"documentation/platform/pam/accounts/redis",
+ "documentation/platform/pam/accounts/snowflake",
"documentation/platform/pam/accounts/ssh",
"documentation/platform/pam/accounts/kubernetes",
"documentation/platform/pam/accounts/aws-iam",
diff --git a/docs/documentation/platform/pam/accounts/overview.mdx b/docs/documentation/platform/pam/accounts/overview.mdx
index 811cfa0ee1..bd4a79cb62 100644
--- a/docs/documentation/platform/pam/accounts/overview.mdx
+++ b/docs/documentation/platform/pam/accounts/overview.mdx
@@ -19,6 +19,7 @@ PAM supports the following account types:
| [**MS SQL**](/documentation/platform/pam/accounts/mssql) | Microsoft SQL Server | |
| [**MongoDB**](/documentation/platform/pam/accounts/mongodb) | MongoDB databases | |
| [**Redis**](/documentation/platform/pam/accounts/redis) | Redis databases | ✓ |
+| [**Snowflake**](/documentation/platform/pam/accounts/snowflake) | Snowflake accounts | ✓ |
| [**SSH**](/documentation/platform/pam/accounts/ssh) | Linux/Unix servers | ✓ |
| [**Kubernetes**](/documentation/platform/pam/accounts/kubernetes) | Kubernetes clusters | |
| [**AWS IAM**](/documentation/platform/pam/accounts/aws-iam) | AWS IAM roles | ✓ |
diff --git a/docs/documentation/platform/pam/accounts/snowflake.mdx b/docs/documentation/platform/pam/accounts/snowflake.mdx
new file mode 100644
index 0000000000..1af50e091a
--- /dev/null
+++ b/docs/documentation/platform/pam/accounts/snowflake.mdx
@@ -0,0 +1,145 @@
+---
+title: "Snowflake accounts"
+sidebarTitle: "Snowflake"
+description: "Add and connect to Snowflake accounts."
+---
+
+Snowflake accounts let you manage access to a Snowflake database. Users connect through Web Access or the CLI, and every statement they run is recorded in the [session](/documentation/platform/pam/sessions/overview).
+
+Snowflake has no database wire protocol, so the [gateway](/documentation/platform/gateways/overview) answers the REST API its drivers speak and runs each statement itself. The credential never reaches the client, and because the gateway sits in your own network, an account behind AWS PrivateLink or a network policy is reachable like any other target.
+
+## Prerequisites
+
+- A Snowflake user for Infisical to connect as.
+- A warehouse the user's role can use. Snowflake bills for the compute a session's queries consume.
+- A [gateway](/documentation/platform/gateways/overview) that can reach your Snowflake account. Snowflake returns large results from cloud object storage rather than from the account host, so a gateway behind an egress allowlist needs that storage reachable too.
+- A key pair or a programmatic access token for that user. Snowflake blocks single-factor password sign-in for human users, so password authentication only works for a service user whose account policy still permits it.
+
+## Creating an account
+
+<Steps>
+ <Step title="Start adding an account">
+ Go to **Privileged Access Management → Accounts** and select **Add Account**.
+ </Step>
+ <Step title="Select a folder and template">
+ Choose which [folder](/documentation/platform/pam/folders/overview) to add the account to, then select a Snowflake [template](/documentation/platform/pam/templates/overview).
+ </Step>
+ <Step title="Enter connection details">
+ | Field | Description |
+ |-------|-------------|
+ | **Name** | A descriptive name (e.g., `analytics-prod`) |
+ | **Account Identifier** | The account identifier from your Snowflake URL, without the `snowflakecomputing.com` suffix (e.g., `myorg-myaccount`) |
+ | **Warehouse** | The warehouse sessions run their queries on. Leave blank to use the user's default warehouse |
+ | **Database** | The database sessions open. Web Access lists the schemas and tables inside it |
+ | **Schema** | The schema sessions open by default. Optional |
+ | **Role** | The role sessions activate. Leave blank to use the user's default role |
+ </Step>
+ <Step title="Enter credentials">
+ | Field | Description |
+ |-------|-------------|
+ | **Auth Method** | Key Pair, Programmatic Access Token, or Password |
+ | **Username** | The Snowflake login name |
+ | **Private Key** | PKCS#8 private key, for key pair authentication |
+ | **Private Key Passphrase** | Passphrase for an encrypted private key. Optional |
+ | **Programmatic Access Token** | The token value, for programmatic access token authentication |
+ | **Password** | The user's password, for password authentication |
+ </Step>
+ <Step title="Save">
+ Select **Create**. Infisical signs in to Snowflake and runs one statement to confirm the credential and the warehouse work before saving the account.
+ </Step>
+</Steps>
+
+## Key pair authentication
+
+Generate a key pair, then assign the public key to the Snowflake user:
+
+```bash
+openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out infisical_key.p8 -nocrypt
+openssl rsa -in infisical_key.p8 -pubout -out infisical_key.pub
+```
+
+```sql
+ALTER USER pam_service SET RSA_PUBLIC_KEY = '<contents of infisical_key.pub, without the header and footer lines>';
+```
+
+Paste the contents of `infisical_key.p8` into **Private Key**, then delete your local copy. Snowflake keeps two key slots per user, `RSA_PUBLIC_KEY` and `RSA_PUBLIC_KEY_2`, so you can add a new key before removing the old one.
+
+To rotate the key pair on a schedule instead of by hand, use a [Snowflake user key pair rotation](/documentation/platform/secret-rotation/snowflake-user-key-pair).
+
+## Programmatic access token authentication
+
+Snowflake only issues a token to a user who is subject to a network policy, and only when the token is restricted to a role:
+
+```sql
+ALTER USER pam_service SET NETWORK_POLICY = <your network policy>;
+ALTER USER pam_service ADD PROGRAMMATIC ACCESS TOKEN infisical
+ ROLE_RESTRICTION = 'PAM_READER' DAYS_TO_EXPIRY = 90;
+```
+
+The token value is shown once. Paste it into **Programmatic Access Token**, and give the same role in **Role** so the session activates the one the token allows.
+
+## Permissions
+
+What a session can do comes from the role the account activates, so grant that role only what the people using the account need. At minimum it needs `USAGE` on the warehouse and the database, and `USAGE` on each schema whose tables should appear in Web Access:
+
+```sql
+GRANT USAGE ON WAREHOUSE analytics_wh TO ROLE pam_reader;
+GRANT USAGE ON DATABASE analytics TO ROLE pam_reader;
+GRANT USAGE ON SCHEMA analytics.public TO ROLE pam_reader;
+GRANT SELECT ON ALL TABLES IN SCHEMA analytics.public TO ROLE pam_reader;
+```
+
+## Connecting
+
+<Tabs>
+ <Tab title="Web Access">
+ Web Access provides a browser-based interface with two tools:
+
+ - **Data Explorer** — browse tables, view data, filter and sort, edit rows, export to CSV/JSON
+ - **SQL Editor** — write and run SQL queries, use transactions
+
+ To connect:
+
+ 1. Go to **Privileged Access Management → Accounts**
+ 2. Find the account and select the rocket icon (or select **Launch Session** from the menu)
+ 3. Select **Connect in Browser**
+
+ </Tab>
+ <Tab title="CLI">
+ The CLI starts a local proxy that snowsql, DBeaver, and the Snowflake drivers connect to. It speaks plain HTTP on `127.0.0.1`, so connect with `ssl=off` and no certificate to trust. The username and password are ignored, since the gateway authenticates for you.
+
+ ```bash
+ infisical pam access analytics/snowflake-prod
+ ```
+
+ The command prints the port and a ready-made connection string for each client.
+
+ **Flags:**
+ - `--port <port>` — use a specific local port (otherwise one is assigned automatically)
+ - `--reason <reason>` — provide an access reason (if required by template)
+
+ </Tab>
+</Tabs>
+
+Results are capped at 10,000 rows per statement, and the Data Explorer shows the first 1,000 rows of a result and tells you when there are more.
+
+<Note>
+ Snowflake doesn't enforce primary keys, but the Data Explorer still needs one declared on a table before it can edit that table's rows. A table without one is read-only in the grid, and editable from the SQL editor.
+</Note>
+
+## Recording
+
+Every statement a session runs is recorded, along with the outcome of each one, and appears under **Session Logs** on the session. Web Access and the CLI both reach Snowflake through the gateway, so recording works the same for either. Recordings are encrypted with a per-session key and written to the storage backend the [template](/documentation/platform/pam/templates/overview) selects, the same as any other account type.
+
+The template's **Command Blocking** policy applies to Snowflake as well: a statement matching one of its patterns is rejected before it reaches Snowflake, and the rejection is recorded. **Session Log Masking** patterns are applied to the recording before it's written.
+
+## Next steps
+
+<CardGroup cols={2}>
+ <Card title="Sessions" icon="display" href="/documentation/platform/pam/sessions/overview">
+ View and manage sessions.
+ </Card>
+ <Card title="Access requests" icon="user-check" href="/documentation/platform/pam/access-requests/overview">
+ Require approval before a session starts.
+ </Card>
+</CardGroup>
diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts
index 8ed42f3b83..d48e0615b8 100644
--- a/frontend/src/hooks/api/pam/enums.ts
+++ b/frontend/src/hooks/api/pam/enums.ts
@@ -6,6 +6,7 @@ export enum PamAccountType {
OracleDB = "oracledb",
MongoDB = "mongodb",
Redis = "redis",
+ Snowflake = "snowflake",
Kubernetes = "kubernetes",
AwsIam = "aws-iam",
GcpServiceAccount = "gcp-service-account",
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
index 2cc38cafc8..2d6bd0d07f 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
@@ -132,7 +132,8 @@ const PageContent = () => {
{({ reason, mfaSessionId }) => {
if (
account.accountType === PamAccountType.Postgres ||
- account.accountType === PamAccountType.MySQL
+ account.accountType === PamAccountType.MySQL ||
+ account.accountType === PamAccountType.Snowflake
) {
return <PamDataExplorerPage reason={reason} mfaSessionId={mfaSessionId} />;
}
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
index 80f8252af0..fd14d13d27 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
@@ -25,6 +25,11 @@ import type { SqlDialect } from "./sql-generation";
import { useDataExplorerSession } from "./use-data-explorer-session";
import { useQueryTabs } from "./use-query-tabs";
+const DIALECT_BY_ACCOUNT_TYPE: Partial<Record<PamAccountType, SqlDialect>> = {
+ [PamAccountType.MySQL]: "mysql",
+ [PamAccountType.Snowflake]: "snowflake"
+};
+
type Props = {
reason?: string;
mfaSessionId?: string;
@@ -40,11 +45,18 @@ export const PamDataExplorerPage = ({ reason, mfaSessionId }: Props = {}) => {
const { data: account } = useGetPamAccountById(accountId);
- const dialect: SqlDialect = account?.accountType === PamAccountType.MySQL ? "mysql" : "postgres";
- const defaultSchema =
- dialect === "mysql"
- ? ((account?.connectionDetails as { database?: string })?.database ?? "")
- : "public";
+ const dialect: SqlDialect =
+ (account?.accountType && DIALECT_BY_ACCOUNT_TYPE[account.accountType]) ?? "postgres";
+ const connectionDetails = account?.connectionDetails as { database?: string; schema?: string };
+
+ let defaultSchema: string;
+ if (dialect === "mysql") {
+ defaultSchema = connectionDetails?.database ?? "";
+ } else if (dialect === "snowflake") {
+ defaultSchema = connectionDetails?.schema ?? "PUBLIC";
+ } else {
+ defaultSchema = "public";
+ }
// Sidebar-only view state. Switching schemas in the sidebar does not alter
// open tabs — tabs are bound to their own (schema, table) at open time.
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
index 6b8f123950..17ae029ac9 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
+++ b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
@@ -1,7 +1,7 @@
// Client-side SQL generation for the Data Explorer.
// All identifiers are properly quoted to prevent SQL injection.
-export type SqlDialect = "postgres" | "mysql";
+export type SqlDialect = "postgres" | "mysql" | "snowflake";
function quoteIdent(name: string, dialect: SqlDialect = "postgres"): string {
if (dialect === "mysql") return `\`${name.replace(/`/g, "``")}\``;
@@ -20,7 +20,9 @@ function quoteLiteral(value: unknown, dialect: SqlDialect = "postgres"): string
return `$$${str}$$`;
}
const escaped =
- dialect === "mysql" ? str.replace(/\\/g, "\\\\").replace(/'/g, "''") : str.replace(/'/g, "''");
+ dialect === "postgres"
+ ? str.replace(/'/g, "''")
+ : str.replace(/\\/g, "\\\\").replace(/'/g, "''");
return `'${escaped}'`;
}
@@ -143,11 +145,14 @@ export function buildInsertQuery(params: {
const entries = Object.entries(row).filter(([, v]) => v !== undefined && v !== "");
if (entries.length === 0) {
if (dialect === "mysql") return `INSERT INTO ${tableName} () VALUES ()`;
+ if (dialect === "snowflake") {
+ throw new Error("Snowflake cannot insert a row with no values. Fill in at least one column.");
+ }
return `INSERT INTO ${tableName} DEFAULT VALUES RETURNING *`;
}
const columns = entries.map(([k]) => quoteIdent(k, dialect)).join(", ");
const values = entries.map(([, v]) => quoteLiteral(v, dialect)).join(", ");
- if (dialect === "mysql") return `INSERT INTO ${tableName} (${columns}) VALUES (${values})`;
+ if (dialect !== "postgres") return `INSERT INTO ${tableName} (${columns}) VALUES (${values})`;
return `INSERT INTO ${tableName} (${columns}) VALUES (${values}) RETURNING *`;
}
@@ -169,7 +174,7 @@ export function buildUpdateQuery(params: {
const whereClauses = Object.entries(primaryKeyMatch)
.map(([col, val]) => `${quoteIdent(col, dialect)} = ${quoteLiteral(val, dialect)}`)
.join(" AND ");
- if (dialect === "mysql") return `UPDATE ${tableName} SET ${setClauses} WHERE ${whereClauses}`;
+ if (dialect !== "postgres") return `UPDATE ${tableName} SET ${setClauses} WHERE ${whereClauses}`;
return `UPDATE ${tableName} SET ${setClauses} WHERE ${whereClauses} RETURNING *`;
}