Skip to content

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

feat(pam): support terminating active sessions (#5862)

Saif Ur Rahman80cd5bd2a5ec
diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.ts
index e93117a50a..bc9face220 100644
--- a/backend/src/ee/routes/v1/pam-session-router.ts
+++ b/backend/src/ee/routes/v1/pam-session-router.ts
@@ -166,23 +166,70 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const { session, projectId } = await server.services.pamSession.endSessionById(
+ const { session, projectId, alreadyEnded } = await server.services.pamSession.endSessionById(
req.params.sessionId,
req.permission
);
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_END,
- metadata: {
- sessionId: req.params.sessionId,
- accountName: session.accountName
+ if (!alreadyEnded) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId,
+ event: {
+ type: EventType.PAM_SESSION_END,
+ metadata: {
+ sessionId: req.params.sessionId,
+ accountName: session.accountName
+ }
}
- }
- });
+ });
+ }
+
+ return { session };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:sessionId/terminate",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ description: "Terminate an active PAM session",
+ params: z.object({
+ sessionId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ session: PamSessionsSchema.omit({
+ encryptedLogsBlob: true
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { session, projectId, alreadyEnded } = await server.services.pamSession.terminateSessionById(
+ req.params.sessionId,
+ req.permission
+ );
+
+ if (!alreadyEnded) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId,
+ event: {
+ type: EventType.PAM_SESSION_TERMINATE,
+ metadata: {
+ sessionId: req.params.sessionId,
+ accountName: session.accountName
+ }
+ }
+ });
+ }
await server.services.telemetry
.sendPostHogEvents({
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index e9726fa2fc..817b71b417 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -593,6 +593,7 @@ export enum EventType {
PAM_SESSION_START = "pam-session-start",
PAM_SESSION_LOGS_UPDATE = "pam-session-logs-update",
PAM_SESSION_END = "pam-session-end",
+ PAM_SESSION_TERMINATE = "pam-session-terminate",
PAM_SESSION_GET = "pam-session-get",
PAM_SESSION_LIST = "pam-session-list",
PAM_FOLDER_CREATE = "pam-folder-create",
@@ -4723,6 +4724,14 @@ interface PamSessionEndEvent {
};
}
+interface PamSessionTerminateEvent {
+ type: EventType.PAM_SESSION_TERMINATE;
+ metadata: {
+ sessionId: string;
+ accountName: string;
+ };
+}
+
interface PamSessionGetEvent {
type: EventType.PAM_SESSION_GET;
metadata: {
@@ -6140,6 +6149,7 @@ export type Event =
| PamSessionStartEvent
| PamSessionLogsUpdateEvent
| PamSessionEndEvent
+ | PamSessionTerminateEvent
| PamSessionGetEvent
| PamSessionListEvent
| PamFolderCreateEvent
diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.ts
index 48928bf6e7..7da9305522 100644
--- a/backend/src/ee/services/pam-session/pam-session-dal.ts
+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts
@@ -18,6 +18,7 @@ export const pamSessionDALFactory = (db: TDbClient) => {
.select(selectAllTableCols(TableName.PamSession))
.select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"))
.select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))
+ .select(db.ref("id").withSchema(TableName.GatewayV2).as("gatewayId"))
.where(`${TableName.PamSession}.id`, id)
.first();
@@ -50,5 +51,43 @@ export const pamSessionDALFactory = (db: TDbClient) => {
return updatedCount;
};
- return { ...orm, findById, expireSessionById, countActiveWebSessions };
+ const findByProjectId = async (projectId: string, tx?: Knex) => {
+ const sessions = await (tx || db.replicaNode())(TableName.PamSession)
+ .leftJoin(TableName.PamAccount, `${TableName.PamSession}.accountId`, `${TableName.PamAccount}.id`)
+ .leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
+ .leftJoin(TableName.GatewayV2, `${TableName.PamResource}.gatewayId`, `${TableName.GatewayV2}.id`)
+ .select(selectAllTableCols(TableName.PamSession))
+ .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))
+ .where(`${TableName.PamSession}.projectId`, projectId);
+
+ return sessions;
+ };
+
+ 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 terminateSessionById = async (sessionId: string, tx?: Knex) => {
+ const [updated] = await (tx || db)(TableName.PamSession)
+ .where("id", sessionId)
+ .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])
+ .update({ status: PamSessionStatus.Terminated, endedAt: new Date() })
+ .returning("*");
+ return updated;
+ };
+
+ return {
+ ...orm,
+ findById,
+ findByProjectId,
+ expireSessionById,
+ countActiveWebSessions,
+ endSessionById,
+ terminateSessionById
+ };
};
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 4c0ab37b70..8b03cf202a 100644
--- a/backend/src/ee/services/pam-session/pam-session-schemas.ts
+++ b/backend/src/ee/services/pam-session/pam-session-schemas.ts
@@ -49,5 +49,6 @@ export const HttpEventSchema = z.discriminatedUnion("eventType", [HttpRequestEve
export const SanitizedSessionSchema = PamSessionsSchema.omit({
encryptedLogsBlob: true
}).extend({
- logs: z.array(z.union([PamSessionCommandLogSchema, HttpEventSchema, TerminalEventSchema]))
+ logs: z.array(z.union([PamSessionCommandLogSchema, HttpEventSchema, TerminalEventSchema])),
+ gatewayIdentityId: z.string().nullable().optional()
});
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 518794c4ab..2aeebf9d66 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -1,14 +1,21 @@
import { ForbiddenError } from "@casl/ability";
+import net from "net";
import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { createGatewayConnection, createRelayConnection } from "@app/lib/gateway-v2/gateway-v2";
+import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
+import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
+import { PamResource } from "../pam-resource/pam-resource-enums";
import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../permission/project-permission";
import { TPamSessionDALFactory } from "./pam-session-dal";
@@ -19,8 +26,10 @@ import { TUpdateSessionLogsDTO } from "./pam-session-types";
type TPamSessionServiceFactoryDep = {
pamSessionDAL: TPamSessionDALFactory;
projectDAL: TProjectDALFactory;
+ userDAL: Pick<TUserDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
};
export type TPamSessionServiceFactory = ReturnType<typeof pamSessionServiceFactory>;
@@ -28,8 +37,10 @@ export type TPamSessionServiceFactory = ReturnType<typeof pamSessionServiceFacto
export const pamSessionServiceFactory = ({
pamSessionDAL,
projectDAL,
+ userDAL,
permissionService,
- kmsService
+ kmsService,
+ gatewayV2Service
}: TPamSessionServiceFactoryDep) => {
// Helper to check and update expired sessions when viewing session details (redundancy for scheduled job)
// Only applies to non-gateway sessions (e.g., AWS IAM) - gateway sessions are managed by the gateway
@@ -100,7 +111,7 @@ export const pamSessionServiceFactory = ({
ProjectPermissionSub.PamSessions
);
- const sessions = await pamSessionDAL.find({ projectId });
+ const sessions = await pamSessionDAL.findByProjectId(projectId);
return {
sessions: await Promise.all(sessions.map((session) => decryptSession(session, projectId, kmsService)))
@@ -190,24 +201,92 @@ export const pamSessionServiceFactory = ({
throw new ForbiddenRequestError({ message: "Only identities and users can perform this action" });
}
- if (session.status === PamSessionStatus.Ended) {
- return {
- session,
- projectId: project.id
- };
+ const updatedSession = await pamSessionDAL.endSessionById(sessionId);
+ if (!updatedSession) {
+ if (session.status !== PamSessionStatus.Ended && session.status !== PamSessionStatus.Terminated) {
+ throw new BadRequestError({ message: "Cannot end sessions that are not active or starting" });
+ }
+ return { session, projectId: project.id, alreadyEnded: true };
}
- if (session.status !== PamSessionStatus.Active && session.status !== PamSessionStatus.Starting) {
- throw new BadRequestError({ message: "Cannot end sessions that are not active or starting" });
- }
+ return { session: updatedSession, projectId: project.id, alreadyEnded: false };
+ };
- const updatedSession = await pamSessionDAL.updateById(sessionId, {
- endedAt: new Date(),
- status: PamSessionStatus.Ended
+ const terminateSessionById = async (sessionId: string, actor: OrgServiceActor) => {
+ const session = await pamSessionDAL.findById(sessionId);
+ if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
+
+ const project = await projectDAL.findById(session.projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: session.projectId,
+ actionProjectType: ActionProjectType.PAM
});
- return { session: updatedSession, projectId: project.id };
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamSessionActions.Terminate,
+ ProjectPermissionSub.PamSessions
+ );
+
+ // Atomic update: only transitions active/starting → terminated
+ const updatedSession = await pamSessionDAL.terminateSessionById(sessionId);
+ if (!updatedSession) {
+ return { session, projectId: project.id, alreadyEnded: true };
+ }
+
+ // Fire-and-forget ALPN cancellation for gateway sessions
+ if (session.gatewayId) {
+ void (async () => {
+ let relayConn: net.Socket | null = null;
+ try {
+ const user = await userDAL.findById(actor.id);
+ const certs = await gatewayV2Service.getPAMConnectionDetails({
+ gatewayId: session.gatewayId,
+ sessionId,
+ resourceType: session.resourceType as PamResource,
+ // host/port are embedded in cert extensions for routing but not used for cancellation —
+ // real values are encrypted in PamResource.encryptedConnectionDetails and not worth decrypting here
+ host: "0.0.0.0",
+ port: 0,
+ actorMetadata: { id: actor.id, type: actor.type, name: user?.email ?? "" }
+ });
+ if (!certs) {
+ logger.error(
+ { sessionId, gatewayId: session.gatewayId },
+ `Failed to get gateway [gatewayId=${session.gatewayId}] connection details for PAM session [sessionId=${sessionId}] termination`
+ );
+ return;
+ }
+ 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.error(
+ { sessionId, err },
+ `Session [sessionId=${sessionId}] termination ALPN signal failed (best-effort)`
+ );
+ } finally {
+ relayConn?.destroy();
+ }
+ })();
+ }
+
+ return { session: updatedSession, projectId: project.id, alreadyEnded: false };
};
- return { getById, list, updateLogsById, endSessionById };
+ return { getById, list, updateLogsById, endSessionById, terminateSessionById };
};
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 4847784ce0..bde55c3a79 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -397,7 +397,10 @@ const buildAdminPermissionRules = () => {
ProjectPermissionSub.PamAccounts
);
- can([ProjectPermissionPamSessionActions.Read], ProjectPermissionSub.PamSessions);
+ can(
+ [ProjectPermissionPamSessionActions.Read, ProjectPermissionPamSessionActions.Terminate],
+ ProjectPermissionSub.PamSessions
+ );
can(
[
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 48e43df095..a24932d7fa 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -258,8 +258,8 @@ export enum ProjectPermissionPamAccountActions {
}
export enum ProjectPermissionPamSessionActions {
- Read = "read"
- // Terminate = "terminate"
+ Read = "read",
+ Terminate = "terminate"
}
export enum ProjectPermissionPamDiscoveryActions {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index b6cbbce50a..a70eef9b53 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2847,8 +2847,10 @@ export const registerRoutes = async (
const pamSessionService = pamSessionServiceFactory({
pamSessionDAL,
projectDAL,
+ userDAL,
permissionService,
- kmsService
+ kmsService,
+ gatewayV2Service
});
const pamWebAccessService = pamWebAccessServiceFactory({
diff --git a/frontend/src/context/ProjectPermissionContext/index.tsx b/frontend/src/context/ProjectPermissionContext/index.tsx
index 467a340f61..9b46b38687 100644
--- a/frontend/src/context/ProjectPermissionContext/index.tsx
+++ b/frontend/src/context/ProjectPermissionContext/index.tsx
@@ -15,6 +15,7 @@ export {
ProjectPermissionKmipActions,
ProjectPermissionMcpEndpointActions,
ProjectPermissionMemberActions,
+ ProjectPermissionPamSessionActions,
ProjectPermissionPkiCertificateInstallationActions,
ProjectPermissionPkiDiscoveryActions,
ProjectPermissionPkiSubscriberActions,
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index 920504c3e0..efab712870 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -261,8 +261,8 @@ export enum ProjectPermissionPamAccountActions {
}
export enum ProjectPermissionPamSessionActions {
- Read = "read"
- // Terminate = "terminate"
+ Read = "read",
+ Terminate = "terminate"
}
export enum ProjectPermissionPamDiscoveryActions {
diff --git a/frontend/src/context/index.tsx b/frontend/src/context/index.tsx
index 8332a0078f..cd14f48bb4 100644
--- a/frontend/src/context/index.tsx
+++ b/frontend/src/context/index.tsx
@@ -27,6 +27,7 @@ export {
ProjectPermissionKmipActions,
ProjectPermissionMcpEndpointActions,
ProjectPermissionMemberActions,
+ ProjectPermissionPamSessionActions,
ProjectPermissionPkiCertificateInstallationActions,
ProjectPermissionPkiDiscoveryActions,
ProjectPermissionPkiSubscriberActions,
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 80c5bbcca8..ea7191c6a2 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -268,6 +268,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.PAM_SESSION_START]: "Start PAM Session",
[EventType.PAM_SESSION_LOGS_UPDATE]: "Update PAM Session Logs",
[EventType.PAM_SESSION_END]: "End PAM Session",
+ [EventType.PAM_SESSION_TERMINATE]: "Terminate PAM Session",
[EventType.PAM_SESSION_GET]: "Get PAM Session",
[EventType.PAM_SESSION_LIST]: "List PAM Sessions",
[EventType.PAM_FOLDER_CREATE]: "Create PAM Folder",
@@ -409,6 +410,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.PAM_SESSION_START,
EventType.PAM_SESSION_LOGS_UPDATE,
EventType.PAM_SESSION_END,
+ EventType.PAM_SESSION_TERMINATE,
EventType.PAM_SESSION_GET,
EventType.PAM_SESSION_LIST,
EventType.PAM_FOLDER_CREATE,
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 55a5adaac5..68c015cc2e 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -263,6 +263,7 @@ export enum EventType {
PAM_SESSION_START = "pam-session-start",
PAM_SESSION_LOGS_UPDATE = "pam-session-logs-update",
PAM_SESSION_END = "pam-session-end",
+ PAM_SESSION_TERMINATE = "pam-session-terminate",
PAM_SESSION_GET = "pam-session-get",
PAM_SESSION_LIST = "pam-session-list",
PAM_FOLDER_CREATE = "pam-folder-create",
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index 0a20f02cee..31fb9f424a 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -16,6 +16,7 @@ import {
TPamFolder,
TPamResource,
TPamRotationRule,
+ TPamSession,
TReorderPamRotationRulesDTO,
TUpdatePamAccountDTO,
TUpdatePamFolderDTO,
@@ -407,3 +408,20 @@ export const useDeletePamFolder = () => {
}
});
};
+
+export const useTerminatePamSession = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ sessionId }: { sessionId: string; projectId: string }) => {
+ const { data } = await apiRequest.post<{ session: TPamSession }>(
+ `/api/v1/pam/sessions/${sessionId}/terminate`
+ );
+
+ return data.session;
+ },
+ onSuccess: (_, { projectId, sessionId }) => {
+ queryClient.invalidateQueries({ queryKey: pamKeys.listSessions(projectId) });
+ queryClient.invalidateQueries({ queryKey: pamKeys.getSession(sessionId) });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 1366b318d8..5c1e02a681 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -116,6 +116,7 @@ export type TPamSession = {
createdAt: string;
updatedAt: string;
logs: TPamSessionLog[];
+ gatewayIdentityId?: string | null;
};
// Resource DTOs
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx
index 1c25dead36..b281c5b3f3 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx
@@ -1,16 +1,26 @@
import { Helmet } from "react-helmet";
-import { faChevronLeft } from "@fortawesome/free-solid-svg-icons";
+import { faChevronLeft, faEllipsisV } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Link, useParams } from "@tanstack/react-router";
+import { GavelIcon } from "lucide-react";
import { ProjectPermissionCan } from "@app/components/permissions";
-import { PageHeader } from "@app/components/v2";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ IconButton,
+ PageHeader
+} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import { ProjectPermissionSub, useOrganization, useProject } from "@app/context";
import { ProjectPermissionPamSessionActions } from "@app/context/ProjectPermissionContext/types";
-import { useGetPamSessionById } from "@app/hooks/api/pam";
+import { usePopUp } from "@app/hooks";
+import { PamSessionStatus, useGetPamSessionById } from "@app/hooks/api/pam";
import { ProjectType } from "@app/hooks/api/projects/types";
+import { PamTerminateSessionModal } from "../components/PamTerminateSessionModal";
import { PamSessionDetailsSection } from "./components/PamSessionDetailsSection";
import { PamSessionLogsSection } from "./components/PamSessionLogsSection";
@@ -22,6 +32,12 @@ const Page = () => {
const { data: session } = useGetPamSessionById(sessionId);
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["terminateSession"] as const);
+
+ const isActive =
+ session?.status === PamSessionStatus.Active || session?.status === PamSessionStatus.Starting;
+ const isGatewaySession = !!session?.gatewayIdentityId;
+
return (
<div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
{session && (
@@ -41,7 +57,39 @@ const Page = () => {
scope={ProjectType.PAM}
title={`${session.accountName} Session`}
description={`View details for this ${session.accountName} session.`}
- />
+ >
+ {isGatewaySession && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ ariaLabel="Options"
+ colorSchema="secondary"
+ className="w-6"
+ variant="plain"
+ >
+ <FontAwesomeIcon icon={faEllipsisV} />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <ProjectPermissionCan
+ I={ProjectPermissionPamSessionActions.Terminate}
+ a={ProjectPermissionSub.PamSessions}
+ >
+ {(isAllowed: boolean) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed || !isActive}
+ className="text-red-600"
+ icon={<GavelIcon size={14} />}
+ onClick={() => handlePopUpOpen("terminateSession")}
+ >
+ Terminate Session
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </PageHeader>
<div className="flex">
<div className="mr-4 flex h-fit w-96">
<PamSessionDetailsSection session={session} />
@@ -50,6 +98,13 @@ const Page = () => {
<PamSessionLogsSection session={session} />
</div>
</div>
+
+ <PamTerminateSessionModal
+ sessionId={session.id}
+ projectId={currentProject.id}
+ isOpen={popUp.terminateSession.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("terminateSession", isOpen)}
+ />
</div>
)}
</div>
diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx
index 6c2b6f616b..e557094199 100644
--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx
+++ b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx
@@ -9,6 +9,7 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "@tanstack/react-router";
+import { GavelIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
@@ -24,9 +25,19 @@ import {
Tr
} from "@app/components/v2";
import { HighlightText } from "@app/components/v2/HighlightText";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
-import { PAM_RESOURCE_TYPE_MAP, TPamSession, TTerminalEvent } from "@app/hooks/api/pam";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionPamSessionActions,
+ ProjectPermissionSub
+} from "@app/context";
+import {
+ PAM_RESOURCE_TYPE_MAP,
+ PamSessionStatus,
+ TPamSession,
+ TTerminalEvent
+} from "@app/hooks/api/pam";
+import { PamTerminateSessionModal } from "../../components/PamTerminateSessionModal";
import { formatLogContent } from "../../PamSessionsByIDPage/components/PamSessionLogsSection.utils";
import { aggregateTerminalEvents } from "../../PamSessionsByIDPage/components/terminal-utils";
import { PamSessionStatusBadge } from "./PamSessionStatusBadge";
@@ -40,6 +51,7 @@ type Props = {
export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
const router = useRouter();
const [showAllLogs, setShowAllLogs] = useState(false);
+ const [isTerminateDialogOpen, setIsTerminateDialogOpen] = useState(false);
const {
id,
@@ -51,9 +63,13 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
actorName,
actorEmail,
createdAt,
- endedAt
+ endedAt,
+ gatewayIdentityId
} = session;
+ const isActive = status === PamSessionStatus.Active || status === PamSessionStatus.Starting;
+ const isGatewaySession = !!gatewayIdentityId;
+
const { image, name: resourceTypeName } = PAM_RESOURCE_TYPE_MAP[resourceType];
// Check if logs are terminal events and aggregate them
@@ -167,6 +183,26 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
</DropdownMenuItem>
)}
</ProjectPermissionCan>
+ {isGatewaySession && (
+ <ProjectPermissionCan
+ I={ProjectPermissionPamSessionActions.Terminate}
+ a={ProjectPermissionSub.PamSessions}
+ >
+ {(isAllowed: boolean) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed || !isActive}
+ className="text-red-600"
+ icon={<GavelIcon size={14} />}
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsTerminateDialogOpen(true);
+ }}
+ >
+ Terminate Session
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</Tooltip>
@@ -174,6 +210,13 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
</Td>
</Tr>
+ <PamTerminateSessionModal
+ sessionId={id}
+ projectId={projectId}
+ isOpen={isTerminateDialogOpen}
+ onOpenChange={setIsTerminateDialogOpen}
+ />
+
{filteredLogs.length > 0 && (
<Tr>
<Td colSpan={5} className="py-3 text-xs">
diff --git a/frontend/src/pages/pam/components/PamTerminateSessionModal.tsx b/frontend/src/pages/pam/components/PamTerminateSessionModal.tsx
new file mode 100644
index 0000000000..29aa4d589e
--- /dev/null
+++ b/frontend/src/pages/pam/components/PamTerminateSessionModal.tsx
@@ -0,0 +1,55 @@
+import { createNotification } from "@app/components/notifications";
+import { Button, Modal, ModalClose, ModalContent } from "@app/components/v2";
+import { useTerminatePamSession } from "@app/hooks/api/pam";
+
+type Props = {
+ sessionId: string;
+ projectId: string;
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const PamTerminateSessionModal = ({ sessionId, projectId, isOpen, onOpenChange }: Props) => {
+ const terminateSession = useTerminatePamSession();
+
+ const handleTerminate = async () => {
+ await terminateSession.mutateAsync(
+ { sessionId, projectId },
+ {
+ onSuccess: () => {
+ createNotification({
+ text: "Session terminated successfully",
+ type: "success"
+ });
+ onOpenChange(false);
+ }
+ }
+ );
+ };
+
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent
+ title="Terminate Session"
+ subTitle="Are you sure you want to terminate this session?"
+ footerContent={
+ <div className="mx-2 flex items-center">
+ <Button
+ className="mr-4"
+ colorSchema="danger"
+ isLoading={terminateSession.isPending}
+ onClick={handleTerminate}
+ >
+ Terminate
+ </Button>
+ <ModalClose asChild>
+ <Button variant="plain" colorSchema="secondary">
+ Cancel
+ </Button>
+ </ModalClose>
+ </div>
+ }
+ />
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 26378eae76..c347130aaf 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -240,7 +240,8 @@ const PamAccountPolicyActionSchema = z.object({
});
const PamSessionPolicyActionSchema = z.object({
- [ProjectPermissionPamSessionActions.Read]: z.boolean().optional()
+ [ProjectPermissionPamSessionActions.Read]: z.boolean().optional(),
+ [ProjectPermissionPamSessionActions.Terminate]: z.boolean().optional()
});
const PamDiscoveryPolicyActionSchema = z.object({
@@ -1791,10 +1792,12 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
if (subject === ProjectPermissionSub.PamSessions) {
const canRead = action.includes(ProjectPermissionPamSessionActions.Read);
+ const canTerminate = action.includes(ProjectPermissionPamSessionActions.Terminate);
if (!formVal[subject]) formVal[subject] = [{}];
if (canRead) formVal[subject]![0][ProjectPermissionPamSessionActions.Read] = true;
+ if (canTerminate) formVal[subject]![0][ProjectPermissionPamSessionActions.Terminate] = true;
}
if (subject === ProjectPermissionSub.PamDiscovery) {
@@ -3144,6 +3147,11 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
label: "Read",
value: ProjectPermissionPamSessionActions.Read,
description: "View PAM session history and recordings"
+ },
+ {
+ label: "Terminate",
+ value: ProjectPermissionPamSessionActions.Terminate,
+ description: "Terminate active PAM sessions"
}
]
},