Skip to content

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

fix(pam): cut sessions on revoke, close approval gaps, restore audit trail

bernie-g59ce97567aca
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts
index d58d598a07..08009e7941 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts
@@ -1,6 +1,7 @@
import z from "zod";
import { ApprovalRequestsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -48,7 +49,24 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod
});
- return result;
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_ACCESS_REQUEST_CREATE,
+ metadata: {
+ requestId: result.request.id,
+ accountId: result.accountId,
+ folderId: result.folderId,
+ duration: req.body.duration,
+ reason: req.body.reason
+ }
+ }
+ });
+
+ return { request: result.request };
}
});
@@ -170,7 +188,24 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod
});
- return result;
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_ACCESS_REQUEST_REVIEW,
+ metadata: {
+ requestId: req.params.requestId,
+ accountId: result.accountId,
+ folderId: result.folderId,
+ status: req.body.status,
+ comment: req.body.comment
+ }
+ }
+ });
+
+ return { request: result.request };
}
});
@@ -202,6 +237,22 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod
});
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_ACCESS_GRANT_REVOKE,
+ metadata: {
+ requestId: req.params.requestId,
+ grantId: result.grant.id,
+ accountId: result.accountId,
+ folderId: result.folderId
+ }
+ }
+ });
+
return {
grant: {
id: result.grant.id,
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts
index 22e79ad575..8f59b91180 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts
@@ -1,5 +1,6 @@
import z from "zod";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -83,7 +84,22 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodP
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod
});
- return result;
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalPamProjectId,
+ event: {
+ type: EventType.PAM_APPROVAL_CONFIG_UPDATE,
+ metadata: {
+ folderId: req.params.folderId,
+ policyId: result.policyId,
+ stepCount: result.stepCount
+ }
+ }
+ });
+
+ return { policyId: result.policyId };
}
});
};
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 cebdf472ab..4edec3c5a2 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -738,6 +738,10 @@ export enum EventType {
PAM_ACCOUNT_DELETE = "pam-account-delete",
PAM_ACCOUNT_SSH_CA_CREATE = "pam-account-ssh-ca-create",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
+ PAM_ACCESS_REQUEST_CREATE = "pam-access-request-create",
+ PAM_ACCESS_REQUEST_REVIEW = "pam-access-request-review",
+ PAM_ACCESS_GRANT_REVOKE = "pam-access-grant-revoke",
+ PAM_APPROVAL_CONFIG_UPDATE = "pam-approval-config-update",
APPROVAL_POLICY_CREATE = "approval-policy-create",
APPROVAL_POLICY_UPDATE = "approval-policy-update",
APPROVAL_POLICY_DELETE = "approval-policy-delete",
@@ -6082,6 +6086,47 @@ interface PamAccountSshCaCreateEvent {
};
}
+interface PamAccessRequestCreateEvent {
+ type: EventType.PAM_ACCESS_REQUEST_CREATE;
+ metadata: {
+ requestId: string;
+ accountId: string;
+ folderId: string;
+ duration: string;
+ reason?: string;
+ };
+}
+
+interface PamAccessRequestReviewEvent {
+ type: EventType.PAM_ACCESS_REQUEST_REVIEW;
+ metadata: {
+ requestId: string;
+ accountId?: string;
+ folderId?: string;
+ status: string;
+ comment?: string;
+ };
+}
+
+interface PamAccessGrantRevokeEvent {
+ type: EventType.PAM_ACCESS_GRANT_REVOKE;
+ metadata: {
+ requestId: string;
+ grantId: string;
+ accountId?: string;
+ folderId?: string;
+ };
+}
+
+interface PamApprovalConfigUpdateEvent {
+ type: EventType.PAM_APPROVAL_CONFIG_UPDATE;
+ metadata: {
+ folderId: string;
+ policyId: string;
+ stepCount: number;
+ };
+}
+
interface UpdateCertificateRenewalConfigEvent {
type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG;
metadata: {
@@ -7690,6 +7735,10 @@ export type Event =
| PamAccountUpdateEvent
| PamAccountDeleteEvent
| PamAccountSshCaCreateEvent
+ | PamAccessRequestCreateEvent
+ | PamAccessRequestReviewEvent
+ | PamAccessGrantRevokeEvent
+ | PamApprovalConfigUpdateEvent
| UpdateCertificateRenewalConfigEvent
| UpdateCertificateMetadataEvent
| DisableCertificateRenewalConfigEvent
diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-service.ts b/backend/src/ee/services/pam-access-request/pam-access-request-service.ts
index e116b553d4..915a7eee8f 100644
--- a/backend/src/ee/services/pam-access-request/pam-access-request-service.ts
+++ b/backend/src/ee/services/pam-access-request/pam-access-request-service.ts
@@ -2,6 +2,7 @@ import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
import { RESOURCE_SCOPE, ResourceType, TApprovalRequestGrants } from "@app/db/schemas";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
@@ -11,7 +12,7 @@ import {
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { ms } from "@app/lib/ms";
+import { formatDuration, ms } from "@app/lib/ms";
import {
TApprovalPolicyDALFactory,
TApprovalPolicyStepApproversDALFactory,
@@ -44,7 +45,7 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TUserDALFactory } from "@app/services/user/user-dal";
-import { PamProductRole } from "../pam/pam-enums";
+import { PamProductRole, PamSessionStatus } from "../pam/pam-enums";
import { resolveAccountByPath } from "../pam/pam-fns";
import {
checkAccountAccess,
@@ -56,6 +57,7 @@ import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
+import { sendPamSessionCancellationSignal } from "../pam-session/pam-session-fns";
import {
TCheckGrantDTO,
TCreateAccessRequestDTO,
@@ -107,6 +109,7 @@ type TPamAccessRequestServiceFactoryDep = {
pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "find">;
pamFolderDAL: Pick<TPamFolderDALFactory, "findById" | "find" | "findOne">;
pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "terminateSessionById">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
membershipDAL: Pick<TMembershipDALFactory, "find">;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
projectDAL: Pick<TProjectDALFactory, "findById">;
@@ -132,6 +135,7 @@ export const pamAccessRequestServiceFactory = ({
pamAccountTemplateDAL,
pamFolderDAL,
pamSessionDAL,
+ gatewayV2Service,
membershipDAL,
membershipRoleDAL,
projectDAL,
@@ -317,7 +321,7 @@ export const pamAccessRequestServiceFactory = ({
await approvalPolicyStepsDAL.delete({ policyId: existingPolicy.id }, tx);
await approvalPolicyDAL.deleteById(existingPolicy.id, tx);
});
- return { policyId: existingPolicy.id };
+ return { policyId: existingPolicy.id, folderId, stepCount: steps.length };
}
if (!hasApprovers) {
@@ -354,7 +358,7 @@ export const pamAccessRequestServiceFactory = ({
}
});
- return { policyId: existingPolicy.id };
+ return { policyId: existingPolicy.id, folderId, stepCount: steps.length };
}
const newPolicy = await approvalPolicyDAL.transaction(async (tx) => {
@@ -401,7 +405,7 @@ export const pamAccessRequestServiceFactory = ({
return policy;
});
- return { policyId: newPolicy.id };
+ return { policyId: newPolicy.id, folderId, stepCount: steps.length };
};
const createRequest = async ({ accountId, path, projectId, reason, duration, ...ctx }: TCreateAccessRequestDTO) => {
@@ -558,7 +562,7 @@ export const pamAccessRequestServiceFactory = ({
requesterEmail: user.email ?? "",
accountName: account.name,
folderName: account.folderName ?? undefined,
- accessDuration: duration,
+ accessDuration: formatDuration(duration),
reason,
approvalUrl
}
@@ -569,7 +573,7 @@ export const pamAccessRequestServiceFactory = ({
}
}
- return { request };
+ return { request, accountId: account.id, folderId: account.folderId };
};
const listRequests = async ({ projectId, folderId, status, offset, limit, ...ctx }: TListAccessRequestsDTO) => {
@@ -606,15 +610,46 @@ export const pamAccessRequestServiceFactory = ({
};
};
+ // Whether the actor is currently an approver on the folder's live policy AND still holds an active
+ // folder membership. This is the same authority reviewRequest enforces, so the approver queue and
+ // the review action agree; the creation-time snapshot alone would leak requests (and requester PII)
+ // to users removed as approvers after the request was created.
+ const isLiveFolderApprover = async (
+ projectId: string,
+ folderId: string,
+ actorId: string,
+ userGroupIds: Set<string>
+ ): Promise<boolean> => {
+ const policy = await findFolderPolicy(folderId);
+ if (!policy) return false;
+ const steps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);
+ const onLivePolicy = steps.some((step) => isUserEligibleApprover(step.approvers, actorId, userGroupIds));
+ if (!onLivePolicy) return false;
+ const activeMemberships = await findActiveFolderMemberships(projectId, folderId);
+ return activeMemberships.some(
+ (m) => m.actorUserId === actorId || (m.actorGroupId && userGroupIds.has(m.actorGroupId))
+ );
+ };
+
const listPendingMyApproval = async ({ projectId, folderId, ...ctx }: TListPendingMyApprovalDTO) => {
await verifyProductMembership(permissionService, projectId, ctx);
const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
+ // Fast reject for users who are not a live approver on any PAM policy in the project.
+ const isApprover = await approvalPolicyDAL.isProjectApprover({
+ projectId,
+ userId: ctx.actorId,
+ groupIds: [...userGroupIds],
+ type: ApprovalPolicyType.PamAccess,
+ scopeType: PAM_FOLDER_SCOPE_TYPE
+ });
+ if (!isApprover) return { requests: [] };
+
const requests = await approvalRequestDAL.findByProjectId(ApprovalPolicyType.PamAccess, projectId);
- // Only requests still awaiting a response belong in an approver's queue.
- const result = requests.filter((request) => {
+ // Only pending requests whose creation-time snapshot lists the actor belong in the queue...
+ const candidates = requests.filter((request) => {
if (request.status !== ApprovalRequestStatus.Pending) return false;
if (folderId) {
@@ -628,6 +663,28 @@ export const pamAccessRequestServiceFactory = ({
return isUserEligibleApprover(currentStep.approvers, ctx.actorId, userGroupIds);
});
+ // ...but the snapshot is re-validated against each folder's live policy so requests whose approver
+ // set changed after creation (e.g. the actor was removed) drop out rather than leaking.
+ const involvedFolderIds = [
+ ...new Set(
+ candidates
+ .map((r) => (r.requestData as { requestData?: TPamAccessRequestData } | null)?.requestData?.folderId)
+ .filter((id): id is string => Boolean(id))
+ )
+ ];
+ const liveApproverFolders = new Set<string>();
+ for (const fId of involvedFolderIds) {
+ // eslint-disable-next-line no-await-in-loop
+ if (await isLiveFolderApprover(projectId, fId, ctx.actorId, userGroupIds)) {
+ liveApproverFolders.add(fId);
+ }
+ }
+
+ const result = candidates.filter((r) => {
+ const fId = (r.requestData as { requestData?: TPamAccessRequestData } | null)?.requestData?.folderId;
+ return Boolean(fId && liveApproverFolders.has(fId));
+ });
+
return { requests: await attachGrantExpiry(await enrichRequestsWithNames(result)) };
};
@@ -687,6 +744,20 @@ export const pamAccessRequestServiceFactory = ({
const requestData = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;
const folderId = requestData?.requestData?.folderId;
+ // The request snapshots the account's folder at creation time, but the account may have since been
+ // moved or deleted. Approving would then grant access governed by the old folder's approvers,
+ // bypassing the account's current folder policy, so block approval of a stale request. Rejection
+ // stays allowed so the stale request can be cleared.
+ if (status === "approved") {
+ const requestedAccountId = requestData?.requestData?.accountId;
+ const account = requestedAccountId ? await pamAccountDAL.findOne({ id: requestedAccountId }) : undefined;
+ if (!account || account.projectId !== projectId || account.folderId !== folderId) {
+ throw new BadRequestError({
+ message: "This request is no longer valid because the account has moved or been removed"
+ });
+ }
+ }
+
const steps = await approvalRequestDAL.findStepsByRequestId(requestId);
const currentStepIndex = steps.findIndex((s) => s.stepNumber === request.currentStep);
if (currentStepIndex === -1) {
@@ -736,7 +807,7 @@ export const pamAccessRequestServiceFactory = ({
}
if (status === "rejected") {
- await approvalRequestDAL.transaction(async (tx) => {
+ const updatedRequest = await approvalRequestDAL.transaction(async (tx) => {
// Row lock serializes concurrent reviews; the pre-transaction checks may be stale by now
const locked = await approvalRequestDAL.findByIdForUpdate(requestId, tx);
if (!locked || locked.status !== ApprovalRequestStatus.Pending) {
@@ -760,10 +831,10 @@ export const pamAccessRequestServiceFactory = ({
tx
);
await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Rejected }, tx);
+ return approvalRequestDAL.findById(requestId, tx);
});
- const updatedRequest = await approvalRequestDAL.findById(requestId);
- return { request: updatedRequest };
+ return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };
}
const { updatedRequest, nextStepToNotify } = await approvalRequestDAL.transaction(async (tx) => {
@@ -884,13 +955,33 @@ export const pamAccessRequestServiceFactory = ({
const attrs = grant.attributes as { accountId?: string } | null;
if (attrs?.accountId) {
- const activeSessions = await pamSessionDAL.find(
- { accountId: attrs.accountId, userId: grant.granteeUserId ?? null, status: "active" },
+ // Cover both active and starting sessions; a session mid-handshake would otherwise slip past
+ // revocation and go live. terminateSessionById flips the row, and the ALPN signal cuts the live
+ // tunnel, since neither the gateway nor the web-access loop watches the status column.
+ const liveSessions = await pamSessionDAL.find(
+ {
+ accountId: attrs.accountId,
+ userId: grant.granteeUserId ?? null,
+ $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] }
+ },
{ tx }
);
- for (const session of activeSessions) {
- // eslint-disable-next-line no-await-in-loop
- await pamSessionDAL.terminateSessionById(session.id, tx);
+ if (liveSessions.length > 0) {
+ const actor = await userDAL.findById(actorId);
+ for (const session of liveSessions) {
+ // eslint-disable-next-line no-await-in-loop
+ await pamSessionDAL.terminateSessionById(session.id, tx);
+ if (session.gatewayId) {
+ sendPamSessionCancellationSignal({
+ sessionId: session.id,
+ gatewayId: session.gatewayId,
+ accountType: session.accountType,
+ actorId,
+ actorEmail: actor?.email ?? "",
+ gatewayV2Service
+ });
+ }
+ }
}
}
@@ -935,7 +1026,7 @@ export const pamAccessRequestServiceFactory = ({
const revokedGrant = await revokeGrantRow(grant, ctx.actorId, "Revoked by admin");
- return { grant: revokedGrant };
+ return { grant: revokedGrant, accountId, folderId: requestData?.requestData?.folderId, grantId: grant.id };
};
// Approval policies, requests, and grants reference folders/accounts by scopeId or by a JSON id
diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.ts
new file mode 100644
index 0000000000..159abaad37
--- /dev/null
+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts
@@ -0,0 +1,65 @@
+import net from "net";
+
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { createGatewayConnection, createRelayConnection } from "@app/lib/gateway-v2/gateway-v2";
+import { logger } from "@app/lib/logger";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { PamAccountType } from "../pam/pam-enums";
+
+// Flipping a session row to terminated does not cut a live tunnel; only this ALPN signal does. Sent
+// best-effort (fire-and-forget) so callers don't block on the gateway round-trip, and shared by every
+// termination path (manual terminate, grant revocation) so they can't drift.
+export const sendPamSessionCancellationSignal = ({
+ sessionId,
+ gatewayId,
+ accountType,
+ actorId,
+ actorEmail,
+ gatewayV2Service
+}: {
+ sessionId: string;
+ gatewayId: string;
+ accountType: string;
+ actorId: string;
+ actorEmail: string;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
+}) => {
+ void (async () => {
+ let relayConn: net.Socket | null = null;
+ try {
+ const certs = await gatewayV2Service.getPAMConnectionDetails({
+ gatewayId,
+ sessionId,
+ accountType: accountType as PamAccountType,
+ host: "0.0.0.0",
+ port: 0,
+ actorMetadata: { id: actorId, type: ActorType.USER, name: actorEmail }
+ });
+ if (!certs) {
+ logger.error(
+ { sessionId, gatewayId },
+ `Failed to get gateway [gatewayId=${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();
+ }
+ })();
+};
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 b111f5ab82..e3ed85a81c 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -1,4 +1,3 @@
-import net from "net";
import RE2 from "re2";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
@@ -8,9 +7,6 @@ import { createSshCert, createSshKeyPair } from "@app/ee/services/ssh/ssh-certif
import { SshCertType } from "@app/ee/services/ssh/ssh-certificate-authority-types";
import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-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 { ms } from "@app/lib/ms";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -63,6 +59,7 @@ import {
import { DEFAULT_SESSION_DURATION_MS } from "./pam-session-constants";
import { TPamSessionDALFactory } from "./pam-session-dal";
import { TPamSessionExpirationServiceFactory } from "./pam-session-expiration-queue";
+import { sendPamSessionCancellationSignal } from "./pam-session-fns";
type TPamSessionServiceFactoryDep = {
pamSessionDAL: Pick<
@@ -631,46 +628,15 @@ export const pamSessionServiceFactory = ({
}
if (session.gatewayId) {
- void (async () => {
- let relayConn: net.Socket | null = null;
- try {
- const user = await userDAL.findById(ctx.actorId);
- const certs = await gatewayV2Service.getPAMConnectionDetails({
- gatewayId: session.gatewayId!,
- sessionId,
- accountType: session.accountType as PamAccountType,
- host: "0.0.0.0",
- port: 0,
- actorMetadata: { id: ctx.actorId, type: ActorType.USER, 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();
- }
- })();
+ const user = await userDAL.findById(ctx.actorId);
+ sendPamSessionCancellationSignal({
+ sessionId,
+ gatewayId: session.gatewayId,
+ accountType: session.accountType,
+ actorId: ctx.actorId,
+ actorEmail: user?.email ?? "",
+ gatewayV2Service
+ });
}
return { session: updated, projectId: session.projectId, accountName: session.accountName };
diff --git a/backend/src/lib/ms/index.ts b/backend/src/lib/ms/index.ts
index 5a0d165cd7..917335eb90 100644
--- a/backend/src/lib/ms/index.ts
+++ b/backend/src/lib/ms/index.ts
@@ -13,3 +13,11 @@ export const ms = (val: string) => {
throw new BadRequestError({ message: `Invalid date format string: ${val}` });
}
};
+
+// Formats a duration string into a human-readable form (e.g. "3600000ms" or "1h" -> "1 hour"),
+// falling back to the input if it can't be parsed. For display only; rounds like the ms package.
+export const formatDuration = (val: string): string => {
+ const parsed = msFn(val as StringValue);
+ if (typeof parsed !== "number") return val;
+ return msFn(parsed, { long: true });
+};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 8eaad67730..77df647f10 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1817,6 +1817,7 @@ export const registerRoutes = async (
pamAccountTemplateDAL,
pamFolderDAL,
pamSessionDAL,
+ gatewayV2Service,
membershipDAL,
membershipRoleDAL,
projectDAL,
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx
index 9b84442ff6..cc76c49f33 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx
@@ -55,6 +55,7 @@ import { TPamAccessRequest } from "@app/hooks/api/pam/types";
import { useGetOrgUsers } from "@app/hooks/api/users/queries";
import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";
+import { formatDuration } from "../../components/formatDuration";
import { formatRelativeExpiry } from "../../components/PamDetailSheet";
import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
import { ApprovalRequestDetailSheet } from "../../PamApprovalRequestsPage/components/ApprovalRequestDetailSheet";
@@ -429,7 +430,11 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {
<TableCell className="text-sm">
<div className="flex flex-col">
<RelativeTime date={request.createdAt} />
- {duration && <span className="text-xs text-muted">for {duration}</span>}
+ {duration && (
+ <span className="text-xs text-muted">
+ for {formatDuration(duration)}
+ </span>
+ )}
</div>
</TableCell>
<TableCell>
diff --git a/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx b/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx
index 3953d68029..6a5f89535a 100644
--- a/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx
+++ b/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx
@@ -41,6 +41,7 @@ import { TPamAccessRequest } from "@app/hooks/api/pam/types";
import { ProjectType } from "@app/hooks/api/projects/types";
import { getRequestStatusInfo } from "../components/approvalRequestStatus";
+import { formatDuration } from "../components/formatDuration";
import { AccountPlatformIcon } from "../PamAccessPage/components/AccountPlatformIcon";
import { ApprovalRequestDetailSheet } from "./components/ApprovalRequestDetailSheet";
@@ -74,7 +75,7 @@ const RequestRow = ({
<TableCell className="max-w-[200px] truncate text-sm">
{request.requestData?.requestData?.reason || "-"}
</TableCell>
- <TableCell className="text-sm">{duration ?? "-"}</TableCell>
+ <TableCell className="text-sm">{formatDuration(duration)}</TableCell>
<TableCell className="text-sm">
{format(new Date(request.createdAt), "MMM d, yyyy h:mm a")}
</TableCell>
diff --git a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx
index e5223a4953..da9571876b 100644
--- a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx
@@ -1,7 +1,6 @@
import { useEffect, useState } from "react";
import { format } from "date-fns";
import { Check, Clock, ShieldCheck, X } from "lucide-react";
-import ms from "ms";
import { createNotification } from "@app/components/notifications";
import { DeleteActionModal } from "@app/components/v2";
@@ -10,16 +9,10 @@ import { useReviewPamAccessRequest, useRevokePamAccessRequest } from "@app/hooks
import { TPamAccessRequest } from "@app/hooks/api/pam/types";
import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";
+import { formatDuration } from "../../components/formatDuration";
import { PamDetailSheet } from "../../components/PamDetailSheet";
import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
-const formatDuration = (duration?: string) => {
- if (!duration) return "-";
- const parsed = ms(duration);
- if (typeof parsed !== "number") return duration;
- return ms(parsed, { long: true });
-};
-
type Props = {
request: TPamAccessRequest | null;
isOpen: boolean;
diff --git a/frontend/src/pages/pam/components/formatDuration.ts b/frontend/src/pages/pam/components/formatDuration.ts
new file mode 100644
index 0000000000..4a4516ebf5
--- /dev/null
+++ b/frontend/src/pages/pam/components/formatDuration.ts
@@ -0,0 +1,10 @@
+import ms from "ms";
+
+// Renders a stored duration (e.g. "3600000ms" from the CLI or "1h" from the dashboard) in a
+// human-readable form, falling back to the raw value if it can't be parsed.
+export const formatDuration = (duration?: string) => {
+ if (!duration) return "-";
+ const parsed = ms(duration);
+ if (typeof parsed !== "number") return duration;
+ return ms(parsed, { long: true });
+};