Skip to content

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

fix(pam): paginate session logs to prevent unbounded memory load

bernie-g0ce5cf3fdb65
diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.ts
index f7b2a22455..490d148412 100644
--- a/backend/src/ee/routes/v1/pam-session-router.ts
+++ b/backend/src/ee/routes/v1/pam-session-router.ts
@@ -12,6 +12,7 @@ import {
HttpEventSchema,
PamSessionCommandLogSchema,
SanitizedSessionSchema,
+ SessionLogsPageSchema,
TerminalEventSchema
} from "@app/ee/services/pam-session/pam-session-schemas";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -253,6 +254,36 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/:sessionId/logs",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ description: "Get paginated PAM session logs",
+ params: z.object({
+ sessionId: z.string().uuid()
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().int().nonnegative().default(0),
+ limit: z.coerce.number().int().min(1).max(100).default(20)
+ }),
+ response: {
+ 200: SessionLogsPageSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.pamSession.getSessionLogs(
+ req.params.sessionId,
+ req.query.offset,
+ req.query.limit,
+ req.permission
+ );
+ }
+ });
+
server.route({
method: "GET",
url: "/:sessionId",
diff --git a/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts b/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts
index 8194608e12..5a2e151f61 100644
--- a/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts
+++ b/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts
@@ -9,10 +9,16 @@ export type TPamSessionEventBatchDALFactory = ReturnType<typeof pamSessionEventB
export const pamSessionEventBatchDALFactory = (db: TDbClient) => {
const orm = ormify(db, TableName.PamSessionEventBatch);
- const findBySessionId = async (sessionId: string, tx?: Knex) => {
+ const findBySessionIdPaginated = async (
+ sessionId: string,
+ { offset, limit }: { offset: number; limit: number },
+ tx?: Knex
+ ) => {
return (tx || db.replicaNode())(TableName.PamSessionEventBatch)
.where("sessionId", sessionId)
.orderBy("startOffset", "asc")
+ .limit(limit)
+ .offset(offset)
.select("*");
};
@@ -23,5 +29,5 @@ export const pamSessionEventBatchDALFactory = (db: TDbClient) => {
.merge(["encryptedEventsBlob"]); // on re-upload of the same offset, overwrite the blob instead of erroring or skipping
};
- return { ...orm, findBySessionId, upsertBatch };
+ return { ...orm, findBySessionIdPaginated, upsertBatch };
};
diff --git a/backend/src/ee/services/pam-session/pam-session-schemas.ts b/backend/src/ee/services/pam-session/pam-session-schemas.ts
index 8b03cf202a..5a700e95b3 100644
--- a/backend/src/ee/services/pam-session/pam-session-schemas.ts
+++ b/backend/src/ee/services/pam-session/pam-session-schemas.ts
@@ -52,3 +52,8 @@ export const SanitizedSessionSchema = PamSessionsSchema.omit({
logs: z.array(z.union([PamSessionCommandLogSchema, HttpEventSchema, TerminalEventSchema])),
gatewayIdentityId: z.string().nullable().optional()
});
+
+export const SessionLogsPageSchema = z.object({
+ logs: z.array(z.union([PamSessionCommandLogSchema, TerminalEventSchema, HttpEventSchema])),
+ hasMore: z.boolean()
+});
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 5795dd68ff..687250848f 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -21,7 +21,7 @@ import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../per
import { TPamSessionDALFactory } from "./pam-session-dal";
import { PamSessionStatus } from "./pam-session-enums";
import { TPamSessionEventBatchDALFactory } from "./pam-session-event-batch-dal";
-import { decryptBatches, decryptSession } from "./pam-session-fns";
+import { decryptBatches, decryptSession, decryptSessionCommandLogs } from "./pam-session-fns";
import { TUpdateSessionLogsDTO, TUploadEventBatchDTO } from "./pam-session-types";
type TPamSessionServiceFactoryDep = {
@@ -94,16 +94,6 @@ export const pamSessionServiceFactory = ({
ProjectPermissionSub.PamSessions
);
- const batches = await pamSessionEventBatchDAL.findBySessionId(sessionId);
- if (batches.length > 0) {
- const logs = await decryptBatches(batches, session.projectId, kmsService);
- return {
- session: { ...session, logs, encryptedLogsBlob: undefined } as unknown as Awaited<
- ReturnType<typeof decryptSession>
- >
- };
- }
-
return {
session: await decryptSession(session, session.projectId, kmsService)
};
@@ -301,6 +291,51 @@ export const pamSessionServiceFactory = ({
return { session: updatedSession, projectId: project.id, alreadyEnded: false };
};
+ const getSessionLogs = async (sessionId: string, offset: number, limit: number, actor: OrgServiceActor) => {
+ const sessionFromDb = await pamSessionDAL.findById(sessionId);
+ if (!sessionFromDb) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: sessionFromDb.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamSessionActions.Read,
+ ProjectPermissionSub.PamSessions
+ );
+
+ // Fetch one extra to determine whether another page exists
+ const batches = await pamSessionEventBatchDAL.findBySessionIdPaginated(sessionId, {
+ offset,
+ limit: limit + 1
+ });
+
+ if (batches.length > 0 || offset > 0) {
+ // Batch-based session
+ const hasMore = batches.length > limit;
+ const pageBatches = hasMore ? batches.slice(0, limit) : batches;
+ const logs = pageBatches.length > 0 ? await decryptBatches(pageBatches, sessionFromDb.projectId, kmsService) : [];
+ return { logs, hasMore };
+ }
+
+ // Legacy blob-based session — bounded by Fastify body limit on upload
+ if (sessionFromDb.encryptedLogsBlob) {
+ const logs = await decryptSessionCommandLogs({
+ projectId: sessionFromDb.projectId,
+ encryptedLogs: sessionFromDb.encryptedLogsBlob,
+ kmsService
+ });
+ return { logs, hasMore: false };
+ }
+
+ return { logs: [], hasMore: false };
+ };
+
const uploadEventBatch = async ({ sessionId, startOffset, events }: TUploadEventBatchDTO, actor: OrgServiceActor) => {
if (actor.type !== ActorType.IDENTITY) {
throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });
@@ -342,5 +377,5 @@ export const pamSessionServiceFactory = ({
return { projectId: project.id };
};
- return { getById, list, updateLogsById, endSessionById, terminateSessionById, uploadEventBatch };
+ return { getById, list, getSessionLogs, updateLogsById, endSessionById, terminateSessionById, uploadEventBatch };
};
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index db79ce84fb..494b80cbfc 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -1,4 +1,4 @@
-import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+import { useInfiniteQuery, useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
@@ -12,7 +12,8 @@ import {
TPamResource,
TPamResourceDependency,
TPamRotationRule,
- TPamSession
+ TPamSession,
+ TPamSessionLogsPage
} from "./types";
export const pamKeys = {
@@ -51,6 +52,7 @@ export const pamKeys = {
accountDependencies: (accountId: string) => [...pamKeys.account(), "dependencies", accountId],
rotationRules: (resourceId: string) => [...pamKeys.resource(), "rotation-rules", resourceId],
getSession: (sessionId: string) => [...pamKeys.session(), "get", sessionId],
+ getSessionLogs: (sessionId: string) => [...pamKeys.session(), "logs", sessionId],
listSessions: (projectId: string) => [...pamKeys.session(), "list", projectId]
};
@@ -301,6 +303,29 @@ export const useGetPamSessionById = (
});
};
+const LOGS_PAGE_LIMIT = 20;
+
+export const useInfiniteGetPamSessionLogs = (
+ sessionId: string,
+ options: { refetchInterval?: number | false } = {}
+) => {
+ return useInfiniteQuery({
+ initialPageParam: 0,
+ queryKey: pamKeys.getSessionLogs(sessionId),
+ queryFn: async ({ pageParam }) => {
+ const { data } = await apiRequest.get<TPamSessionLogsPage>(
+ `/api/v1/pam/sessions/${sessionId}/logs`,
+ { params: { offset: pageParam, limit: LOGS_PAGE_LIMIT } }
+ );
+ return data;
+ },
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.hasMore ? allPages.length * LOGS_PAGE_LIMIT : undefined,
+ enabled: !!sessionId,
+ ...options
+ });
+};
+
export const useListPamSessions = (
projectId: string,
options?: Omit<
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 3e49bb535c..ff5070964f 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -269,3 +269,8 @@ export type TReorderPamRotationRulesDTO = {
export type TPamResourceDependency = TPamAccountDependency & {
accountName: string | null;
};
+
+export type TPamSessionLogsPage = {
+ logs: TPamSessionLog[];
+ hasMore: boolean;
+};
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
index 576c78d23d..10397d24e0 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
@@ -1,12 +1,15 @@
import { faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Button } from "@app/components/v2";
import {
PamResourceType,
+ PamSessionStatus,
THttpEvent,
TPamCommandLog,
TPamSession,
- TTerminalEvent
+ TTerminalEvent,
+ useInfiniteGetPamSessionLogs
} from "@app/hooks/api/pam";
import { CommandLogView } from "./CommandLogView";
@@ -18,7 +21,16 @@ type Props = {
};
export const PamSessionLogsSection = ({ session }: Props) => {
- // Determine log type based on resource type
+ const isActive =
+ session.status === PamSessionStatus.Active || session.status === PamSessionStatus.Starting;
+
+ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isFetching } =
+ useInfiniteGetPamSessionLogs(session.id, {
+ refetchInterval: isActive ? 5000 : false
+ });
+
+ const allLogs = data?.pages.flatMap((page) => page.logs) ?? [];
+
const isSSHSession = session.resourceType === PamResourceType.SSH;
const isDatabaseSession =
session.resourceType === PamResourceType.Postgres ||
@@ -28,7 +40,7 @@ export const PamSessionLogsSection = ({ session }: Props) => {
session.resourceType === PamResourceType.Redis;
const isHttpSession = session.resourceType === PamResourceType.Kubernetes;
const isAwsIamSession = session.resourceType === PamResourceType.AwsIam;
- const hasLogs = session.logs.length > 0;
+ const hasLogs = allLogs.length > 0;
return (
<div className="flex h-full w-full flex-col gap-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
@@ -36,9 +48,9 @@ export const PamSessionLogsSection = ({ session }: Props) => {
<h3 className="text-lg font-medium text-mineshaft-100">Session Logs</h3>
</div>
- {isDatabaseSession && hasLogs && <CommandLogView logs={session.logs as TPamCommandLog[]} />}
- {isSSHSession && hasLogs && <TerminalEventView events={session.logs as TTerminalEvent[]} />}
- {isHttpSession && hasLogs && <HttpEventView events={session.logs as THttpEvent[]} />}
+ {isDatabaseSession && hasLogs && <CommandLogView logs={allLogs as TPamCommandLog[]} />}
+ {isSSHSession && hasLogs && <TerminalEventView events={allLogs as TTerminalEvent[]} />}
+ {isHttpSession && hasLogs && <HttpEventView events={allLogs as THttpEvent[]} />}
{isAwsIamSession && (
<div className="flex grow items-center justify-center text-bunker-300">
<div className="text-center">
@@ -59,7 +71,7 @@ export const PamSessionLogsSection = ({ session }: Props) => {
</div>
</div>
)}
- {!hasLogs && !isAwsIamSession && (
+ {!hasLogs && !isAwsIamSession && !isFetching && (
<div className="flex grow items-center justify-center text-bunker-300">
<div className="text-center">
<div className="mb-2">Session logs are not yet available</div>
@@ -71,6 +83,19 @@ export const PamSessionLogsSection = ({ session }: Props) => {
</div>
</div>
)}
+
+ {hasNextPage && !isAwsIamSession && (
+ <div className="flex justify-center pt-2">
+ <Button
+ variant="outline_bg"
+ size="xs"
+ isLoading={isFetchingNextPage}
+ onClick={() => fetchNextPage()}
+ >
+ Load more
+ </Button>
+ </div>
+ )}
</div>
);
};