Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
session rewire backend
x0322057c73ab035ef9
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 4a238b9260..de8f46f6fa 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -38,6 +38,7 @@ import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { TPamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";import { TPamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";+import { TPamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { TPitServiceFactory } from "@app/ee/services/pit/pit-service";import { TPkiAcmeServiceFactory } from "@app/ee/services/pki-acme/pki-acme-types";@@ -410,6 +411,7 @@ declare module "fastify" {pamFolder: TPamFolderServiceFactory;pamAccount: TPamAccountServiceFactory;pamMembership: TPamMembershipServiceFactory;+ pamWebAccess: TPamWebAccessServiceFactory;mfaSession: TMfaSessionServiceFactory;membershipUser: TMembershipUserServiceFactory;membershipIdentity: TMembershipIdentityServiceFactory;diff --git a/backend/src/ee/routes/v1/pam-routers/index.ts b/backend/src/ee/routes/v1/pam-routers/index.tsindex d92d52e7ea..b968b2fd98 100644--- a/backend/src/ee/routes/v1/pam-routers/index.ts+++ b/backend/src/ee/routes/v1/pam-routers/index.ts@@ -3,6 +3,7 @@ import { registerPamAccountTemplateRouter } from "./pam-account-template-router"import { registerPamFolderRouter } from "./pam-folder-router";import { registerPamMembershipRouter } from "./pam-membership-router";import { registerPamResourceRoleRouter } from "./pam-resource-role-router";+import { registerPamSessionRouter } from "./pam-session-router";export const registerPamRouters = async (server: FastifyZodProvider) => {await server.register(registerPamAccountTemplateRouter, { prefix: "/account-templates" });@@ -10,4 +11,5 @@ export const registerPamRouters = async (server: FastifyZodProvider) => {await server.register(registerPamAccountRouter, { prefix: "/accounts" });await server.register(registerPamMembershipRouter, { prefix: "/members" });await server.register(registerPamResourceRoleRouter, { prefix: "/resource-roles" });+ await server.register(registerPamSessionRouter, { prefix: "/sessions" });};diff --git a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-session-router.tsnew file mode 100644index 0000000000..83ed1dbced--- /dev/null+++ b/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts@@ -0,0 +1,176 @@+import type WebSocket from "ws";+import z from "zod";++import { UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { BadRequestError } from "@app/lib/errors";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { ActorType, AuthMode } from "@app/services/auth/auth-type";+import { TokenType } from "@app/services/auth-token/auth-token-types";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++export const registerPamSessionRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/:accountId/web-access-ticket",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "pamSessionWebAccessTicket",+ params: z.object({+ accountId: z.string().uuid()+ }),+ body: z.object({+ reason: z.string().trim().max(1000).optional()+ }),+ response: {+ 200: z.object({ ticket: z.string() })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ if (req.auth.authMode !== AuthMode.JWT) {+ throw new BadRequestError({ message: "Web access requires JWT authentication" });+ }++ const { ticket } = await server.services.pamWebAccess.issueWebSocketTicket({+ accountId: req.params.accountId,+ projectId: req.internalPamProjectId,+ orgId: req.permission.orgId,+ actor: req.permission,+ actorEmail: req.auth.user.email ?? "",+ actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),+ auditLogInfo: req.auditLogInfo,+ reason: req.body.reason+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.PamSessionStarted,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: {+ orgId: req.permission.orgId+ }+ })+ .catch(() => {});++ return { ticket };+ }+ });++ server.route({+ method: "GET",+ url: "/:accountId/web-access",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "pamSessionWebAccess",+ params: z.object({+ accountId: z.string().uuid()+ }),+ querystring: z.object({+ ticket: z.string()+ }),+ response: {+ 200: z.object({ message: z.string() })+ }+ },+ wsHandler: async (connection: WebSocket, req) => {+ const preAuthMessages: { data: Buffer; isBinary: boolean }[] = [];+ const preAuthHandler = (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {+ let buf: Buffer;+ if (Buffer.isBuffer(raw)) {+ buf = raw;+ } else if (Array.isArray(raw)) {+ buf = Buffer.concat(raw);+ } else {+ buf = Buffer.from(raw);+ }+ preAuthMessages.push({ data: buf, isBinary });+ };+ connection.on("message", preAuthHandler);++ try {+ const ticketValue = req.query.ticket;+ const separatorIndex = ticketValue.indexOf(":");+ if (separatorIndex === -1) {+ connection.off("message", preAuthHandler);+ connection.close(4001, "Invalid or expired ticket");+ return;+ }++ const userId = ticketValue.slice(0, separatorIndex);+ const tokenCode = ticketValue.slice(separatorIndex + 1);++ const tokenRecord = await server.services.authToken.validateTokenForUser({+ type: TokenType.TOKEN_PAM_WS_TICKET,+ userId,+ code: tokenCode+ });++ if (!tokenRecord?.payload) {+ connection.off("message", preAuthHandler);+ connection.close(4001, "Invalid or expired ticket");+ return;+ }++ const payload = z+ .object({+ accountId: z.string(),+ projectId: z.string(),+ orgId: z.string(),+ accountName: z.string(),+ accountType: z.string(),+ actorEmail: z.string(),+ actorName: z.string(),+ reason: z.string().nullable().optional(),+ auditLogInfo: z.object({+ ipAddress: z.string().optional(),+ userAgent: z.string().optional(),+ userAgentType: z.nativeEnum(UserAgentType).optional(),+ actor: z.object({+ type: z.nativeEnum(ActorType),+ metadata: z.record(z.unknown())+ })+ })+ })+ .parse(JSON.parse(tokenRecord.payload));++ if (payload.accountId !== req.params.accountId) {+ connection.off("message", preAuthHandler);+ connection.close(4001, "Invalid or expired ticket");+ return;+ }++ await server.services.pamWebAccess.handleWebSocketConnection({+ socket: connection,+ accountId: payload.accountId,+ projectId: payload.projectId,+ orgId: payload.orgId,+ accountName: payload.accountName,+ actorEmail: payload.actorEmail,+ actorName: payload.actorName,+ auditLogInfo: payload.auditLogInfo as Parameters<+ typeof server.services.pamWebAccess.handleWebSocketConnection+ >[0]["auditLogInfo"],+ userId,+ actorIp: req.realIp ?? "",+ actorUserAgent: req.headers["user-agent"] ?? "",+ reason: payload.reason,+ preAuthMessages,+ preAuthHandler+ });+ } catch (err) {+ connection.off("message", preAuthHandler);+ connection.close(4001, "Invalid or expired ticket");+ }+ },+ handler: async () => {+ return { message: "WebSocket upgrade required" };+ }+ });+};diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.tsnew file mode 100644index 0000000000..57047abdc6--- /dev/null+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts@@ -0,0 +1,88 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify, selectAllTableCols } from "@app/lib/knex";++import { PamSessionStatus } from "./pam-session-enums";++export type TPamSessionDALFactory = ReturnType<typeof pamSessionDALFactory>;++export const pamSessionDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamSession);++ const findById = async (id: string, tx?: Knex) => {+ const session = await (tx || db.replicaNode())(TableName.PamSession)+ .leftJoin(TableName.GatewayV2, `${TableName.GatewayV2}.id`, `${TableName.PamSession}.gatewayId`)+ .select(selectAllTableCols(TableName.PamSession))+ .select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"))+ .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))+ .where(`${TableName.PamSession}.id`, id)+ .first();++ return session;+ };++ const countActiveWebSessions = async (userId: string, projectId: string, tx?: Knex): Promise<number> => {+ const result = await (tx || db.replicaNode())(TableName.PamSession)+ .where("userId", userId)+ .where("projectId", projectId)+ .where("accessMethod", "web")+ .whereIn("status", [PamSessionStatus.Starting, PamSessionStatus.Active])+ .count("id as count")+ .first();++ return Number((result as { count?: string | number })?.count ?? 0);+ };++ const endExpiredWebSessions = async (userId: string, projectId: string, tx?: Knex): Promise<number> => {+ const now = new Date();+ const updatedCount = await (tx || db)(TableName.PamSession)+ .where("userId", userId)+ .where("projectId", projectId)+ .where("accessMethod", "web")+ .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])+ .where("expiresAt", "<", now)+ .update({ status: PamSessionStatus.Ended, endedAt: now });+ return updatedCount;+ };++ const endSessionById = async (sessionId: string, tx?: Knex) => {+ const [updated] = await (tx || db)(TableName.PamSession)+ .where("id", sessionId)+ .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])+ .update({ status: PamSessionStatus.Ended, endedAt: new Date() })+ .returning("*");+ return updated;+ };++ const activateSession = async (sessionId: string, tx?: Knex) => {+ const [updated] = await (tx || db)(TableName.PamSession)+ .where("id", sessionId)+ .where("status", PamSessionStatus.Starting)+ .update({ status: PamSessionStatus.Active, startedAt: new Date() })+ .returning("*");+ return updated;+ };++ const findByProjectId = async (projectId: string, tx?: Knex) => {+ const sessions = await (tx || db.replicaNode())(TableName.PamSession)+ .leftJoin(TableName.GatewayV2, `${TableName.GatewayV2}.id`, `${TableName.PamSession}.gatewayId`)+ .select(selectAllTableCols(TableName.PamSession))+ .select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"))+ .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))+ .where(`${TableName.PamSession}.projectId`, projectId);++ return sessions;+ };++ return {+ ...orm,+ findById,+ countActiveWebSessions,+ endExpiredWebSessions,+ endSessionById,+ activateSession,+ findByProjectId+ };+};diff --git a/backend/src/ee/services/pam-session/pam-session-enums.ts b/backend/src/ee/services/pam-session/pam-session-enums.tsnew file mode 100644index 0000000000..58879c1371--- /dev/null+++ b/backend/src/ee/services/pam-session/pam-session-enums.ts@@ -0,0 +1,6 @@+export enum PamSessionStatus {+ Starting = "starting",+ Active = "active",+ Ended = "ended",+ Terminated = "terminated"+}diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts b/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.tsnew file mode 100644index 0000000000..04335a6d7d--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts@@ -0,0 +1,282 @@+import { parse as parseSql } from "libpg-query";+import pg from "pg";+import Cursor from "pg-cursor";++import { logger } from "@app/lib/logger";++import { getTableDetailQuery } from "./pam-postgres-data-explorer-metadata";+import {+ PostgresClientMessageType,+ PostgresServerMessageType,+ type TPostgresClientMessage,+ type TPostgresCorrelatedServerMessage+} from "./pam-postgres-ws-types";++type ControllerParams = {+ relayPort: number;+ username: string;+ database: string;+ sessionId: string;+ connectionId: string;+ sendResponse: (msg: TPostgresCorrelatedServerMessage) => void;+ onUnexpectedTermination: (reason: string) => void;+};++type TTabScopedMessage = Extract<+ TPostgresClientMessage,+ {+ type: PostgresClientMessageType.GetTableDetail | PostgresClientMessageType.Query | PostgresClientMessageType.Cancel;+ }+>;++export type TPostgresConnectionController = {+ connectionId: string;+ backendPid: number | null;+ handleMessage: (msg: TTabScopedMessage) => void;+ dispose: () => void;+ isDisposing: () => boolean;+};++const pgTypes = {+ getTypeParser: (oid: number) => {+ 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"));+ }+};++export const createPostgresConnectionController = async (+ params: ControllerParams+): Promise<TPostgresConnectionController> => {+ const { relayPort, username, database, sessionId, connectionId, sendResponse, onUnexpectedTermination } = params;++ const pgClient = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: username,+ database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 30_000,+ statement_timeout: 30_000,+ types: pgTypes+ });++ await pgClient.connect();++ const { rows: pidRows } = await pgClient.query<{ pid: number }>("SELECT pg_backend_pid() AS pid");+ const backendPid = pidRows[0]?.pid ?? null;++ let isInTransaction = false;+ let disposing = false;++ const sendQueryError = async (id: string, err: unknown) => {+ const pgErr = err as { message?: string; detail?: string; hint?: string };++ try {+ await pgClient.query("ROLLBACK");+ } catch {+ // ROLLBACK fails if there was no active transaction+ }++ isInTransaction = false;++ sendResponse({+ type: PostgresServerMessageType.Error,+ id,+ connectionId,+ transactionOpen: false,+ error: pgErr.message ?? "Query execution failed",+ detail: pgErr.detail,+ hint: pgErr.hint+ });+ };++ const cancelRunningQuery = async () => {+ if (!backendPid) return;+ const cancelClient = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: username,+ database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 5_000+ });+ cancelClient.on("error", (err) => {+ logger.debug(err, `Cancel client error [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ });+ try {+ await cancelClient.connect();+ await cancelClient.query("SELECT pg_cancel_backend($1)", [backendPid]);+ } catch (err) {+ logger.debug(err, `Failed to cancel backend query [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ } finally {+ await cancelClient.end().catch(() => {});+ }+ };++ let processingPromise: Promise<void> = Promise.resolve();++ const handleMessage = (message: TTabScopedMessage) => {+ if (message.type === PostgresClientMessageType.Cancel) {+ if (disposing) return;+ void cancelRunningQuery();+ return;+ }++ processingPromise = processingPromise+ .then(async () => {+ if (disposing) return;++ switch (message.type) {+ case PostgresClientMessageType.GetTableDetail: {+ try {+ const query = getTableDetailQuery(message.schema, message.table);+ const result = await pgClient.query<{ result: string }>(query.text, query.values);+ const rawDetail = result.rows[0]?.result;+ if (!rawDetail) {+ sendResponse({+ type: PostgresServerMessageType.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: PostgresServerMessageType.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 PostgresClientMessageType.Query: {+ try {+ const startTime = performance.now();+ const MAX_ROWS = 1000;++ // 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).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 executionTimeMs = Math.round(performance.now() - startTime);+ sendResponse({+ type: PostgresServerMessageType.QueryResult,+ id: message.id,+ connectionId,+ rows: lastRows,+ 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 Postgres message [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ });+ };++ pgClient.on("error", (err) => {+ if (disposing) return;+ logger.error(err, `Tab connection error [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ disposing = true;+ onUnexpectedTermination(err.message || "Database connection error");+ });++ pgClient.on("end", () => {+ if (disposing) return;+ disposing = true;+ onUnexpectedTermination("Database connection ended");+ });++ const dispose = () => {+ if (disposing) return;+ disposing = true;+ void pgClient.end().catch((err) => {+ logger.debug(err, `Error closing pg client [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ });+ };++ return {+ connectionId,+ backendPid,+ handleMessage,+ dispose,+ isDisposing: () => disposing+ };+};diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.tsnew file mode 100644index 0000000000..745946b01d--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts@@ -0,0 +1,102 @@+export const getSchemasQuery = () => ({+ text: `+ SELECT nspname AS name+ FROM pg_namespace+ WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')+ AND nspname NOT LIKE 'pg_temp_%'+ AND nspname NOT LIKE 'pg_toast_temp_%'+ ORDER BY nspname+ `,+ values: [] as string[]+});++export const getTablesQuery = (schema: string) => ({+ text: `+ SELECT+ c.relname AS name,+ CASE c.relkind+ WHEN 'r' THEN 'table'+ WHEN 'v' THEN 'view'+ WHEN 'm' THEN 'materialized_view'+ WHEN 'f' THEN 'foreign_table'+ WHEN 'p' THEN 'partitioned_table'+ ELSE 'other'+ END AS "tableType"+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1+ AND c.relkind IN ('r', 'v', 'm', 'f', 'p')+ ORDER BY c.relname+ `,+ values: [schema]+});++export const getTableDetailQuery = (schema: string, table: string) => ({+ text: `+ WITH target AS (+ SELECT c.oid AS table_oid+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1 AND c.relname = $2+ ),+ cols AS (+ SELECT json_agg(+ json_build_object(+ 'name', a.attname,+ 'type', CASE WHEN a.attndims > 0 OR t.typelem != 0 AND t.typlen = -1+ THEN (SELECT bt.typname FROM pg_type bt WHERE bt.oid = t.typelem) || '[]'+ ELSE t.typname END,+ 'nullable', NOT a.attnotnull,+ 'identityGeneration', CASE a.attidentity+ WHEN 'a' THEN 'ALWAYS'+ WHEN 'd' THEN 'BY DEFAULT'+ ELSE null END+ ) ORDER BY a.attnum+ ) AS data+ FROM pg_attribute a+ JOIN target ON a.attrelid = target.table_oid+ JOIN pg_type t ON t.oid = a.atttypid+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum+ WHERE a.attnum > 0 AND NOT a.attisdropped+ ),+ pks AS (+ SELECT json_agg(a.attname ORDER BY arr.pos) AS data+ FROM pg_constraint con+ JOIN target ON con.conrelid = target.table_oid+ CROSS JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS arr(attnum, pos)+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = arr.attnum+ WHERE con.contype = 'p'+ ),+ fks AS (+ SELECT json_agg(+ json_build_object(+ 'constraintName', con.conname,+ 'columns', (+ SELECT json_agg(a.attname ORDER BY arr.pos)+ FROM unnest(con.conkey) WITH ORDINALITY AS arr(attnum, pos)+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = arr.attnum+ ),+ 'targetSchema', tn.nspname,+ 'targetTable', tc.relname,+ 'targetColumns', (+ SELECT json_agg(a.attname ORDER BY arr.pos)+ FROM unnest(con.confkey) WITH ORDINALITY AS arr(attnum, pos)+ JOIN pg_attribute a ON a.attrelid = con.confrelid AND a.attnum = arr.attnum+ )+ )+ ) AS data+ FROM pg_constraint con+ JOIN target ON con.conrelid = target.table_oid+ JOIN pg_class tc ON tc.oid = con.confrelid+ JOIN pg_namespace tn ON tn.oid = tc.relnamespace+ WHERE con.contype = 'f'+ )+ SELECT json_build_object(+ 'columns', COALESCE(cols.data, '[]'::json),+ 'primaryKeys', COALESCE(pks.data, '[]'::json),+ 'foreignKeys', COALESCE(fks.data, '[]'::json)+ ) AS result+ FROM cols, pks, fks+ `,+ values: [schema, table]+});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts b/backend/src/ee/services/pam-web-access/pam-postgres-metadata.tsnew file mode 100644index 0000000000..fd5e603250--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts@@ -0,0 +1,60 @@+import pg from "pg";++import { logger } from "@app/lib/logger";++import { getSchemasQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";++type OneShotOptions = {+ relayPort: number;+ username: string;+ database: string;+};++const buildClient = ({ relayPort, username, database }: OneShotOptions): pg.Client => {+ const client = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: username,+ database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 10_000,+ statement_timeout: 30_000+ });+ client.on("error", (err) => {+ logger.debug(err, "one-shot pg client error");+ });+ return client;+};++const withClient = async <T>(opts: OneShotOptions, fn: (client: pg.Client) => Promise<T>): Promise<T> => {+ const client = buildClient(opts);+ await client.connect();+ try {+ return await fn(client);+ } finally {+ await client.end().catch(() => {});+ }+};++export const fetchSchemasOneShot = (opts: OneShotOptions): Promise<{ name: string }[]> =>+ withClient(opts, async (client) => {+ const query = getSchemasQuery();+ const result = await client.query<{ name: string }>(query.text, query.values);+ return result.rows;+ });++export const fetchTablesOneShot = (+ opts: OneShotOptions,+ schema: string+): Promise<{ name: string; tableType: string }[]> =>+ withClient(opts, async (client) => {+ const query = getTablesQuery(schema);+ const result = await client.query<{ name: string; tableType: string }>(query.text, query.values);+ return result.rows;+ });++export const verifyReachabilityOneShot = (opts: OneShotOptions): Promise<void> =>+ withClient(opts, async (client) => {+ await client.query("SELECT 1");+ });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.tsnew file mode 100644index 0000000000..fb4d98c93d--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts@@ -0,0 +1,252 @@+import crypto from "crypto";++import { PamAccountType } from "@app/ee/services/pam/pam-enums";+import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";+import { logger } from "@app/lib/logger";++import {+ createPostgresConnectionController,+ type TPostgresConnectionController+} from "./pam-postgres-connection-controller";+import { fetchSchemasOneShot, fetchTablesOneShot, verifyReachabilityOneShot } from "./pam-postgres-metadata";+import {+ PostgresClientMessageSchema,+ PostgresClientMessageType,+ PostgresServerMessageType,+ type TPostgresCorrelatedServerMessage+} from "./pam-postgres-ws-types";+import { registerSessionHandler } from "./pam-session-handler-registry";+import { parseClientMessage } from "./pam-web-access-fns";+import {+ SessionEndReason,+ TerminalServerMessageType,+ TSessionContext,+ TSessionHandlerResult+} from "./pam-web-access-types";++const MAX_CONNECTIONS_PER_WS = 20;++const toPgErrorFields = (err: unknown) => {+ const pgErr = err as { message?: string; detail?: string; hint?: string };+ return { message: pgErr.message, detail: pgErr.detail, hint: pgErr.hint };+};++const handlePostgresSession = async (+ ctx: TSessionContext,+ params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }+): Promise<TSessionHandlerResult> => {+ const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, onCleanup } = ctx;+ const connectionDetails = params.connectionDetails as { host: string; port: number; database: string };+ const credentials = params.credentials as { username: string; password: string };++ const oneShotOpts = {+ relayPort,+ username: credentials.username,+ database: connectionDetails.database+ };++ await verifyReachabilityOneShot(oneShotOpts);++ sendMessage({+ type: TerminalServerMessageType.Ready,+ data: `Connected to ${resourceName} (${connectionDetails.database}) as ${credentials.username}\n\n`+ });++ logger.info(`Postgres web access session established [sessionId=${sessionId}]`);++ const sendResponse = (msg: TPostgresCorrelatedServerMessage) => {+ try {+ if (socket.readyState === socket.OPEN) {+ socket.send(JSON.stringify(msg));+ }+ } catch (err) {+ logger.error(err, `Failed to send WebSocket message [sessionId=${sessionId}]`);+ }+ };++ const controllers = new Map<string, TPostgresConnectionController | null>();+ let metadataPromise: Promise<void> = Promise.resolve();++ const openTabConnection = async (requestId: string) => {+ if (controllers.size >= MAX_CONNECTIONS_PER_WS) {+ sendResponse({+ type: PostgresServerMessageType.ConnectionOpenFailed,+ id: requestId,+ error: `Maximum ${MAX_CONNECTIONS_PER_WS} connections per session reached`+ });+ return;+ }++ const connectionId = crypto.randomUUID();+ controllers.set(connectionId, null);+ try {+ const controller = await createPostgresConnectionController({+ relayPort,+ username: credentials.username,+ database: connectionDetails.database,+ sessionId,+ connectionId,+ sendResponse,+ onUnexpectedTermination: (reason) => {+ if (!controllers.has(connectionId)) return;+ controllers.delete(connectionId);+ sendResponse({+ type: PostgresServerMessageType.ConnectionClosed,+ connectionId,+ reason+ });+ }+ });+ if (!controllers.has(connectionId)) {+ controller.dispose();+ return;+ }+ controllers.set(connectionId, controller);+ sendResponse({+ type: PostgresServerMessageType.ConnectionOpened,+ id: requestId,+ connectionId,+ backendPid: controller.backendPid+ });+ } catch (err) {+ controllers.delete(connectionId);+ const msg = err instanceof Error ? err.message : "Failed to open connection";+ logger.error(err, `Failed to open tab connection [sessionId=${sessionId}]`);+ sendResponse({+ type: PostgresServerMessageType.ConnectionOpenFailed,+ id: requestId,+ error: msg+ });+ }+ };++ const queueMetadata = <T>(+ requestId: string,+ fetcher: () => Promise<T>,+ onSuccess: (rows: T) => TPostgresCorrelatedServerMessage,+ fallbackError: string+ ) => {+ metadataPromise = metadataPromise+ .then(async () => {+ try {+ const rows = await fetcher();+ sendResponse(onSuccess(rows));+ } catch (err) {+ const { message: errMsg, detail, hint } = toPgErrorFields(err);+ sendResponse({+ type: PostgresServerMessageType.Error,+ id: requestId,+ error: errMsg ?? fallbackError,+ detail,+ hint+ });+ }+ })+ .catch(() => {});+ };++ socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {+ const message = parseClientMessage(rawData, PostgresClientMessageSchema);+ if (!message) return;++ switch (message.type) {+ case PostgresClientMessageType.Control: {+ if (message.data === "quit") {+ sendSessionEnd(SessionEndReason.UserQuit);+ onCleanup();+ socket.close();+ }+ break;+ }++ case PostgresClientMessageType.OpenConnection: {+ void openTabConnection(message.id);+ break;+ }++ case PostgresClientMessageType.CloseConnection: {+ const controller = controllers.get(message.connectionId);+ if (!controller) return;+ controllers.delete(message.connectionId);+ controller.dispose();+ break;+ }++ case PostgresClientMessageType.Cancel: {+ const controller = controllers.get(message.connectionId);+ if (!controller || controller.isDisposing()) {+ logger.debug(+ `Cancel on missing/disposing connection [sessionId=${sessionId}] [connectionId=${message.connectionId}]`+ );+ return;+ }+ controller.handleMessage(message);+ break;+ }++ case PostgresClientMessageType.GetSchemas: {+ queueMetadata(+ message.id,+ () => fetchSchemasOneShot(oneShotOpts),+ (rows) => ({ type: PostgresServerMessageType.Schemas, id: message.id, data: rows }),+ "Failed to fetch schemas"+ );+ break;+ }++ case PostgresClientMessageType.GetTables: {+ queueMetadata(+ message.id,+ () => fetchTablesOneShot(oneShotOpts, message.schema),+ (rows) => ({ type: PostgresServerMessageType.Tables, id: message.id, data: rows }),+ "Failed to fetch tables"+ );+ break;+ }++ case PostgresClientMessageType.GetTableDetail:+ case PostgresClientMessageType.Query: {+ const controller = controllers.get(message.connectionId);+ if (!controller || controller.isDisposing()) {+ sendResponse({+ type: PostgresServerMessageType.Error,+ id: message.id,+ connectionId: message.connectionId,+ error: "Connection not found"+ });+ return;+ }+ controller.handleMessage(message);+ break;+ }++ case PostgresClientMessageType.Activity: {+ break;+ }++ default:+ break;+ }+ });++ return {+ cleanup: async () => {+ const snapshot = Array.from(controllers.values());+ controllers.clear();+ for (const controller of snapshot) {+ if (controller) {+ try {+ controller.dispose();+ } catch (err) {+ logger.debug(err, `Error disposing controller [sessionId=${sessionId}]`);+ }+ }+ }+ }+ };+};++registerSessionHandler(PamAccountType.Postgres, {+ gatewayResourceType: PamResource.Postgres,+ handler: handlePostgresSession+});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.tsnew file mode 100644index 0000000000..878ddddb2d--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts@@ -0,0 +1,164 @@+import { z } from "zod";++export enum PostgresClientMessageType {+ Control = "control",+ GetSchemas = "get-schemas",+ GetTables = "get-tables",+ GetTableDetail = "get-table-detail",+ Query = "query",+ Cancel = "cancel",+ OpenConnection = "open-connection",+ CloseConnection = "close-connection",+ Activity = "activity"+}++export enum PostgresServerMessageType {+ Schemas = "schemas",+ Tables = "tables",+ TableDetail = "table-detail",+ QueryResult = "query-result",+ Error = "error",+ ConnectionOpened = "connection-opened",+ ConnectionOpenFailed = "connection-open-failed",+ ConnectionClosed = "connection-closed"+}++const CorrelatedBaseSchema = z.object({ id: z.string().uuid() });+const TabScopedBaseSchema = CorrelatedBaseSchema.extend({ connectionId: z.string().uuid() });++const ControlSchema = z.object({ type: z.literal(PostgresClientMessageType.Control), data: z.string() });++const GetSchemasRequestSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.GetSchemas)+});++const GetTablesRequestSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.GetTables),+ schema: z.string()+});++const GetTableDetailRequestSchema = TabScopedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.GetTableDetail),+ schema: z.string(),+ table: z.string()+});++const QueryRequestSchema = TabScopedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.Query),+ sql: z.string().max(50 * 1024)+});++const CancelSchema = z.object({+ type: z.literal(PostgresClientMessageType.Cancel),+ connectionId: z.string().uuid()+});++const OpenConnectionSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.OpenConnection)+});++const CloseConnectionSchema = z.object({+ type: z.literal(PostgresClientMessageType.CloseConnection),+ connectionId: z.string().uuid()+});++const ActivitySchema = z.object({+ type: z.literal(PostgresClientMessageType.Activity)+});++export const PostgresClientMessageSchema = z.discriminatedUnion("type", [+ ControlSchema,+ GetSchemasRequestSchema,+ GetTablesRequestSchema,+ GetTableDetailRequestSchema,+ QueryRequestSchema,+ CancelSchema,+ OpenConnectionSchema,+ CloseConnectionSchema,+ ActivitySchema+]);++export type TPostgresClientMessage = z.infer<typeof PostgresClientMessageSchema>;++const SchemasResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.Schemas),+ data: z.array(z.object({ name: z.string() }))+});++const TablesResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.Tables),+ data: z.array(z.object({ name: z.string(), tableType: z.string() }))+});++const TableDetailResponseSchema = TabScopedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.TableDetail),+ transactionOpen: z.boolean(),+ data: z.object({+ columns: z.array(+ z.object({+ name: z.string(),+ type: z.string(),+ nullable: z.boolean(),+ identityGeneration: z.string().nullable()+ })+ ),+ primaryKeys: z.array(z.string()),+ foreignKeys: z.array(+ z.object({+ constraintName: z.string(),+ columns: z.array(z.string()),+ targetSchema: z.string(),+ targetTable: z.string(),+ targetColumns: z.array(z.string())+ })+ )+ })+});++const QueryResultResponseSchema = TabScopedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.QueryResult),+ rows: z.array(z.record(z.string(), z.unknown())),+ fields: z.array(z.object({ name: z.string() })),+ rowCount: z.number().nullable(),+ isTruncated: z.boolean(),+ transactionOpen: z.boolean(),+ command: z.string(),+ executionTimeMs: z.number()+});++const ErrorResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.Error),+ connectionId: z.string().uuid().optional(),+ transactionOpen: z.boolean().optional(),+ error: z.string(),+ detail: z.string().optional(),+ hint: z.string().optional()+});++const ConnectionOpenedResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.ConnectionOpened),+ connectionId: z.string().uuid(),+ backendPid: z.number().nullable()+});++const ConnectionOpenFailedResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.ConnectionOpenFailed),+ error: z.string()+});++const ConnectionClosedResponseSchema = z.object({+ type: z.literal(PostgresServerMessageType.ConnectionClosed),+ connectionId: z.string().uuid(),+ reason: z.string()+});++export type TPostgresCorrelatedServerMessage = z.infer<+ | typeof SchemasResponseSchema+ | typeof TablesResponseSchema+ | typeof TableDetailResponseSchema+ | typeof QueryResultResponseSchema+ | typeof ErrorResponseSchema+ | typeof ConnectionOpenedResponseSchema+ | typeof ConnectionOpenFailedResponseSchema+ | typeof ConnectionClosedResponseSchema+>;diff --git a/backend/src/ee/services/pam-web-access/pam-session-handler-registry.ts b/backend/src/ee/services/pam-web-access/pam-session-handler-registry.tsnew file mode 100644index 0000000000..bee167a029--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-session-handler-registry.ts@@ -0,0 +1,28 @@+import { PamAccountType } from "@app/ee/services/pam/pam-enums";+import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";++import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";++export type TWebAccessHandler = (+ ctx: TSessionContext,+ params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }+) => Promise<TSessionHandlerResult>;++type TSessionHandlerEntry = {+ gatewayResourceType: PamResource;+ handler: TWebAccessHandler;+};++const registry = new Map<PamAccountType, TSessionHandlerEntry>();++export const registerSessionHandler = (accountType: PamAccountType, entry: TSessionHandlerEntry) => {+ registry.set(accountType, entry);+};++export const getSessionHandler = (accountType: PamAccountType): TSessionHandlerEntry | undefined => {+ return registry.get(accountType);+};++export const isWebAccessSupported = (accountType: PamAccountType): boolean => {+ return registry.has(accountType);+};diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.tsnew file mode 100644index 0000000000..e9186588a7--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts@@ -0,0 +1,136 @@+import { Client, type ClientChannel, type ConnectConfig } from "ssh2";++import { PamAccountType } from "@app/ee/services/pam/pam-enums";+import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";+import { logger } from "@app/lib/logger";++import { registerSessionHandler } from "./pam-session-handler-registry";+import { SshClientMessageSchema, SshClientMessageType } from "./pam-ssh-ws-types";+import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";+import {+ SessionEndReason,+ TerminalServerMessageType,+ TSessionContext,+ TSessionHandlerResult+} from "./pam-web-access-types";++const handleSSHSession = async (+ ctx: TSessionContext,+ params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }+): Promise<TSessionHandlerResult> => {+ const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =+ ctx;+ const credentials = params.credentials as { username: string };++ const client = new Client();+ let stream: ClientChannel | null = null;++ const connectConfig: ConnectConfig = {+ host: "localhost",+ port: relayPort,+ username: credentials.username,+ readyTimeout: 30_000,+ authHandler: ["none"]+ };++ return new Promise((resolve, reject) => {+ client.on("ready", () => {+ client.shell({ term: "xterm-256color", rows: 24, cols: 80 }, (err, shellStream) => {+ if (err) {+ logger.error(err, "Failed to open SSH shell");+ sendSessionEnd(SessionEndReason.SetupFailed);+ client.end();+ reject(err);+ return;+ }++ stream = shellStream;++ sendMessage({+ type: TerminalServerMessageType.Ready,+ data: `Connected to ${resourceName} as ${credentials.username}\r\n`+ });++ logger.info({ sessionId }, "SSH web access session shell opened");++ shellStream.on("data", (data: Buffer) => {+ sendMessage({+ type: TerminalServerMessageType.Output,+ data: data.toString("utf-8")+ });+ });++ shellStream.stderr.on("data", (data: Buffer) => {+ sendMessage({+ type: TerminalServerMessageType.Output,+ data: data.toString("utf-8")+ });+ });++ socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {+ const message = parseClientMessage(rawData, SshClientMessageSchema);+ if (!message) return;++ if (message.type === SshClientMessageType.Input) {+ shellStream.write(message.data);+ } else if (message.type === SshClientMessageType.Resize) {+ try {+ const { rows, cols } = JSON.parse(message.data) as { rows: number; cols: number };+ shellStream.setWindow(rows, cols, 0, 0);+ } catch {+ logger.debug("Invalid resize data received");+ }+ } else if (message.type === SshClientMessageType.Control) {+ if (message.data === "quit") {+ shellStream.close();+ client.end();+ }+ }+ });++ shellStream.on("close", () => {+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));+ onCleanup();+ socket.close();+ });++ resolve({+ cleanup: async () => {+ try {+ stream?.close();+ } catch (streamErr) {+ logger.debug(streamErr, "Error closing SSH stream");+ }+ try {+ client.end();+ } catch (clientErr) {+ logger.debug(clientErr, "Error closing SSH client");+ }+ }+ });+ });+ });++ client.on("error", (err) => {+ logger.error(err, "SSH client connection error");+ if (stream) {+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));+ onCleanup();+ socket.close();+ } else {+ reject(err);+ }+ });++ client.on("end", () => {+ logger.debug({ sessionId }, "SSH client connection ended");+ });++ client.connect(connectConfig);+ });+};++registerSessionHandler(PamAccountType.SSH, {+ gatewayResourceType: PamResource.SSH,+ handler: handleSSHSession+});diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.tsnew file mode 100644index 0000000000..4015375f38--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts@@ -0,0 +1,13 @@+import { z } from "zod";++export enum SshClientMessageType {+ Input = "input",+ Control = "control",+ Resize = "resize"+}++const InputSchema = z.object({ type: z.literal(SshClientMessageType.Input), data: z.string() });+const ControlSchema = z.object({ type: z.literal(SshClientMessageType.Control), data: z.string() });+const ResizeSchema = z.object({ type: z.literal(SshClientMessageType.Resize), data: z.string() });++export const SshClientMessageSchema = z.discriminatedUnion("type", [InputSchema, ControlSchema, ResizeSchema]);diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts b/backend/src/ee/services/pam-web-access/pam-web-access-fns.tsnew file mode 100644index 0000000000..d6a842671d--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts@@ -0,0 +1,25 @@+import { SessionEndReason } from "./pam-web-access-types";++export const rawBufferToString = (rawData: Buffer | ArrayBuffer | Buffer[]): string => {+ if (Buffer.isBuffer(rawData)) return rawData.toString();+ if (Array.isArray(rawData)) return Buffer.concat(rawData).toString();+ return Buffer.from(rawData).toString();+};++export const resolveEndReason = (isNearSessionExpiry: () => boolean): SessionEndReason =>+ isNearSessionExpiry() ? SessionEndReason.SessionCompleted : SessionEndReason.ConnectionLost;++export const parseClientMessage = <T>(+ rawData: Buffer | ArrayBuffer | Buffer[],+ schema: { safeParse: (data: unknown) => { success: true; data: T } | { success: false } }+): T | null => {+ const str = rawBufferToString(rawData);+ let parsed: unknown;+ try {+ parsed = JSON.parse(str);+ } catch {+ return null;+ }+ const result = schema.safeParse(parsed);+ return result.success ? result.data : null;+};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.tsnew file mode 100644index 0000000000..7b0bb16951--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts@@ -0,0 +1,558 @@+import "./pam-postgres-session-handler";+import "./pam-ssh-session-handler";++import net from "node:net";++import { ForbiddenError } from "@casl/ability";+import type WebSocket from "ws";++import { ResourceType } from "@app/db/schemas";+import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { PamAccountType } from "@app/ee/services/pam/pam-enums";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ResourcePermissionPamResourceActions,+ ResourcePermissionSub+} from "@app/ee/services/permission/resource-permission";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { GatewayProxyProtocol } from "@app/lib/gateway/types";+import { createGatewayConnection, createRelayConnection, setupRelayServer } from "@app/lib/gateway-v2/gateway-v2";+import { logger } from "@app/lib/logger";+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";+import { TokenType } from "@app/services/auth-token/auth-token-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { TUserDALFactory } from "@app/services/user/user-dal";++import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";+import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";+import { PamSessionStatus } from "../pam-session/pam-session-enums";+import { getSessionHandler, isWebAccessSupported } from "./pam-session-handler-registry";+import {+ DEFAULT_WEB_SESSION_DURATION_MS,+ MAX_WEB_SESSIONS_PER_USER,+ SessionEndReason,+ TEarlyBufferedMsg,+ TerminalServerMessageType,+ TIssueWebSocketTicketDTO,+ TSessionContext,+ TSessionHandlerResult,+ TWebSocketServerMessage,+ WebSocketServerMessageSchema,+ WS_IDLE_TIMEOUT_MS,+ WS_PING_INTERVAL_MS+} from "./pam-web-access-types";++type TPamWebAccessServiceFactoryDep = {+ pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails">;+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;+ tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;+ pamSessionDAL: Pick<+ TPamSessionDALFactory,+ "create" | "endSessionById" | "activateSession" | "countActiveWebSessions" | "endExpiredWebSessions"+ >;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ userDAL: Pick<TUserDALFactory, "findById">;+};++export type TPamWebAccessServiceFactory = ReturnType<typeof pamWebAccessServiceFactory>;++type THandleWebSocketConnectionDTO = {+ socket: WebSocket;+ accountId: string;+ projectId: string;+ orgId: string;+ accountName: string;+ auditLogInfo: AuditLogInfo;+ userId: string;+ actorEmail: string;+ actorName: string;+ actorIp: string;+ actorUserAgent: string;+ reason: string | null | undefined;+ preAuthMessages: TEarlyBufferedMsg[];+ preAuthHandler: (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => void;+};++export const pamWebAccessServiceFactory = ({+ pamAccountDAL,+ permissionService,+ auditLogService,+ tokenService,+ pamSessionDAL,+ gatewayV2Service,+ gatewayPoolService,+ kmsService,+ userDAL+}: TPamWebAccessServiceFactoryDep) => {+ const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;+ };++ const sendMessage = (socket: WebSocket, message: TWebSocketServerMessage): void => {+ try {+ if (socket.readyState === socket.OPEN) {+ const parsed = WebSocketServerMessageSchema.parse(message);+ socket.send(JSON.stringify(parsed));+ }+ } catch (err) {+ logger.error(err, "Failed to send WebSocket message");+ }+ };++ const sendSessionEndAndClose = (socket: WebSocket, reason: SessionEndReason): void => {+ try {+ if (socket.readyState === socket.OPEN) {+ const parsed = WebSocketServerMessageSchema.parse({ type: TerminalServerMessageType.SessionEnd, reason });+ socket.send(JSON.stringify(parsed), () => {+ socket.close();+ });+ return;+ }+ } catch (err) {+ logger.error(err, "Failed to send session end message");+ }+ socket.close();+ };++ const checkLaunchPermission = async (+ projectId: string,+ accountId: string,+ folderId: string | null | undefined,+ ctx: { actorId: string; actor: ActorType; actorOrgId: string; actorAuthMethod: ActorAuthMethod }+ ) => {+ if (folderId) {+ try {+ const { permission } = await permissionService.getResourcePermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ resourceType: ResourceType.PamFolder,+ resourceId: folderId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionPamResourceActions.LaunchSessions,+ ResourcePermissionSub.PamResource+ );+ return;+ } catch {+ // folder permission failed, fall through to account-level check+ }+ }++ const { permission } = await permissionService.getResourcePermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ resourceType: ResourceType.PamAccount,+ resourceId: accountId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionPamResourceActions.LaunchSessions,+ ResourcePermissionSub.PamResource+ );+ };++ const issueWebSocketTicket = async ({+ accountId,+ projectId,+ orgId,+ actor,+ actorEmail,+ actorName,+ auditLogInfo,+ reason+ }: TIssueWebSocketTicketDTO) => {+ const account = await pamAccountDAL.findByIdWithDetails(accountId);+ if (!account || account.projectId !== projectId) {+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });+ }++ if (!isWebAccessSupported(account.accountType as PamAccountType)) {+ throw new BadRequestError({ message: "Web access is not supported for this account type" });+ }++ const trimmedReason = reason?.trim() || null;++ await checkLaunchPermission(projectId, accountId, account.folderId, {+ actorId: actor.id,+ actor: actor.type,+ actorOrgId: actor.orgId,+ actorAuthMethod: actor.authMethod+ });++ await pamSessionDAL.endExpiredWebSessions(actor.id, projectId);+ const activeCount = await pamSessionDAL.countActiveWebSessions(actor.id, projectId);+ if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {+ throw new BadRequestError({+ message: `You have reached the maximum of ${MAX_WEB_SESSIONS_PER_USER} active web access sessions. Close an existing session and try again.`+ });+ }++ const token = await tokenService.createTokenForUser({+ type: TokenType.TOKEN_PAM_WS_TICKET,+ userId: actor.id,+ payload: JSON.stringify({+ accountId,+ projectId,+ orgId,+ accountName: account.name,+ accountType: account.accountType,+ actorEmail,+ actorName,+ auditLogInfo,+ reason: trimmedReason+ })+ });++ await auditLogService.createAuditLog({+ ...auditLogInfo,+ orgId,+ projectId,+ event: {+ type: EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED,+ metadata: {+ accountId,+ resourceName: account.name,+ accountName: account.name+ }+ }+ });++ return { ticket: `${actor.id}:${token}` };+ };++ const handleWebSocketConnection = async ({+ socket,+ accountId,+ projectId,+ orgId,+ accountName,+ auditLogInfo,+ userId,+ actorEmail,+ actorName,+ actorIp,+ actorUserAgent,+ reason: accessReason,+ preAuthMessages,+ preAuthHandler+ }: THandleWebSocketConnectionDTO): Promise<void> => {+ const earlyMessages: TEarlyBufferedMsg[] = preAuthMessages;+ const releaseEarlyBuffer = () => {+ socket.off("message", preAuthHandler);+ };++ let session: { id: string } | null = null;+ let cleanedUp = false;+ let handlerResult: TSessionHandlerResult | null = null;+ let relayServer: { port: number; cleanup: () => Promise<void> } | null = null;+ let relayCerts: {+ relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };+ gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };+ relayHost: string;+ } | null = null;+ let expiryTimer: ReturnType<typeof setTimeout> | null = null;+ let pingInterval: ReturnType<typeof setInterval> | null = null;+ let idleTimer: ReturnType<typeof setTimeout> | null = null;++ const cleanup = async () => {+ if (expiryTimer) {+ clearTimeout(expiryTimer);+ expiryTimer = null;+ }+ if (pingInterval) {+ clearInterval(pingInterval);+ pingInterval = null;+ }+ if (idleTimer) {+ clearTimeout(idleTimer);+ idleTimer = null;+ }++ if (handlerResult) {+ try {+ await handlerResult.cleanup();+ } catch (err) {+ logger.debug(err, "Error in handler cleanup");+ } finally {+ handlerResult = null;+ }+ }++ if (relayServer) {+ try {+ await relayServer.cleanup();+ } catch (err) {+ logger.debug(err, "Error closing relay server");+ } finally {+ relayServer = null;+ }+ }++ if (session) {+ const sessionId = session.id;+ try {+ const updated = await pamSessionDAL.endSessionById(sessionId);+ if (updated) {+ await auditLogService.createAuditLog({+ ...auditLogInfo,+ orgId,+ projectId,+ event: {+ type: EventType.PAM_SESSION_END,+ metadata: { sessionId, accountName }+ }+ });+ }+ } catch (err) {+ logger.error(err, `Failed to end session in DB [sessionId=${sessionId}]`);+ } finally {+ session = null;+ }+ }++ if (relayCerts) {+ const certs = relayCerts;+ relayCerts = null;+ void (async () => {+ let relayConn: net.Socket | null = null;+ try {+ relayConn = await createRelayConnection({+ relayHost: certs.relayHost,+ clientCertificate: certs.relay.clientCertificate,+ clientPrivateKey: certs.relay.clientPrivateKey,+ serverCertificateChain: certs.relay.serverCertificateChain+ });+ const cancelConn = await createGatewayConnection(+ relayConn,+ certs.gateway,+ GatewayProxyProtocol.PamSessionCancellation+ );+ cancelConn.end();+ } catch (err) {+ logger.debug(err, "Session cancellation signal failed (best-effort)");+ } finally {+ relayConn?.destroy();+ }+ })();+ }++ cleanedUp = true;+ };++ try {+ const account = await pamAccountDAL.findByIdWithDetails(accountId);+ if (!account || account.projectId !== projectId) {+ throw new BadRequestError({ message: "Invalid account or project" });+ }++ const handlerEntry = getSessionHandler(account.accountType as PamAccountType);+ if (!handlerEntry) {+ throw new BadRequestError({ message: "Web access is not supported for this account type" });+ }++ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: account.gatewayId,+ gatewayPoolId: account.gatewayPoolId+ });+ if (!effectiveGatewayId) {+ throw new BadRequestError({ message: "Gateway not configured for this account" });+ }++ await pamSessionDAL.endExpiredWebSessions(userId, projectId);+ const activeCount = await pamSessionDAL.countActiveWebSessions(userId, projectId);+ if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {+ sendMessage(socket, {+ type: TerminalServerMessageType.Output,+ data: `${SessionEndReason.SessionLimitReached}\n`+ });+ sendSessionEndAndClose(socket, SessionEndReason.SessionLimitReached);+ return;+ }++ const connectionDetails = (await decrypt(projectId, account.encryptedConnectionDetails)) as {+ host: string;+ port: number;+ };+ const credentials = await decrypt(projectId, account.encryptedCredentials);++ const user = await userDAL.findById(userId);+ const sessionDurationMs = DEFAULT_WEB_SESSION_DURATION_MS;+ const expiresAt = new Date(Date.now() + sessionDurationMs);++ session = await pamSessionDAL.create({+ status: PamSessionStatus.Starting,+ accessMethod: "web",+ expiresAt,+ accountName,+ accountType: account.accountType,+ actorEmail,+ actorIp,+ actorName,+ actorUserAgent,+ projectId,+ resourceName: account.name,+ accountId: account.id,+ userId,+ gatewayId: effectiveGatewayId,+ reason: accessReason?.trim() || null,+ folderName: account.folderName,+ selectedHost: connectionDetails.host+ });++ const certs = await gatewayV2Service.getPAMConnectionDetails({+ gatewayId: effectiveGatewayId,+ sessionId: session.id,+ resourceType: handlerEntry.gatewayResourceType,+ host: connectionDetails.host,+ port: connectionDetails.port,+ duration: sessionDurationMs,+ actorMetadata: {+ id: userId,+ type: ActorType.USER,+ name: user?.email ?? ""+ }+ });++ if (!certs) {+ throw new BadRequestError({ message: "Failed to obtain gateway connection details" });+ }++ relayCerts = {+ relayHost: certs.relayHost,+ relay: certs.relay,+ gateway: certs.gateway+ };++ relayServer = await setupRelayServer({+ protocol: GatewayProxyProtocol.Pam,+ relayHost: certs.relayHost,+ relay: certs.relay,+ gateway: certs.gateway,+ longLived: true+ });++ const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;++ const boundSendMessage = (msg: TWebSocketServerMessage) => sendMessage(socket, msg);+ const boundSendSessionEnd = (reason: SessionEndReason) =>+ sendMessage(socket, { type: TerminalServerMessageType.SessionEnd, reason });+ const handlerCleanup = () => {+ if (!cleanedUp) void cleanup();+ };++ const ctx: TSessionContext = {+ socket,+ relayPort: relayServer.port,+ resourceName: account.name,+ sessionId: session.id,+ sendMessage: boundSendMessage,+ sendSessionEnd: boundSendSessionEnd,+ isNearSessionExpiry,+ onCleanup: handlerCleanup,+ earlyMessages,+ releaseEarlyBuffer+ };++ try {+ handlerResult = await handlerEntry.handler(ctx, {+ connectionDetails: connectionDetails as Record<string, unknown>,+ credentials+ });+ } finally {+ releaseEarlyBuffer();+ }++ await pamSessionDAL.activateSession(session.id);++ logger.info({ accountId, sessionId: session.id }, "Web access session established");++ await auditLogService.createAuditLog({+ ...auditLogInfo,+ orgId,+ projectId,+ event: {+ type: EventType.PAM_ACCOUNT_ACCESS,+ metadata: {+ accountId,+ resourceName: account.name,+ accountName,+ duration: expiresAt.toISOString(),+ reason: accessReason ?? undefined+ }+ }+ });++ const resetIdleTimer = () => {+ if (idleTimer) clearTimeout(idleTimer);+ idleTimer = setTimeout(() => {+ if (!cleanedUp) {+ void cleanup();+ sendSessionEndAndClose(socket, SessionEndReason.IdleTimeout);+ }+ }, WS_IDLE_TIMEOUT_MS);+ };++ resetIdleTimer();++ let isAlive = true;++ socket.on("pong", () => {+ isAlive = true;+ });++ pingInterval = setInterval(() => {+ if (!isAlive) {+ socket.terminate();+ return;+ }+ isAlive = false;+ if (socket.readyState === socket.OPEN) {+ socket.ping();+ }+ }, WS_PING_INTERVAL_MS);++ socket.on("message", () => {+ resetIdleTimer();+ });++ expiryTimer = setTimeout(() => {+ if (!cleanedUp) {+ void cleanup();+ sendSessionEndAndClose(socket, SessionEndReason.SessionCompleted);+ }+ }, sessionDurationMs);++ socket.on("close", () => {+ logger.info({ accountId, sessionId: session?.id }, "WebSocket connection closed");+ void cleanup();+ });++ socket.on("error", (err: Error) => {+ logger.error(err, "WebSocket error");+ void cleanup();+ });+ } catch (err) {+ logger.error(err, "Failed to establish web access session");+ await cleanup();+ sendSessionEndAndClose(socket, SessionEndReason.SetupFailed);+ }+ };++ return {+ issueWebSocketTicket,+ handleWebSocketConnection+ };+};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.tsnew file mode 100644index 0000000000..bfdab9f3c8--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts@@ -0,0 +1,69 @@+import type WebSocket from "ws";+import { z } from "zod";++import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";+import { ProjectServiceActor } from "@app/lib/types";++export enum SessionEndReason {+ SessionCompleted = "Session duration complete",+ UserQuit = "Goodbye",+ ConnectionLost = "Connection lost",+ SetupFailed = "Failed to establish connection",+ IdleTimeout = "Session closed due to inactivity",+ SessionLimitReached = "Maximum concurrent sessions reached"+}++export enum TerminalServerMessageType {+ Ready = "ready",+ Output = "output",+ SessionEnd = "session_end"+}++export const WebSocketServerMessageSchema = z.discriminatedUnion("type", [+ z.object({+ type: z.enum([TerminalServerMessageType.Ready, TerminalServerMessageType.Output]),+ data: z.string(),+ prompt: z.string().default("")+ }),+ z.object({+ type: z.literal(TerminalServerMessageType.SessionEnd),+ reason: z.nativeEnum(SessionEndReason)+ })+]);++export type TWebSocketServerMessage = z.input<typeof WebSocketServerMessageSchema>;++export const DEFAULT_WEB_SESSION_DURATION_MS = 60 * 60 * 1000;+export const MAX_WEB_SESSIONS_PER_USER = 5;+export const WS_PING_INTERVAL_MS = 30000;+export const WS_IDLE_TIMEOUT_MS = 10 * 60 * 1000;++export type TEarlyBufferedMsg = { data: Buffer; isBinary: boolean };++export type TSessionContext = {+ socket: WebSocket;+ relayPort: number;+ resourceName: string;+ sessionId: string;+ sendMessage: (msg: TWebSocketServerMessage) => void;+ sendSessionEnd: (reason: SessionEndReason) => void;+ isNearSessionExpiry: () => boolean;+ onCleanup: () => void;+ earlyMessages: TEarlyBufferedMsg[];+ releaseEarlyBuffer: () => void;+};++export type TSessionHandlerResult = {+ cleanup: () => Promise<void>;+};++export type TIssueWebSocketTicketDTO = {+ accountId: string;+ projectId: string;+ orgId: string;+ actor: ProjectServiceActor;+ actorEmail: string;+ actorName: string;+ auditLogInfo: AuditLogInfo;+ reason?: string;+};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 6bc627eb12..30257e543f 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -103,6 +103,8 @@ import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal"import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { pamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";import { pamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";+import { pamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";+import { pamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";import { pitServiceFactory } from "@app/ee/services/pit/pit-service";@@ -1653,6 +1655,20 @@ export const registerRoutes = async (dynamicSecretDAL});+ const pamSessionDAL = pamSessionDALFactory(db);++ const pamWebAccessService = pamWebAccessServiceFactory({+ pamAccountDAL,+ permissionService,+ auditLogService,+ tokenService,+ pamSessionDAL,+ gatewayV2Service,+ gatewayPoolService,+ kmsService,+ userDAL+ });+const secretSyncQueue = secretSyncQueueFactory({queueService,cronJob,@@ -3450,6 +3466,7 @@ export const registerRoutes = async (pamFolder: pamFolderService,pamAccount: pamAccountService,pamMembership: pamMembershipService,+ pamWebAccess: pamWebAccessService,certManagerInstance: certManagerInstanceService,certManagerExport: certManagerExportService,certificateAuthorityCrl: certificateAuthorityCrlService,