Skip to content

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

feat(pam): redis web access (#7510)

Saif Ur Rahmand18530d86f9a
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 4e4a5432b7..3e950577a8 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
@@ -14,7 +14,7 @@ import {
// These assertions exercise the Zod-introspection path (buildPamAccountTypeMetadata reads schema internals to derive field descriptors)
describe("buildPamAccountTypeMetadata", () => {
const metadata = buildPamAccountTypeMetadata(
- new Set([PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.SSH])
+ new Set([PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.SSH, PamAccountType.Redis])
);
const byType = new Map(metadata.map((m) => [m.type, m]));
@@ -119,7 +119,7 @@ describe("buildPamAccountTypeMetadata", () => {
const redis = byType.get(PamAccountType.Redis);
expect(redis).toBeDefined();
expect(redis?.name).toBe("Redis");
- expect(redis?.supportsWebAccess).toBe(false);
+ expect(redis?.supportsWebAccess).toBe(true);
expect(redis?.connectionFields.map((f) => f.key)).toEqual([
"host",
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 40440cfb8c..eccec6a269 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
@@ -4,6 +4,7 @@ import { handleMysqlSession } from "./mysql/pam-mysql-session-handler";
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 { handleSSHSession } from "./ssh/pam-ssh-session-handler";
export type TWebAccessHandler = (
@@ -25,6 +26,10 @@ export const SESSION_HANDLERS: Partial<Record<PamAccountType, TSessionHandlerEnt
gatewayAccountType: PamAccountType.MySQL,
handler: handleMysqlSession
},
+ [PamAccountType.Redis]: {
+ gatewayAccountType: PamAccountType.Redis,
+ handler: handleRedisSession
+ },
[PamAccountType.SSH]: {
gatewayAccountType: PamAccountType.SSH,
handler: handleSSHSession
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 244984138b..3e081fa9b9 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
@@ -11,7 +11,8 @@ export enum SessionEndReason {
SetupFailed = "Failed to establish connection",
IdleTimeout = "Session closed due to inactivity",
SessionLimitReached = "Maximum concurrent sessions reached",
- ApprovalRevoked = "Your approved access is no longer active"
+ ApprovalRevoked = "Your approved access is no longer active",
+ ReplyTooLarge = "The reply was too large to read safely. Use the Infisical CLI for data this size"
}
export enum TerminalServerMessageType {
diff --git a/backend/src/ee/services/pam-web-access/redis/pam-redis-formatter.test.ts b/backend/src/ee/services/pam-web-access/redis/pam-redis-formatter.test.ts
new file mode 100644
index 0000000000..d71121d891
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/redis/pam-redis-formatter.test.ts
@@ -0,0 +1,211 @@
+import { describe, expect, it } from "vitest";
+
+import { formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";
+
+describe("tokenizeRedisInput", () => {
+ it("splits simple command", () => {
+ expect(tokenizeRedisInput("SET key value")).toEqual(["SET", "key", "value"]);
+ });
+
+ it("handles double-quoted strings", () => {
+ expect(tokenizeRedisInput('SET key "hello world"')).toEqual(["SET", "key", "hello world"]);
+ });
+
+ it("handles single-quoted strings", () => {
+ expect(tokenizeRedisInput("SET key 'hello world'")).toEqual(["SET", "key", "hello world"]);
+ });
+
+ it("handles multiple quoted arguments", () => {
+ expect(tokenizeRedisInput('MSET "key one" "value one" "key two" "value two"')).toEqual([
+ "MSET",
+ "key one",
+ "value one",
+ "key two",
+ "value two"
+ ]);
+ });
+
+ it("handles single word command", () => {
+ expect(tokenizeRedisInput("PING")).toEqual(["PING"]);
+ });
+
+ it("handles extra whitespace", () => {
+ expect(tokenizeRedisInput(" SET key value ")).toEqual(["SET", "key", "value"]);
+ });
+
+ it("handles tabs", () => {
+ expect(tokenizeRedisInput("SET\tkey\tvalue")).toEqual(["SET", "key", "value"]);
+ });
+
+ it("returns empty array for empty input", () => {
+ expect(tokenizeRedisInput("")).toEqual([]);
+ expect(tokenizeRedisInput(" ")).toEqual([]);
+ });
+
+ it("handles empty quoted string", () => {
+ expect(tokenizeRedisInput('SET key ""')).toEqual(["SET", "key", ""]);
+ });
+
+ it("handles mixed quoted and unquoted", () => {
+ expect(tokenizeRedisInput('MSET key1 "value 1" key2 value2')).toEqual([
+ "MSET",
+ "key1",
+ "value 1",
+ "key2",
+ "value2"
+ ]);
+ });
+
+ it("keeps an escaped double quote inside the argument", () => {
+ expect(tokenizeRedisInput('SET key "hello\\"world"')).toEqual(["SET", "key", 'hello"world']);
+ });
+
+ it("keeps multiple escaped quotes inside one argument", () => {
+ expect(tokenizeRedisInput('LPUSH logs "a \\"quoted\\" value"')).toEqual(["LPUSH", "logs", 'a "quoted" value']);
+ });
+
+ it("keeps an escaped single quote inside a single-quoted argument", () => {
+ expect(tokenizeRedisInput("SET key 'it\\'s here'")).toEqual(["SET", "key", "it's here"]);
+ });
+
+ it("keeps an escaped backslash inside the argument", () => {
+ expect(tokenizeRedisInput('SET path "C:\\\\temp"')).toEqual(["SET", "path", "C:\\temp"]);
+ });
+
+ it("does not treat a backslash outside quotes as an escape", () => {
+ expect(tokenizeRedisInput("SET key back\\slash")).toEqual(["SET", "key", "back\\slash"]);
+ });
+});
+
+describe("formatRedisReply", () => {
+ it("formats null as (nil)", () => {
+ expect(formatRedisReply(null)).toBe("(nil)");
+ });
+
+ it("formats undefined as (nil)", () => {
+ expect(formatRedisReply(undefined)).toBe("(nil)");
+ });
+
+ it("formats integer", () => {
+ expect(formatRedisReply(42)).toBe("(integer) 42");
+ });
+
+ it("formats zero", () => {
+ expect(formatRedisReply(0)).toBe("(integer) 0");
+ });
+
+ it("formats negative integer", () => {
+ expect(formatRedisReply(-1)).toBe("(integer) -1");
+ });
+
+ it("formats string with quotes", () => {
+ expect(formatRedisReply("hello world")).toBe('"hello world"');
+ });
+
+ it("formats OK with quotes", () => {
+ expect(formatRedisReply("OK")).toBe('"OK"');
+ });
+
+ it("escapes embedded double quotes", () => {
+ expect(formatRedisReply('He said "hello"')).toBe('"He said \\"hello\\""');
+ });
+
+ it("escapes embedded backslashes", () => {
+ expect(formatRedisReply("path\\to\\file")).toBe('"path\\\\to\\\\file"');
+ });
+
+ it("formats empty array", () => {
+ expect(formatRedisReply([])).toBe("(empty array)");
+ });
+
+ it("formats simple array", () => {
+ const result = formatRedisReply(["foo", "bar", "baz"]);
+ expect(result).toBe('1) "foo"\n2) "bar"\n3) "baz"');
+ });
+
+ it("formats array with mixed types", () => {
+ const result = formatRedisReply(["key", 42, null]);
+ expect(result).toBe('1) "key"\n2) (integer) 42\n3) (nil)');
+ });
+
+ it("formats nested arrays", () => {
+ const result = formatRedisReply([["a", "b"], ["c"]]);
+ expect(result).toContain('1) 1) "a"');
+ expect(result).toContain(' 2) "b"');
+ expect(result).toContain('2) 1) "c"');
+ });
+
+ it("formats Buffer as quoted string", () => {
+ const result = formatRedisReply(Buffer.from("hello"));
+ expect(result).toBe('"hello"');
+ });
+
+ it("formats an error inside an array the way redis-cli does", () => {
+ const result = formatRedisReply(["OK", new Error("WRONGTYPE wrong kind of value"), "v"]);
+ expect(result).toBe('1) "OK"\n2) (error) WRONGTYPE wrong kind of value\n3) "v"');
+ });
+
+ it("escapes control bytes in a nested error message", () => {
+ expect(formatRedisReply([new Error("bad\u001b[2Jvalue")])).toBe("1) (error) bad\\x1b[2Jvalue");
+ });
+
+ it("formats bigint", () => {
+ expect(formatRedisReply(BigInt(999))).toBe("(integer) 999");
+ });
+
+ it("escapes terminal control bytes so xterm cannot act on them", () => {
+ expect(formatRedisReply("safe\u001b[2J\u001b[Hspoofed")).toBe('"safe\\x1b[2J\\x1b[Hspoofed"');
+ });
+
+ it("escapes carriage return, bell and null", () => {
+ expect(formatRedisReply("a\rb\u0007c\u0000d")).toBe('"a\\rb\\x07c\\x00d"');
+ });
+
+ it("escapes C1 control bytes", () => {
+ expect(formatRedisReply("a\u009bb")).toBe('"a\\x9bb"');
+ });
+
+ it("leaves normal printable text alone", () => {
+ expect(formatRedisReply("hello world 123")).toBe('"hello world 123"');
+ });
+
+ it("lets newline and tab through so multi-line replies stay readable", () => {
+ expect(formatRedisReply("line1\nline2")).toBe('"line1\nline2"');
+ expect(formatRedisReply("a\tb")).toBe('"a\tb"');
+ });
+
+ it("normalizes CRLF to a single newline", () => {
+ expect(formatRedisReply("a\r\nb")).toBe('"a\nb"');
+ });
+
+ it("escapes a lone CR, which could otherwise overwrite the line above", () => {
+ expect(formatRedisReply("a\rb")).toBe('"a\\rb"');
+ });
+
+ it("still escapes ESC and other control bytes", () => {
+ expect(formatRedisReply("a\u001b[2Jb")).toBe('"a\\x1b[2Jb"');
+ expect(formatRedisReply("a\u0007b")).toBe('"a\\x07b"');
+ expect(formatRedisReply("a\u0000b")).toBe('"a\\x00b"');
+ });
+});
+
+describe("round trip: what you type comes back the same way", () => {
+ it("translates \\n on input and keeps it as a real newline coming back", () => {
+ const [, , value] = tokenizeRedisInput('SET k "a\\nb"');
+ expect(value).toBe("a\nb");
+ expect(formatRedisReply(value)).toBe('"a\nb"');
+ });
+
+ it("translates \\t and \\xHH on input", () => {
+ expect(tokenizeRedisInput('SET k "a\\tb"')[2]).toBe("a\tb");
+ expect(tokenizeRedisInput('SET k "a\\x41b"')[2]).toBe("aAb");
+ });
+
+ it("still keeps an escaped quote literal", () => {
+ expect(tokenizeRedisInput('SET k "he said \\"hi\\""')[2]).toBe('he said "hi"');
+ });
+
+ it("single quotes only treat the quote itself as escapable", () => {
+ expect(tokenizeRedisInput("SET k 'a\\nb'")[2]).toBe("a\\nb");
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/redis/pam-redis-formatter.ts b/backend/src/ee/services/pam-web-access/redis/pam-redis-formatter.ts
new file mode 100644
index 0000000000..2c191e324e
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/redis/pam-redis-formatter.ts
@@ -0,0 +1,118 @@
+import RE2 from "re2";
+
+const escapeBackslash = new RE2(/\\/, "g");
+const escapeQuote = new RE2(/"/, "g");
+
+const crlf = new RE2(/\r\n/, "g");
+
+// all control bytes except tab and newline, which are safe to render
+// eslint-disable-next-line no-control-regex
+const controlBytes = new RE2(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/, "g");
+
+const SHORT_ESCAPES: Record<string, string> = {
+ "\n": "\\n",
+ "\r": "\\r",
+ "\t": "\\t",
+ "\b": "\\b",
+ "\f": "\\f"
+};
+
+const toEscape = (ch: string): string => SHORT_ESCAPES[ch] ?? `\\x${ch.charCodeAt(0).toString(16).padStart(2, "0")}`;
+
+export const escapeTerminalControlBytes = (str: string): string =>
+ str.replace(crlf, "\n").replace(controlBytes, toEscape);
+
+const INPUT_ESCAPES: Record<string, string> = {
+ n: "\n",
+ r: "\r",
+ t: "\t",
+ b: "\b",
+ f: "\f",
+ a: "\u0007"
+};
+
+const HEX_PAIR = new RE2(/^[0-9a-fA-F]{2}$/);
+
+const escapeRedisString = (str: string): string =>
+ escapeTerminalControlBytes(str.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"'));
+
+export const tokenizeRedisInput = (input: string): string[] => {
+ const tokens: string[] = [];
+ let current = "";
+ let inQuote: "'" | '"' | null = null;
+ let escaped = false;
+
+ for (let i = 0; i < input.length; i += 1) {
+ const ch = input[i];
+
+ if (inQuote) {
+ if (escaped) {
+ if (inQuote === "'") {
+ current += ch === "'" ? ch : `\\${ch}`;
+ } else if (ch === "x" && HEX_PAIR.test(input.slice(i + 1, i + 3))) {
+ current += String.fromCharCode(parseInt(input.slice(i + 1, i + 3), 16));
+ i += 2;
+ } else {
+ current += INPUT_ESCAPES[ch] ?? ch;
+ }
+ escaped = false;
+ } else if (ch === "\\") {
+ escaped = true;
+ } else if (ch === inQuote) {
+ tokens.push(current);
+ current = "";
+ inQuote = null;
+ } else {
+ current += ch;
+ }
+ } else if (ch === '"' || ch === "'") {
+ inQuote = ch;
+ } else if (ch === " " || ch === "\t") {
+ if (current.length > 0) {
+ tokens.push(current);
+ current = "";
+ }
+ } else {
+ current += ch;
+ }
+ }
+
+ if (current.length > 0) {
+ tokens.push(current);
+ }
+
+ return tokens;
+};
+
+export const formatRedisReply = (reply: unknown, indent: number = 0): string => {
+ const prefix = " ".repeat(indent);
+
+ if (reply === null || reply === undefined) {
+ return `${prefix}(nil)`;
+ }
+
+ if (typeof reply === "number" || typeof reply === "bigint") {
+ return `${prefix}(integer) ${reply}`;
+ }
+
+ if (typeof reply === "string") {
+ return `${prefix}"${escapeRedisString(reply)}"`;
+ }
+
+ if (Buffer.isBuffer(reply)) {
+ return `${prefix}"${escapeRedisString(reply.toString())}"`;
+ }
+
+ if (reply instanceof Error) {
+ return `${prefix}(error) ${escapeTerminalControlBytes(reply.message)}`;
+ }
+
+ if (Array.isArray(reply)) {
+ if (reply.length === 0) {
+ return `${prefix}(empty array)`;
+ }
+ return reply.map((item, i) => `${prefix}${i + 1}) ${formatRedisReply(item, indent + 3).trimStart()}`).join("\n");
+ }
+
+ return `${prefix}"${String(reply)}"`;
+};
diff --git a/backend/src/ee/services/pam-web-access/redis/pam-redis-reply-budget.test.ts b/backend/src/ee/services/pam-web-access/redis/pam-redis-reply-budget.test.ts
new file mode 100644
index 0000000000..d9b5badc8c
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/redis/pam-redis-reply-budget.test.ts
@@ -0,0 +1,169 @@
+import net from "node:net";
+
+import { Redis } from "ioredis";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createReplyBudget } from "./pam-redis-reply-budget";
+
+// answer once per command rather than once per chunk, the way a real server does
+const takeCommands = (buf: Buffer): { names: string[]; rest: Buffer } => {
+ const names: string[] = [];
+ let offset = 0;
+
+ for (;;) {
+ const headerEnd = buf.indexOf("\r\n", offset);
+ if (headerEnd < 0 || buf[offset] !== 0x2a) break;
+
+ const argc = Number.parseInt(buf.subarray(offset + 1, headerEnd).toString(), 10);
+ let cursor = headerEnd + 2;
+ let name = "";
+ let complete = true;
+
+ for (let i = 0; i < argc; i += 1) {
+ const lenEnd = buf.indexOf("\r\n", cursor);
+ if (lenEnd < 0) {
+ complete = false;
+ break;
+ }
+ const len = Number.parseInt(buf.subarray(cursor + 1, lenEnd).toString(), 10);
+ if (lenEnd + 2 + len + 2 > buf.length) {
+ complete = false;
+ break;
+ }
+ if (i === 0)
+ name = buf
+ .subarray(lenEnd + 2, lenEnd + 2 + len)
+ .toString()
+ .toLowerCase();
+ cursor = lenEnd + 2 + len + 2;
+ }
+
+ if (!complete) break;
+ names.push(name);
+ offset = cursor;
+ }
+
+ return { names, rest: buf.subarray(offset) };
+};
+
+const INFO_BODY = "# Server\r\nloading:0\r\n";
+
+const startFakeRedis = async (replyBytes: () => number) => {
+ const server = net.createServer((socket) => {
+ let pending = Buffer.alloc(0);
+
+ socket.on("data", (chunk) => {
+ pending = Buffer.concat([pending, chunk]);
+ const { names, rest } = takeCommands(pending);
+ pending = rest;
+
+ names.forEach((name) => {
+ if (name === "info") {
+ socket.write(`$${INFO_BODY.length}\r\n${INFO_BODY}\r\n`);
+ return;
+ }
+ if (name === "client") {
+ socket.write("+OK\r\n");
+ return;
+ }
+ const size = replyBytes();
+ socket.write(`$${size}\r\n${"x".repeat(size)}\r\n`);
+ });
+ });
+ socket.on("error", () => {});
+ });
+
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", resolve);
+ });
+
+ return {
+ port: (server.address() as net.AddressInfo).port,
+ close: () =>
+ new Promise<void>((resolve) => {
+ server.close(() => resolve());
+ })
+ };
+};
+
+let live: { client?: Redis; server?: { close: () => Promise<void> } } = {};
+
+const connect = async (maxBytes: number, replyBytes: () => number) => {
+ const server = await startFakeRedis(replyBytes);
+ const budget = createReplyBudget(maxBytes);
+ const client = new Redis({
+ host: "127.0.0.1",
+ port: server.port,
+ maxRetriesPerRequest: 0,
+ reconnectOnError: () => false,
+ retryStrategy: () => null
+ });
+ client.on("error", () => {});
+ budget.attach(client);
+
+ await new Promise<void>((resolve, reject) => {
+ client.once("ready", resolve);
+ client.once("error", reject);
+ });
+
+ live = { client, server };
+ return { client, budget };
+};
+
+afterEach(async () => {
+ live.client?.disconnect();
+ await live.server?.close();
+ live = {};
+});
+
+describe("createReplyBudget", () => {
+ it("lets a reply inside the budget through", async () => {
+ const { client, budget } = await connect(64 * 1024, () => 1024);
+ budget.arm();
+ expect(((await client.call("get", "k")) as string).length).toBe(1024);
+ expect(budget.exceeded()).toBe(false);
+ });
+
+ it("drops the connection when one reply passes the budget", async () => {
+ const { client, budget } = await connect(16 * 1024, () => 512 * 1024);
+ budget.arm();
+ await expect(client.call("get", "big")).rejects.toThrow();
+ expect(budget.exceeded()).toBe(true);
+ });
+
+ it("stays exceeded after arming again, so the session end can report the reason", async () => {
+ const { client, budget } = await connect(16 * 1024, () => 512 * 1024);
+ budget.arm();
+ await expect(client.call("get", "big")).rejects.toThrow();
+ budget.arm();
+ expect(budget.exceeded()).toBe(true);
+ });
+
+ it("applies per reply, so many replies never add up to a trip", async () => {
+ const { client, budget } = await connect(8 * 1024, () => 4 * 1024);
+
+ for (let i = 0; i < 20; i += 1) {
+ budget.arm();
+ // eslint-disable-next-line no-await-in-loop
+ expect(((await client.call("get", `k${i}`)) as string).length).toBe(4 * 1024);
+ }
+
+ expect(budget.exceeded()).toBe(false);
+ });
+
+ it("does not let the handshake eat the first command's budget", async () => {
+ const { client, budget } = await connect(8 * 1024, () => 6 * 1024);
+ budget.arm();
+ expect(((await client.call("get", "k")) as string).length).toBe(6 * 1024);
+ expect(budget.exceeded()).toBe(false);
+ });
+
+ it("gives each session its own counter", async () => {
+ const { client, budget: first } = await connect(16 * 1024, () => 512 * 1024);
+ first.arm();
+ await expect(client.call("get", "big")).rejects.toThrow();
+
+ expect(first.exceeded()).toBe(true);
+ expect(createReplyBudget(16 * 1024).exceeded()).toBe(false);
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/redis/pam-redis-reply-budget.ts b/backend/src/ee/services/pam-web-access/redis/pam-redis-reply-budget.ts
new file mode 100644
index 0000000000..b54a142ec4
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/redis/pam-redis-reply-budget.ts
@@ -0,0 +1,34 @@
+import { Redis } from "ioredis";
+
+export type TReplyBudget = {
+ attach: (client: Redis) => void;
+ arm: () => void;
+ exceeded: () => boolean;
+};
+
+export const createReplyBudget = (maxBytes: number): TReplyBudget => {
+ let remaining = maxBytes;
+ let exceeded = false;
+
+ return {
+ // attaching before ready would flow the socket before ioredis builds its parser, losing bytes
+ attach: (client) => {
+ client.once("ready", () => {
+ client.stream.prependListener("data", (chunk: Buffer) => {
+ if (exceeded) return;
+ remaining -= chunk.length;
+ if (remaining < 0) {
+ exceeded = true;
+ client.stream.destroy();
+ }
+ });
+ });
+ },
+
+ arm: () => {
+ remaining = maxBytes;
+ },
+
+ exceeded: () => exceeded
+ };
+};
diff --git a/backend/src/ee/services/pam-web-access/redis/pam-redis-session-handler.ts b/backend/src/ee/services/pam-web-access/redis/pam-redis-session-handler.ts
new file mode 100644
index 0000000000..79f489b5ee
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/redis/pam-redis-session-handler.ts
@@ -0,0 +1,252 @@
+import { Redis } from "ioredis";
+
+import { logger } from "@app/lib/logger";
+
+import { parseClientMessage, resolveEndReason } from "../pam-web-access-fns";
+import {
+ SessionEndReason,
+ TerminalServerMessageType,
+ TSessionContext,
+ TSessionHandlerResult
+} from "../pam-web-access-types";
+import { escapeTerminalControlBytes, formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";
+import { createReplyBudget, TReplyBudget } from "./pam-redis-reply-budget";
+import { RedisClientMessageSchema, RedisClientMessageType } from "./pam-redis-ws-types";
+
+const COMMAND_TIMEOUT_MS = 30_000;
+
+const CLEANUP_QUIT_TIMEOUT_MS = 2_000;
+
+// these put the connection into a mode ioredis cannot follow
+const BLOCKED_COMMANDS = new Set([
+ "subscribe",
+ "unsubscribe",
+ "psubscribe",
+ "punsubscribe",
+ "ssubscribe",
+ "sunsubscribe",
+ "monitor",
+ "hello",
+ "reset",
+ "select",
+ "client"
+]);
+
+const MAX_REPLY_BYTES = 256 * 1024;
+
+// a reply costs ~3x its size to receive, and one user may hold several sessions
+const MAX_WIRE_BYTES = 8 * 1024 * 1024;
+
+const CONNECT_TIMEOUT_MS = 15_000;
+
+const callWithDeadline = async (redisClient: Redis, command: string, args: string[]): Promise<unknown> => {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ redisClient.call(command, ...args),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`command timed out after ${COMMAND_TIMEOUT_MS / 1000}s`)),
+ COMMAND_TIMEOUT_MS
+ );
+ })
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+};
+
+const executeCommand = async (
+ redisClient: Redis,
+ budget: TReplyBudget,
+ input: string
+): Promise<{ output: string; shouldClose: boolean }> => {
+ const trimmed = input.trim();
+
+ if (trimmed.length === 0) {
+ return { output: "", shouldClose: false };
+ }
+
+ const lower = trimmed.toLowerCase();
+ if (lower === "quit" || lower === "exit") {
+ return { output: "", shouldClose: true };
+ }
+
+ const tokens = tokenizeRedisInput(trimmed);
+ if (tokens.length === 0) {
+ return { output: "", shouldClose: false };
+ }
+
+ const [command, ...args] = tokens;
+
+ if (BLOCKED_COMMANDS.has(command.toLowerCase())) {
+ return {
+ output: `(error) ${command.toUpperCase()} is not supported in web access, use the Infisical CLI for this\n`,
+ shouldClose: false
+ };
+ }
+
+ try {
+ budget.arm();
+ const result = await callWithDeadline(redisClient, command, args);
+ const formatted = formatRedisReply(result);
+ if (formatted.length > MAX_REPLY_BYTES) {
+ return {
+ output: `${formatted.slice(0, MAX_REPLY_BYTES)}\n(reply truncated at ${MAX_REPLY_BYTES / 1024}KB)\n`,
+ shouldClose: false
+ };
+ }
+ return { output: `${formatted}\n`, shouldClose: false };
+ } catch (err) {
+ if (budget.exceeded()) return { output: "", shouldClose: false };
+ const message = err instanceof Error ? err.message : String(err);
+ return { output: `(error) ${escapeTerminalControlBytes(message)}\n`, shouldClose: false };
+ }
+};
+
+export const handleRedisSession = 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 connectionDetails = params.connectionDetails as { host: string; port: number };
+ const credentials = params.credentials as { username?: string };
+
+ const budget = createReplyBudget(MAX_WIRE_BYTES);
+
+ const redisClient = new Redis({
+ host: "localhost",
+ port: relayPort,
+ maxRetriesPerRequest: 0,
+ reconnectOnError: () => false,
+ retryStrategy: () => null
+ });
+
+ budget.attach(redisClient);
+
+ try {
+ let connectTimer: NodeJS.Timeout | undefined;
+ try {
+ await new Promise<void>((resolve, reject) => {
+ connectTimer = setTimeout(
+ () => reject(new Error(`Redis connection timed out after ${CONNECT_TIMEOUT_MS / 1000}s`)),
+ CONNECT_TIMEOUT_MS
+ );
+ redisClient.once("ready", resolve);
+ redisClient.once("error", reject);
+ redisClient.once("close", () => reject(new Error("Redis connection closed before ready")));
+ });
+ } finally {
+ if (connectTimer) clearTimeout(connectTimer);
+ }
+ } catch (err) {
+ try {
+ redisClient.disconnect();
+ } catch {
+ /* ignore */
+ }
+ throw err;
+ }
+
+ const prompt = `${connectionDetails.host}:${connectionDetails.port}> `;
+
+ sendMessage({
+ type: TerminalServerMessageType.Ready,
+ data: `Connected to ${resourceName} as ${credentials.username || "default"}\n\n`,
+ prompt
+ });
+
+ logger.info({ sessionId }, "Redis web access session established");
+
+ // Sequential message processing to prevent concurrent command issues
+ let processingPromise = Promise.resolve();
+
+ socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
+ processingPromise = processingPromise
+ .then(async () => {
+ const message = parseClientMessage(rawData, RedisClientMessageSchema);
+ if (!message) {
+ sendMessage({
+ type: TerminalServerMessageType.Output,
+ data: "Invalid message format\n",
+ prompt
+ });
+ return;
+ }
+
+ if (message.type === RedisClientMessageType.Control) {
+ if (message.data === "quit") {
+ sendSessionEnd(SessionEndReason.UserQuit);
+ onCleanup();
+ socket.close();
+ return;
+ }
+ if (message.data === "clear-buffer") {
+ return;
+ }
+ return;
+ }
+
+ if (message.type === RedisClientMessageType.Input) {
+ const result = await executeCommand(redisClient, budget, message.data);
+
+ if (result.shouldClose) {
+ sendSessionEnd(SessionEndReason.UserQuit);
+ onCleanup();
+ socket.close();
+ return;
+ }
+
+ sendMessage({
+ type: TerminalServerMessageType.Output,
+ data: result.output,
+ prompt
+ });
+ }
+ })
+ .catch((err) => {
+ logger.error(err, "Error processing Redis message");
+ sendMessage({
+ type: TerminalServerMessageType.Output,
+ data: "Internal error\n",
+ prompt
+ });
+ });
+ });
+
+ // Tunnel drop detection
+ const endReason = () => (budget.exceeded() ? SessionEndReason.ReplyTooLarge : resolveEndReason(isNearSessionExpiry));
+
+ redisClient.on("error", (err) => {
+ logger.error(err, "Redis connection error");
+ sendSessionEnd(endReason());
+ onCleanup();
+ socket.close();
+ });
+
+ redisClient.on("close", () => {
+ sendSessionEnd(endReason());
+ onCleanup();
+ socket.close();
+ });
+
+ return {
+ cleanup: async () => {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ await Promise.race([
+ redisClient.quit(),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, CLEANUP_QUIT_TIMEOUT_MS);
+ })
+ ]);
+ } catch (err) {
+ logger.debug(err, "Error closing Redis client");
+ } finally {
+ if (timer) clearTimeout(timer);
+ redisClient.disconnect();
+ }
+ }
+ };
+};
diff --git a/backend/src/ee/services/pam-web-access/redis/pam-redis-ws-types.ts b/backend/src/ee/services/pam-web-access/redis/pam-redis-ws-types.ts
new file mode 100644
index 0000000000..40c3abcd6e
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/redis/pam-redis-ws-types.ts
@@ -0,0 +1,11 @@
+import { z } from "zod";
+
+export enum RedisClientMessageType {
+ Input = "input",
+ Control = "control"
+}
+
+const InputSchema = z.object({ type: z.literal(RedisClientMessageType.Input), data: z.string() });
+const ControlSchema = z.object({ type: z.literal(RedisClientMessageType.Control), data: z.string() });
+
+export const RedisClientMessageSchema = z.discriminatedUnion("type", [InputSchema, ControlSchema]);
diff --git a/docs/documentation/platform/pam/accounts/overview.mdx b/docs/documentation/platform/pam/accounts/overview.mdx
index 47526d93d3..02cd9a5302 100644
--- a/docs/documentation/platform/pam/accounts/overview.mdx
+++ b/docs/documentation/platform/pam/accounts/overview.mdx
@@ -18,7 +18,7 @@ PAM supports the following account types:
| [**MySQL**](/documentation/platform/pam/accounts/mysql) | MySQL databases | ✓ |
| [**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 | |
+| [**Redis**](/documentation/platform/pam/accounts/redis) | Redis databases | ✓ |
| [**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/redis.mdx b/docs/documentation/platform/pam/accounts/redis.mdx
index 15eb55b220..bcc3ea28be 100644
--- a/docs/documentation/platform/pam/accounts/redis.mdx
+++ b/docs/documentation/platform/pam/accounts/redis.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "Redis"
description: "Add and connect to Redis databases."
---
-Redis accounts let you manage access to your Redis databases. Users connect through the CLI (a local proxy), and every [session](/documentation/platform/pam/sessions/overview) is recorded.
+Redis accounts let you manage access to your Redis databases. Users connect through Web Access (a browser-based interface) or CLI (a local proxy), and every [session](/documentation/platform/pam/sessions/overview) is recorded.
## Creating an Account
@@ -38,22 +38,39 @@ Redis accounts let you manage access to your Redis databases. Users connect thro
## Connecting
-The CLI starts a local proxy that you connect to with your preferred Redis client.
+<Tabs>
+ <Tab title="Web Access">
+ Web Access provides a browser-based Redis console where you type commands the same way you would in `redis-cli`.
-```bash
-infisical pam access my-folder/cache-primary
-```
+ To connect:
+ 1. Go to **Privileged Access Management → Accounts**
+ 2. Find the account and click the rocket icon (or select **Launch Session** from the menu)
+ 3. Click **Connect in Browser**
-The command outputs the local port to connect to. Then use `redis-cli` or any Redis client:
-```bash
-redis-cli -h 127.0.0.1 -p <port>
-```
+ Type `quit` or `exit` to end the session.
-No password needed since the proxy handles authentication.
+ Web Access is built for interactive use. Very long replies are shortened, and commands that stream results, such as `SUBSCRIBE` and `MONITOR`, are only available through the CLI.
-**Flags:**
-- `--port <port>` — use a specific local port (otherwise one is assigned automatically)
-- `--reason <reason>` — provide an access reason (if required by template)
+ </Tab>
+ <Tab title="CLI">
+ The CLI starts a local proxy that you connect to with your preferred Redis client.
+
+ ```bash
+ infisical pam access my-folder/cache-primary
+ ```
+
+ The command outputs the local port to connect to. Then use `redis-cli` or any Redis client:
+ ```bash
+ redis-cli -h 127.0.0.1 -p <port>
+ ```
+
+ No password needed since the proxy handles authentication.
+
+ **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>
## Next Steps
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
index 8d7ada6c6b..2cc38cafc8 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
@@ -23,16 +23,21 @@ const TerminalContent = ({
mfaSessionId?: string;
}) => {
const [sessionEnded, setSessionEnded] = useState(false);
+ const [endReason, setEndReason] = useState<string | undefined>();
const { containerRef, isConnected, disconnect, reconnect } = useWebAccessSession({
accountId: account.id,
accountType: account.accountType,
reason,
mfaSessionId,
- onSessionEnd: () => setSessionEnded(true)
+ onSessionEnd: (reasonText) => {
+ setEndReason(reasonText);
+ setSessionEnded(true);
+ }
});
const handleReconnect = () => {
+ setEndReason(undefined);
setSessionEnded(false);
reconnect();
};
@@ -54,7 +59,9 @@ const TerminalContent = ({
style={{ minHeight: 0 }}
>
<div ref={containerRef} className="h-full" style={{ minWidth: "100%" }} />
- {sessionEnded && <DisconnectedScreen onReconnect={handleReconnect} />}
+ {sessionEnded && (
+ <DisconnectedScreen onReconnect={handleReconnect} description={endReason} />
+ )}
</div>
<div className="flex items-center justify-between border-t border-border bg-card px-3 py-1.5 text-xs">
<span className="flex items-center gap-1.5">
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
index 76d44cfcbe..f7a12eb0ca 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
+++ b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
@@ -17,7 +17,7 @@ type UseWebAccessSessionOptions = {
accountType: string;
reason?: string;
mfaSessionId?: string;
- onSessionEnd?: () => void;
+ onSessionEnd?: (endReason?: string) => void;
};
export const useWebAccessSession = ({
@@ -42,6 +42,7 @@ export const useWebAccessSession = ({
const nextPromptRejecterRef = useRef<((reason: Error) => void) | null>(null);
const onSessionEndRef = useRef(onSessionEnd);
+ const endReasonRef = useRef<string | undefined>(undefined);
const submittedReasonRef = useRef<string | undefined>(reason);
const mfaSessionIdRef = useRef<string | undefined>(mfaSessionId);
@@ -85,6 +86,7 @@ export const useWebAccessSession = ({
const { protocol, host } = window.location;
const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;
+ endReasonRef.current = undefined;
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
@@ -168,6 +170,7 @@ export const useWebAccessSession = ({
}
if (msg.type === WsMessageType.SessionEnd) {
+ endReasonRef.current = msg.reason;
terminal.write(`\r\n${msg.reason.replace(/\r?\n/g, "\r\n")}\r\n`);
return;
}
@@ -207,7 +210,7 @@ export const useWebAccessSession = ({
terminalRef.current.options.disableStdin = true;
}
setIsConnected(false);
- onSessionEndRef.current?.();
+ onSessionEndRef.current?.(endReasonRef.current);
};
ws.onerror = () => {
@@ -470,7 +473,7 @@ export const useWebAccessSession = ({
}
});
} else {
- // Non-SSH (PostgreSQL, Redis): use xterm-readline for full line-editing support
+ // Redis: use xterm-readline for full line-editing support
const readlineAddon = new Readline();
terminal.loadAddon(readlineAddon);
readlineRef.current = readlineAddon;