Skip to content

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

fix(pam): fix live logs

x0322055d45f2f0d6f9
diff --git a/backend/src/ee/routes/v1/pam-session-chunk-router.ts b/backend/src/ee/routes/v1/pam-session-chunk-router.ts
index 3f03154ca6..527eb5d744 100644
--- a/backend/src/ee/routes/v1/pam-session-chunk-router.ts
+++ b/backend/src/ee/routes/v1/pam-session-chunk-router.ts
@@ -184,6 +184,7 @@ export const registerPamSessionChunkRouter = async (server: FastifyZodProvider)
response: {
200: z.object({
legacy: z.boolean(),
+ sessionComplete: z.boolean(),
sessionKey: z.string().nullable(),
projectId: z.string().optional(),
storageBackend: z.string().optional(),
@@ -195,10 +196,11 @@ export const registerPamSessionChunkRouter = async (server: FastifyZodProvider)
handler: async (req) => {
const result = await server.services.pamSessionChunk.getPlaybackBundle(req.params.sessionId, req.permission);
if (result.legacy) {
- return { legacy: true, sessionKey: null, chunks: [] };
+ return { legacy: true, sessionComplete: result.sessionComplete, sessionKey: null, chunks: [] };
}
return {
legacy: false,
+ sessionComplete: result.sessionComplete,
sessionKey: result.sessionKey,
projectId: result.projectId,
storageBackend: result.storageBackend,
diff --git a/backend/src/ee/services/pam-session/pam-session-chunk-service.ts b/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
index 03bd742c62..de04997ed0 100644
--- a/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
@@ -15,6 +15,7 @@ import { PAM_RECORDING_STORAGE_FACTORY_MAP } from "../pam-session-recording-stor
import { buildExternalChunkObjectKey } from "../pam-session-recording-storage/pam-session-recording-storage-types";
import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../permission/project-permission";
import { TPamSessionDALFactory } from "./pam-session-dal";
+import { PamSessionStatus } from "./pam-session-enums";
import { TPamSessionEventChunkDALFactory } from "./pam-session-event-chunk-dal";
import { decryptSessionKey, verifyGatewayUploadToken } from "./pam-session-recording-secrets";
@@ -231,9 +232,11 @@ export const pamSessionChunkServiceFactory = ({
ProjectPermissionSub.PamSessions
);
+ const sessionComplete = session.status !== PamSessionStatus.Active && session.status !== PamSessionStatus.Starting;
+
if (!session.encryptedSessionKey) {
// Legacy session fall through to legacy decrypt path
- return { sessionKey: null, chunks: [], legacy: true as const };
+ return { sessionKey: null, chunks: [], legacy: true as const, sessionComplete };
}
const sessionKey = await decryptSessionKey({
@@ -266,6 +269,7 @@ export const pamSessionChunkServiceFactory = ({
return {
sessionKey: sessionKey.toString("base64"),
legacy: false as const,
+ sessionComplete,
projectId: session.projectId,
storageBackend: config?.backend ?? PamRecordingStorageBackend.Postgres,
chunks: chunks.map((c) => ({
diff --git a/frontend/src/hooks/api/pam/session-playback/queries.tsx b/frontend/src/hooks/api/pam/session-playback/queries.tsx
index 275c89a5dc..ced1e5816b 100644
--- a/frontend/src/hooks/api/pam/session-playback/queries.tsx
+++ b/frontend/src/hooks/api/pam/session-playback/queries.tsx
@@ -1,9 +1,10 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import {
+ DecryptedChunkResult,
decryptOneChunk,
detectChunkGaps,
importSessionKeyFromBase64,
@@ -24,13 +25,22 @@ const fetchBundle = async (sessionId: string): Promise<TPamPlaybackBundle> => {
return data;
};
-export const useGetPamSessionPlaybackBundle = (sessionId: string, enabled = true) =>
+const PLAYBACK_POLL_INTERVAL_MS = 5000;
+
+export const useGetPamSessionPlaybackBundle = (
+ sessionId: string,
+ enabled = true,
+ isActive = false
+) =>
useQuery({
queryKey: pamPlaybackKeys.bundle(sessionId),
enabled: Boolean(sessionId) && enabled,
queryFn: () => fetchBundle(sessionId),
staleTime: 0,
- gcTime: 0
+ gcTime: 0,
+ refetchInterval: isActive
+ ? (query) => (query.state.data?.sessionComplete ? false : PLAYBACK_POLL_INTERVAL_MS)
+ : false
});
export type DecryptedChunkRecord = {
@@ -47,18 +57,50 @@ export type PlaybackDecryptState = {
missingChunks: number[];
totalChunks: number;
totalDurationMs: number;
+ sessionComplete: boolean;
};
const fallbackUrlBuilderFor = (sessionId: string) => (chunkIndex: number) =>
`/api/v1/pam/sessions/${sessionId}/chunks/${chunkIndex}/ciphertext`;
+const collectChunkResult = (
+ r: Awaited<DecryptedChunkResult>,
+ events: unknown[],
+ brokenChunks: TBrokenChunkMarker[],
+ inlineMarkers = false
+): boolean => {
+ if (r.ok) {
+ events.push(...r.events);
+ if (events.length > PAM_PLAYBACK_MAX_TOTAL_EVENTS) {
+ brokenChunks.push({
+ __brokenChunk: true,
+ chunkIndex: r.chunkIndex,
+ reason: "limit",
+ message: `Total event count exceeds playback limit of ${PAM_PLAYBACK_MAX_TOTAL_EVENTS}; remaining chunks skipped`
+ });
+ return true;
+ }
+ } else {
+ const marker: TBrokenChunkMarker = {
+ __brokenChunk: true,
+ chunkIndex: r.chunkIndex,
+ reason: r.reason,
+ message: r.message
+ };
+ brokenChunks.push(marker);
+ if (inlineMarkers) events.push(marker);
+ }
+ return false;
+};
+
export const useDecryptedSessionLogs = (
sessionId: string,
- enabled = true
+ enabled = true,
+ isActive = false
): PlaybackDecryptState => {
- const bundleQuery = useGetPamSessionPlaybackBundle(sessionId, enabled);
+ const bundleQuery = useGetPamSessionPlaybackBundle(sessionId, enabled, isActive);
const bundle = bundleQuery.data;
- const [state, setState] = useState<PlaybackDecryptState>({
+ const [state, setState] = useState<Omit<PlaybackDecryptState, "sessionComplete">>({
legacy: false,
loading: true,
events: [],
@@ -70,6 +112,21 @@ export const useDecryptedSessionLogs = (
const fallbackUrlBuilder = useMemo(() => fallbackUrlBuilderFor(sessionId), [sessionId]);
+ // Refs for incremental decryption across poll cycles (active sessions only)
+ const sessionKeyRef = useRef<CryptoKey | null>(null);
+ const decryptedIndicesRef = useRef(new Set<number>());
+ const accEventsRef = useRef<unknown[]>([]);
+ const accBrokenRef = useRef<TBrokenChunkMarker[]>([]);
+ const prevSessionIdRef = useRef(sessionId);
+
+ if (prevSessionIdRef.current !== sessionId) {
+ sessionKeyRef.current = null;
+ decryptedIndicesRef.current = new Set();
+ accEventsRef.current = [];
+ accBrokenRef.current = [];
+ prevSessionIdRef.current = sessionId;
+ }
+
useEffect(() => {
if (!enabled || !bundle) return undefined;
let cancelled = false;
@@ -103,19 +160,22 @@ export const useDecryptedSessionLogs = (
return;
}
- let sessionKey: CryptoKey;
- try {
- sessionKey = await importSessionKeyFromBase64(bundle.sessionKey);
- } catch (err) {
- if (!cancelled) {
- setState((s) => ({
- ...s,
- loading: false,
- error: `Invalid session key: ${(err as Error).message}`
- }));
+ // Cache session key across poll cycles
+ if (!sessionKeyRef.current) {
+ try {
+ sessionKeyRef.current = await importSessionKeyFromBase64(bundle.sessionKey);
+ } catch (err) {
+ if (!cancelled) {
+ setState((s) => ({
+ ...s,
+ loading: false,
+ error: `Invalid session key: ${(err as Error).message}`
+ }));
+ }
+ return;
}
- return;
}
+ const sessionKey = sessionKeyRef.current;
const projectId = bundle.projectId ?? "";
const sortedChunks = [...bundle.chunks].sort((a, b) => a.chunkIndex - b.chunkIndex);
@@ -133,89 +193,107 @@ export const useDecryptedSessionLogs = (
}
const missingChunks = detectChunkGaps(sortedChunks);
- const missingSet = new Set(missingChunks);
- const events: unknown[] = [];
- const brokenChunks: PlaybackDecryptState["brokenChunks"] = [];
- let chunkIdx = 0;
+ const useIncremental = isActive || decryptedIndicesRef.current.size > 0;
- const maxIndex = sortedChunks.length ? sortedChunks[sortedChunks.length - 1].chunkIndex : 0;
+ if (useIncremental) {
+ const newChunks = sortedChunks.filter(
+ (c) => !decryptedIndicesRef.current.has(c.chunkIndex)
+ );
- // Publish total before any chunk decrypts.
- setState((s) => ({
- ...s,
- totalChunks: sortedChunks.length,
- totalDurationMs,
- missingChunks
- }));
+ for (let ci = 0; ci < newChunks.length; ci += 1) {
+ if (cancelled) return;
- for (let i = 0; i <= maxIndex; i += 1) {
- if (cancelled) return;
-
- if (missingSet.has(i)) {
- const marker: TBrokenChunkMarker = {
- __brokenChunk: true,
- chunkIndex: i,
- reason: "missing",
- message: `Chunk ${i} was not found in the recording`
- };
- events.push(marker);
- brokenChunks.push(marker);
- } else {
+ const chunk = newChunks[ci];
// eslint-disable-next-line no-await-in-loop
const r = await decryptOneChunk({
- chunk: sortedChunks[chunkIdx],
+ chunk,
sessionKey,
projectId,
sessionId,
fallbackUrlBuilder
});
- chunkIdx += 1;
- if (r.ok) {
- events.push(...r.events);
- if (events.length > PAM_PLAYBACK_MAX_TOTAL_EVENTS) {
- brokenChunks.push({
- __brokenChunk: true,
- chunkIndex: r.chunkIndex,
- reason: "limit",
- message: `Total event count exceeds playback limit of ${PAM_PLAYBACK_MAX_TOTAL_EVENTS}; remaining chunks skipped`
- });
- break;
- }
- } else {
+
+ decryptedIndicesRef.current.add(chunk.chunkIndex);
+
+ if (collectChunkResult(r, accEventsRef.current, accBrokenRef.current)) break;
+ }
+
+ if (!cancelled) {
+ setState({
+ legacy: false,
+ loading: isActive && !bundle.sessionComplete,
+ events: [...accEventsRef.current],
+ brokenChunks: [...accBrokenRef.current],
+ missingChunks,
+ totalChunks: sortedChunks.length,
+ totalDurationMs
+ });
+ }
+ } else {
+ // Full path: decrypt all chunks with gap markers (completed sessions)
+ const missingSet = new Set(missingChunks);
+ const events: unknown[] = [];
+ const brokenChunks: PlaybackDecryptState["brokenChunks"] = [];
+ let chunkIdx = 0;
+
+ const maxIndex = sortedChunks.length ? sortedChunks[sortedChunks.length - 1].chunkIndex : 0;
+
+ setState((s) => ({
+ ...s,
+ totalChunks: sortedChunks.length,
+ totalDurationMs,
+ missingChunks
+ }));
+
+ for (let i = 0; i <= maxIndex; i += 1) {
+ if (cancelled) return;
+
+ if (missingSet.has(i)) {
const marker: TBrokenChunkMarker = {
__brokenChunk: true,
- chunkIndex: r.chunkIndex,
- reason: r.reason,
- message: r.message
+ chunkIndex: i,
+ reason: "missing",
+ message: `Chunk ${i} was not found in the recording`
};
events.push(marker);
brokenChunks.push(marker);
+ } else {
+ // eslint-disable-next-line no-await-in-loop
+ const r = await decryptOneChunk({
+ chunk: sortedChunks[chunkIdx],
+ sessionKey,
+ projectId,
+ sessionId,
+ fallbackUrlBuilder
+ });
+ chunkIdx += 1;
+ if (collectChunkResult(r, events, brokenChunks, true)) break;
}
+
+ setState({
+ legacy: false,
+ loading: true,
+ events: [...events],
+ brokenChunks: [...brokenChunks],
+ missingChunks,
+ totalChunks: sortedChunks.length,
+ totalDurationMs
+ });
}
+ if (cancelled) return;
+
setState({
legacy: false,
- loading: true,
- events: [...events],
- brokenChunks: [...brokenChunks],
+ loading: false,
+ events,
+ brokenChunks,
missingChunks,
totalChunks: sortedChunks.length,
totalDurationMs
});
}
-
- if (cancelled) return;
-
- setState({
- legacy: false,
- loading: false,
- events,
- brokenChunks,
- missingChunks,
- totalChunks: sortedChunks.length,
- totalDurationMs
- });
};
run().catch((err) => {
@@ -227,7 +305,10 @@ export const useDecryptedSessionLogs = (
return () => {
cancelled = true;
};
- }, [bundle, enabled, sessionId, fallbackUrlBuilder]);
+ }, [bundle, enabled, sessionId, fallbackUrlBuilder, isActive]);
- return state;
+ return {
+ ...state,
+ sessionComplete: bundle?.sessionComplete ?? false
+ };
};
diff --git a/frontend/src/hooks/api/pam/session-playback/types.ts b/frontend/src/hooks/api/pam/session-playback/types.ts
index 0a734c5160..cd4eec57c0 100644
--- a/frontend/src/hooks/api/pam/session-playback/types.ts
+++ b/frontend/src/hooks/api/pam/session-playback/types.ts
@@ -14,6 +14,7 @@ export type TPamPlaybackChunk = {
export type TPamPlaybackBundle = {
legacy: boolean;
+ sessionComplete: boolean;
sessionKey: string | null;
projectId?: string;
storageBackend?: TPamRecordingStorageBackend;
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx
index 9022d70e24..154df66988 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx
@@ -19,6 +19,7 @@ import { ProjectPermissionSub, useOrganization, useProject } from "@app/context"
import { ProjectPermissionPamSessionActions } from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
import { PamSessionStatus, useGetPamSessionById } from "@app/hooks/api/pam";
+import { useGetPamSessionPlaybackBundle } from "@app/hooks/api/pam/session-playback";
import { ProjectType } from "@app/hooks/api/projects/types";
import { PamTerminateSessionModal } from "../components/PamTerminateSessionModal";
@@ -57,8 +58,13 @@ const Page = () => {
requestAnimationFrame(() => setScrollToLogIndex(logIndex));
};
+ const bundleQuery = useGetPamSessionPlaybackBundle(sessionId, !!session);
+ const sessionComplete = bundleQuery.data?.sessionComplete ?? false;
+
const isActive =
- session?.status === PamSessionStatus.Active || session?.status === PamSessionStatus.Starting;
+ (session?.status === PamSessionStatus.Active ||
+ session?.status === PamSessionStatus.Starting) &&
+ !sessionComplete;
const isGatewaySession = !!session?.gatewayIdentityId || !!session?.gatewayId;
return (
<div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
@@ -114,7 +120,10 @@ const Page = () => {
</PageHeader>
<div className="flex">
<div className="mr-4 flex h-fit w-96 shrink-0">
- <PamSessionDetailsSection session={session} />
+ <PamSessionDetailsSection
+ session={session}
+ statusOverride={sessionComplete ? PamSessionStatus.Ended : undefined}
+ />
</div>
<div className="flex min-w-0 flex-1 flex-col gap-4">
<PamSessionAiInsightsSection session={session} onWarningClick={handleWarningClick} />
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx
index d845ab12da..45f3f40d34 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx
@@ -5,12 +5,13 @@ import { PackageOpenIcon } from "lucide-react";
import { IconButton, Tooltip } from "@app/components/v2";
import { Badge } from "@app/components/v3";
import { useTimedReset } from "@app/hooks";
-import { PAM_RESOURCE_TYPE_MAP, TPamSession } from "@app/hooks/api/pam";
+import { PAM_RESOURCE_TYPE_MAP, PamSessionStatus, TPamSession } from "@app/hooks/api/pam";
import { PamSessionStatusBadge } from "../../PamSessionsPage/components/PamSessionStatusBadge";
type Props = {
session: TPamSession;
+ statusOverride?: PamSessionStatus;
};
const DetailItem = ({ label, children }: { label: string; children: React.ReactNode }) => (
@@ -36,8 +37,10 @@ export const PamSessionDetailsSection = ({
startedAt,
expiresAt,
reason
- }
+ },
+ statusOverride
}: Props) => {
+ const displayStatus = statusOverride ?? status;
const [copyTextId, isCopyingId, setCopyTextId] = useTimedReset<string>({
initialState: "Copy ID to clipboard"
});
@@ -96,7 +99,7 @@ export const PamSessionDetailsSection = ({
</DetailItem>
<DetailItem label="Status">
- <PamSessionStatusBadge status={status} />
+ <PamSessionStatusBadge status={displayStatus} />
</DetailItem>
<DetailItem label="IP Address">
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
index 701204d41a..9ad67a4d86 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
@@ -31,16 +31,19 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {
const isActive =
session.status === PamSessionStatus.Active || session.status === PamSessionStatus.Starting;
- const playback = useDecryptedSessionLogs(session.id, true);
+ const playback = useDecryptedSessionLogs(session.id, true, isActive);
+
+ const isLive = isActive && !playback.sessionComplete;
const isLegacyOrNoChunks = playback.legacy || (!playback.loading && playback.totalChunks === 0);
- const legacy = useGetPamSessionLogs(session.id, isActive, isLegacyOrNoChunks);
+ const legacy = useGetPamSessionLogs(session.id, isLive, isLegacyOrNoChunks);
- const logs = isLegacyOrNoChunks ? legacy.logs : (playback.events as typeof legacy.logs);
- const isLoading = isLegacyOrNoChunks ? legacy.isLoading : playback.loading;
- const hasMore = isLegacyOrNoChunks ? legacy.hasMore : false;
- const loadMore = isLegacyOrNoChunks ? legacy.loadMore : () => {};
- const isLoadingMore = isLegacyOrNoChunks ? legacy.isLoadingMore : false;
+ const hasChunkEvents = !playback.legacy && playback.events.length > 0;
+ const logs = hasChunkEvents ? (playback.events as typeof legacy.logs) : legacy.logs;
+ const isLoading = hasChunkEvents ? false : legacy.isLoading || (isLive && logs.length === 0);
+ const hasMore = hasChunkEvents ? false : legacy.hasMore;
+ const loadMore = hasChunkEvents ? () => {} : legacy.loadMore;
+ const isLoadingMore = hasChunkEvents ? false : legacy.isLoadingMore;
const isSSHSession = session.resourceType === PamResourceType.SSH;
const isDatabaseSession =
@@ -72,7 +75,7 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {
<h3 className="text-lg font-medium text-foreground">
{isRdpSession ? "Session Recording" : "Session Logs"}
</h3>
- {isActive && (
+ {isLive && (
<span className="flex animate-pulse items-center gap-1.5 rounded-full bg-success/10 px-2.5 py-1 text-xs font-medium text-success">
<span className="size-1.5 animate-pulse rounded-full bg-success" />
LIVE
@@ -149,7 +152,7 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {
</div>
)}
- {!isActive && hasMore && !isAwsIamSession && (
+ {!isLive && hasMore && !isAwsIamSession && (
<div className="flex justify-center pt-2">
<Button variant="outline" size="xs" isPending={isLoadingMore} onClick={loadMore}>
Load more