Skip to content

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

feat(pam): terminate sessions on user removal from org

Andrey79c5fcc94647
diff --git a/backend/src/ee/services/pam-session/pam-session-access-fns.ts b/backend/src/ee/services/pam-session/pam-session-access-fns.ts
index 9fd30a1984..4236ec0827 100644
--- a/backend/src/ee/services/pam-session/pam-session-access-fns.ts
+++ b/backend/src/ee/services/pam-session/pam-session-access-fns.ts
@@ -11,7 +11,7 @@ import { getResourceIdsWithActionsForActors, pamActorKey } from "../pam/pam-perm
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { ResourcePermissionPamResourceActions } from "../permission/resource-permission";
import { TPamSessionDALFactory } from "./pam-session-dal";
-import { terminatePamSessions } from "./pam-session-fns";
+import { LIVE_PAM_SESSION_STATUSES, sendPamSessionCancellationSignal, terminatePamSessions } from "./pam-session-fns";
// Users and machine identities can both hold PAM sessions, and the two are tracked in separate columns
// (`userId` / `identityId` on the session, `actorUserId` / `actorIdentityId` on the membership). Carrying
@@ -153,3 +153,50 @@ export const terminatePamSessionsWithoutLaunchAccess = async ({
tx
});
};
+
+type TTerminatePamSessionsForUsersDTO = {
+ orgIds: string[];
+ userIds: string[];
+ pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
+ tx?: Knex;
+};
+
+// Same transaction contract as `terminatePamSessions`: the row update rolls back with the caller's
+// transaction, the cancellation signals cannot, so the caller fires the returned callback after COMMIT.
+export const terminatePamSessionsForUsers = async ({
+ orgIds,
+ userIds,
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+}: TTerminatePamSessionsForUsersDTO): Promise<() => void> => {
+ const noop = () => {};
+ if (userIds.length === 0) return noop;
+
+ const sessions = await pamSessionDAL.findLiveByOrgAndUserIds(orgIds, userIds, tx);
+ if (sessions.length === 0) return noop;
+
+ await pamSessionDAL.update(
+ { $in: { id: sessions.map((session) => session.id), status: LIVE_PAM_SESSION_STATUSES } },
+ { status: PamSessionStatus.Terminated, endedAt: new Date() },
+ tx
+ );
+
+ return () => {
+ for (const session of sessions) {
+ if (session.gatewayId) {
+ const sessionActor = resolveSessionActor(session);
+ sendPamSessionCancellationSignal({
+ sessionId: session.id,
+ gatewayId: session.gatewayId,
+ accountType: session.accountType,
+ actorId: sessionActor?.id ?? "",
+ actorType: sessionActor?.type,
+ actorEmail: session.actorEmail || session.actorName,
+ gatewayV2Service
+ });
+ }
+ }
+ };
+};
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 aacfe0c333..e39ccea0cc 100644
--- a/backend/src/ee/services/pam-session/pam-session-dal.ts
+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts
@@ -200,9 +200,21 @@ export const pamSessionDALFactory = (db: TDbClient) => {
return { sessions, totalCount: Number(countResult?.count ?? 0) };
};
+ const findLiveByOrgAndUserIds = async (orgIds: string[], userIds: string[], tx?: Knex) => {
+ if (!orgIds.length || !userIds.length) return [];
+
+ return (tx || db)(TableName.PamSession)
+ .join(TableName.Project, `${TableName.Project}.id`, `${TableName.PamSession}.projectId`)
+ .select(selectAllTableCols(TableName.PamSession))
+ .whereIn(`${TableName.Project}.orgId`, orgIds)
+ .whereIn(`${TableName.PamSession}.userId`, userIds)
+ .whereIn(`${TableName.PamSession}.status`, [PamSessionStatus.Active, PamSessionStatus.Starting]);
+ };
+
return {
...orm,
findById,
+ findLiveByOrgAndUserIds,
claimRecordingSecrets,
countActiveWebSessions,
endExpiredWebSessions,
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index a56b03f0b7..5b8feb566b 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -188,6 +188,13 @@ are reused from `app-connection/shared/sql`, and rotation is brokered through th
account deletion). Duration is capped at the template max; expiration is enforced by a delayed BullMQ job
scheduled at session creation.
+**Nothing re-checks the actor mid-session**, so every path that takes access away has to close sessions
+itself. `pam-session-access-fns.ts` holds the two: `terminatePamSessionsWithoutLaunchAccess` re-derives
+`LaunchSessions` after a membership or role change, and `terminatePamSessionsForUsers` drops everything a
+user holds when they leave the org (SCIM deactivate/delete, org deactivate/remove). Both run inside the
+caller's transaction and hand back a callback to fire after COMMIT — the row flip rolls back, the gateway
+signal does not.
+
**An orphaned session (null `accountId`) is scoped to product admin.** Every
resource-scoped predicate is false once the FK is nulled, so `PamProductRole.Admin` stands in on the
read/terminate paths (the DAL's `includeOrphaned`, `getSessionById`/`terminateSession`, recording
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index c50171ba90..66a18768e6 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -14,11 +14,14 @@ import {
TOrganizations,
TUsers
} from "@app/db/schemas";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
import { reapDeletedGroupFolderGrants } from "@app/ee/services/group/group-folder-grant-fns";
import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";
+import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import { TScimDALFactory } from "@app/ee/services/scim/scim-dal";
import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
@@ -140,6 +143,8 @@ type TScimServiceFactoryDep = {
additionalPrivilegeDAL: TAdditionalPrivilegeDALFactory;
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients" | "deleteByPrincipals">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
scimEventsDAL: Pick<TScimEventsDALFactory, "create" | "findEventsByOrgId">;
emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
@@ -170,7 +175,9 @@ export const scimServiceFactory = ({
scimEventsDAL,
emailDomainDAL,
telemetryService,
- usageMeteringService
+ usageMeteringService,
+ pamSessionDAL,
+ gatewayV2Service
}: TScimServiceFactoryDep): TScimServiceFactory => {
const createScimToken: TScimServiceFactory["createScimToken"] = async ({
actor,
@@ -790,6 +797,8 @@ export const scimServiceFactory = ({
emailDomainDAL
});
+ let sendPamCancellations = () => {};
+
try {
await userDAL.transaction(async (tx) => {
await membershipUserDAL.updateById(
@@ -799,6 +808,16 @@ export const scimServiceFactory = ({
},
tx
);
+
+ if (!scimUser.active) {
+ sendPamCancellations = await terminatePamSessionsForUsers({
+ orgIds: [orgId],
+ userIds: [membership.actorUserId as string],
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+ }
await userDAL.updateById(
membership.actorUserId as string,
{
@@ -838,6 +857,8 @@ export const scimServiceFactory = ({
throw $toScimEmailConflictError(err, newEmail);
}
+ sendPamCancellations();
+
return scimUser;
};
@@ -907,6 +928,8 @@ export const scimServiceFactory = ({
emailDomainDAL
});
+ let sendPamCancellations = () => {};
+
try {
await userDAL.transaction(async (tx) => {
await membershipUserDAL.updateById(
@@ -916,6 +939,16 @@ export const scimServiceFactory = ({
},
tx
);
+
+ if (!active) {
+ sendPamCancellations = await terminatePamSessionsForUsers({
+ orgIds: [orgId],
+ userIds: [membership.actorUserId as string],
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+ }
await userDAL.updateById(
membership.actorUserId!,
{
@@ -962,6 +995,8 @@ export const scimServiceFactory = ({
throw $toScimEmailConflictError(err, newEmail);
}
+ sendPamCancellations();
+
return buildScimUser({
orgMembershipId: membership.id,
username: externalId || user.username,
@@ -1005,7 +1040,9 @@ export const scimServiceFactory = ({
userGroupMembershipDAL,
additionalPrivilegeDAL,
approvalPolicyDAL,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service
});
// Deprovisioning cascades the user's project + group memberships, changing the identity meters.
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index bfdc88c906..4450ecf450 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -70,7 +70,7 @@ import { gatewayPoolDalFactory } from "@app/ee/services/gateway-pool/gateway-poo
import { gatewayPoolMembershipDalFactory } from "@app/ee/services/gateway-pool/gateway-pool-membership-dal";
import { gatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { gatewayV2DalFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
-import { gatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { gatewayV2ServiceFactory, TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { orgGatewayConfigV2DalFactory } from "@app/ee/services/gateway-v2/org-gateway-config-v2-dal";
import { githubOrgSyncDALFactory } from "@app/ee/services/github-org-sync/github-org-sync-dal";
import { githubOrgSyncServiceFactory } from "@app/ee/services/github-org-sync/github-org-sync-service";
@@ -706,6 +706,12 @@ export const registerRoutes = async (
const hsmConnectorDAL = hsmConnectorDALFactory(db);
const secretSyncDAL = secretSyncDALFactory(db, folderDAL);
const userNotificationDAL = userNotificationDALFactory(db);
+ const pamSessionDAL = pamSessionDALFactory(db);
+
+ const deferredGatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails"> = {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ getPAMConnectionDetails: (dto) => gatewayV2Service.getPAMConnectionDetails(dto)
+ };
// ee db layer ops
const permissionDAL = permissionDALFactory(db);
@@ -928,7 +934,9 @@ export const registerRoutes = async (
emailDomainDAL,
oidcConfigDAL,
samlConfigDAL,
- usageMeteringService
+ usageMeteringService,
+ pamSessionDAL,
+ gatewayV2Service: deferredGatewayV2Service
});
const identityAccessTokenService = identityAccessTokenServiceFactory({
@@ -1301,7 +1309,9 @@ export const registerRoutes = async (
alertChannelRecipientDAL,
emailDomainDAL,
telemetryService,
- usageMeteringService
+ usageMeteringService,
+ pamSessionDAL,
+ gatewayV2Service: deferredGatewayV2Service
});
const githubOrgSyncConfigService = githubOrgSyncServiceFactory({
@@ -1514,7 +1524,9 @@ export const registerRoutes = async (
approvalPolicyDAL,
certificatePolicyDAL,
usageMeteringService,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service: deferredGatewayV2Service
});
const subOrgService = subOrgServiceFactory({
@@ -2018,7 +2030,6 @@ export const registerRoutes = async (
kmsService
});
- const pamSessionDAL = pamSessionDALFactory(db);
const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);
// Wired after pamSessionDAL/gatewayV2Service: narrowing a member's access has to close the PAM
diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.ts
index 63ba9ba02d..2ed7ca47b5 100644
--- a/backend/src/services/membership-user/membership-user-service.ts
+++ b/backend/src/services/membership-user/membership-user-service.ts
@@ -9,9 +9,11 @@ import {
TMembershipRolesInsert
} from "@app/db/schemas";
import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
+import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
@@ -91,6 +93,8 @@ type TMembershipUserServiceFactoryDep = {
samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
};
export type TMembershipUserServiceFactory = ReturnType<typeof membershipUserServiceFactory>;
@@ -117,7 +121,9 @@ export const membershipUserServiceFactory = ({
oidcConfigDAL,
samlConfigDAL,
usageMeteringService,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service
}: TMembershipUserServiceFactoryDep) => {
const scopeFactory = {
[AccessScope.Organization]: newOrgMembershipUserFactory({
@@ -600,7 +606,9 @@ export const membershipUserServiceFactory = ({
membershipRoleDAL,
additionalPrivilegeDAL,
approvalPolicyDAL,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service
});
return doc;
}
diff --git a/backend/src/services/org/org-fns.ts b/backend/src/services/org/org-fns.ts
index abffe9b800..7e4af2d52d 100644
--- a/backend/src/services/org/org-fns.ts
+++ b/backend/src/services/org/org-fns.ts
@@ -1,6 +1,9 @@
import { AccessScope } 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 { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";
+import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import { BadRequestError } from "@app/lib/errors";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal";
@@ -28,6 +31,8 @@ type TDeleteOrgMemberships = {
additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
};
export const deleteOrgMembershipsFn = async ({
@@ -42,8 +47,12 @@ export const deleteOrgMembershipsFn = async ({
userGroupMembershipDAL,
additionalPrivilegeDAL,
approvalPolicyDAL,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service
}: TDeleteOrgMemberships) => {
+ let sendPamCancellations = () => {};
+
const deletedMemberships = await orgDAL.transaction(async (tx) => {
await assertWillRetainOrgAdmin({
scopeOrgId: orgId,
@@ -154,9 +163,19 @@ export const deleteOrgMembershipsFn = async ({
await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: membershipUserIds }, tx);
+ sendPamCancellations = await terminatePamSessionsForUsers({
+ orgIds: [orgId, ...childOrgs.map((el) => el.id)],
+ userIds: membershipUserIds,
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+
await licenseService.updateSubscriptionOrgMemberCount(orgId);
return orgMemberships;
});
+ sendPamCancellations();
+
return deletedMemberships;
};
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 7bf1c1d059..83d87704a2 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -13,12 +13,15 @@ import {
TSamlConfigs
} from "@app/db/schemas";
import { bootstrapAgentVaultProject } from "@app/ee/services/agent-vault-project/agent-vault-project-bootstrap";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TLdapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { bootstrapPamProject } from "@app/ee/services/pam-project/pam-project-bootstrap";
+import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";
+import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import {
OrgPermissionActions,
OrgPermissionGroupActions,
@@ -134,6 +137,8 @@ type TOrgServiceFactoryDep = {
additionalPrivilegeDAL: TAdditionalPrivilegeDALFactory;
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteUserStepApproversInProjects">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "create">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
};
@@ -173,7 +178,9 @@ export const orgServiceFactory = ({
approvalPolicyDAL,
alertChannelRecipientDAL,
certificatePolicyDAL,
- usageMeteringService
+ usageMeteringService,
+ pamSessionDAL,
+ gatewayV2Service
}: TOrgServiceFactoryDep) => {
/*
* Get organization details by the organization id
@@ -949,6 +956,8 @@ export const orgServiceFactory = ({
const updatesToActiveAdmin = role === OrgMembershipRole.Admin && isActive !== false;
const noRoleOrActivationChange = role === undefined && (isActive === undefined || isActive === true);
+ let sendPamCancellations = () => {};
+
const membership = await orgDAL.transaction(async (tx) => {
if (!updatesToActiveAdmin && !noRoleOrActivationChange) {
await assertWillRetainOrgAdmin({
@@ -994,8 +1003,22 @@ export const orgServiceFactory = ({
);
}
}
+
+ if (isActive === false && updatedOrgMembership.actorUserId) {
+ sendPamCancellations = await terminatePamSessionsForUsers({
+ orgIds: [orgId],
+ userIds: [updatedOrgMembership.actorUserId],
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+ }
+
return updatedOrgMembership;
});
+
+ sendPamCancellations();
+
return membership;
};
@@ -1300,7 +1323,9 @@ export const orgServiceFactory = ({
userGroupMembershipDAL,
additionalPrivilegeDAL,
approvalPolicyDAL,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service
});
// Removing an org member cascades their project + group memberships, changing the identity meters.
@@ -1356,7 +1381,9 @@ export const orgServiceFactory = ({
userGroupMembershipDAL,
additionalPrivilegeDAL,
approvalPolicyDAL,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ pamSessionDAL,
+ gatewayV2Service
});
// Removing org members cascades their project + group memberships, changing the identity meters.