Skip to content

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

fix: patches

Sheen Capadngan8ad50308b329
diff --git a/backend/src/ee/routes/v1/external-kms-routers/gcp-kms-router.ts b/backend/src/ee/routes/v1/external-kms-routers/gcp-kms-router.ts
index 97b600c102..6e2ac2eae5 100644
--- a/backend/src/ee/routes/v1/external-kms-routers/gcp-kms-router.ts
+++ b/backend/src/ee/routes/v1/external-kms-routers/gcp-kms-router.ts
@@ -78,6 +78,10 @@ export const registerGcpKmsRouter = async (server: FastifyZodProvider) => {
}
const results = await server.services.externalKms.fetchGcpKeys({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
credential: credentialJson,
gcpRegion: region
});
diff --git a/backend/src/ee/services/external-kms/external-kms-service.ts b/backend/src/ee/services/external-kms/external-kms-service.ts
index af246eacdc..15035c4e77 100644
--- a/backend/src/ee/services/external-kms/external-kms-service.ts
+++ b/backend/src/ee/services/external-kms/external-kms-service.ts
@@ -17,6 +17,7 @@ import { TExternalKmsDALFactory } from "./external-kms-dal";
import {
TCreateExternalKmsDTO,
TDeleteExternalKmsDTO,
+ TFetchGcpKmsKeysDTO,
TGetExternalKmsByIdDTO,
TGetExternalKmsBySlugDTO,
TListExternalKmsDTO,
@@ -471,7 +472,31 @@ export const externalKmsServiceFactory = ({
}
};
- const fetchGcpKeys = async ({ credential, gcpRegion }: Pick<TExternalKmsGcpSchema, "credential" | "gcpRegion">) => {
+ const fetchGcpKeys = async ({
+ credential,
+ gcpRegion,
+ actor,
+ actorId,
+ actorOrgId,
+ actorAuthMethod
+ }: TFetchGcpKmsKeysDTO) => {
+ const { permission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms);
+
+ const plan = await licenseService.getPlan(actorOrgId);
+ if (!plan.externalKms) {
+ throw new BadRequestError({
+ message: "Failed to fetch GCP KMS keys due to plan restriction. Upgrade to the Enterprise plan."
+ });
+ }
+
const externalKms = await GcpKmsProviderFactory({ inputs: { credential, gcpRegion, keyName: "" } });
try {
return await externalKms.getKeysList();
diff --git a/backend/src/ee/services/external-kms/external-kms-types.ts b/backend/src/ee/services/external-kms/external-kms-types.ts
index 850108ac47..e2a25c43e1 100644
--- a/backend/src/ee/services/external-kms/external-kms-types.ts
+++ b/backend/src/ee/services/external-kms/external-kms-types.ts
@@ -1,6 +1,6 @@
import { TOrgPermission } from "@app/lib/types";
-import { TExternalKmsInputSchema, TExternalKmsInputUpdateSchema } from "./providers/model";
+import { TExternalKmsGcpSchema, TExternalKmsInputSchema, TExternalKmsInputUpdateSchema } from "./providers/model";
export type TCreateExternalKmsDTO = {
name?: string;
@@ -28,3 +28,6 @@ export type TGetExternalKmsByIdDTO = {
export type TGetExternalKmsBySlugDTO = {
name: string;
} & Omit<TOrgPermission, "orgId">;
+
+export type TFetchGcpKmsKeysDTO = Pick<TExternalKmsGcpSchema, "credential" | "gcpRegion"> &
+ Omit<TOrgPermission, "orgId">;
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 7a5d8909ea..970a7f98bc 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
@@ -69,7 +69,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 { terminatePamSessions } from "../pam-session/pam-session-fns";
import { getSlackSendTargets, parseNotificationChannels, parseNotificationEvents } from "./pam-access-request-fns";
import {
TAccessRequestActor,
@@ -1255,15 +1255,17 @@ export const pamAccessRequestServiceFactory = ({
return { request: updatedRequest, accountId: requestData?.requestData?.accountId, folderId };
};
- // Marks a grant Revoked and terminates the grantee's live sessions on the granted account. An
- // undefined userId in the session filter would throw in knex; granteeUserId is null when the
- // grantee user was deleted, and their sessions carry a null userId too.
+ // Marks a grant Revoked and terminates the grantee's live sessions on the granted account.
+ //
+ // Returns the tunnel-cancellation callback rather than firing it, so a caller that revokes inside a
+ // transaction which can still roll back (account deletion) only cuts tunnels once the revocation is
+ // durable. Callers outside a transaction invoke it immediately.
const revokeGrantRow = async (
grant: TApprovalRequestGrants,
actorId: string,
reason: string,
tx?: Knex
- ): Promise<TApprovalRequestGrants> => {
+ ): Promise<{ revoked: TApprovalRequestGrants; sendCancellationSignals: () => void }> => {
const revoked = await approvalRequestGrantsDAL.updateById(
grant.id,
{
@@ -1275,47 +1277,43 @@ export const pamAccessRequestServiceFactory = ({
tx
);
+ const noSignals = { revoked, sendCancellationSignals: () => {} };
+
+ // Sessions mirror the grant's actor column: a machine identity session carries identityId with a null
+ // userId, so scope the sweep to whichever column the grant was issued to. granteeUserId is SET NULL
+ // when the grantee user is deleted, leaving a grant with neither column — filtering on a null userId
+ // there would match every machine identity session on the account, so bail instead.
+ let granteeFilter: { userId: string } | { identityId: string } | null = null;
+ if (grant.granteeMachineIdentityId) granteeFilter = { identityId: grant.granteeMachineIdentityId };
+ else if (grant.granteeUserId) granteeFilter = { userId: grant.granteeUserId };
+
const attrs = grant.attributes as { accountId?: string } | null;
- // granteeUserId is SET NULL when the grantee user is deleted, so an orphaned grant has neither
- // actor column. Sweeping on a null userId would match every machine identity session on the
- // account (they carry userId null), so skip the sweep when there is no actor to scope it to.
- const hasGrantee = Boolean(grant.granteeMachineIdentityId || grant.granteeUserId);
- if (attrs?.accountId && hasGrantee) {
- // 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,
- // Sessions mirror the grant's actor column: machine identity sessions carry identityId
- // with a null userId, so filter on whichever the grant was issued to.
- ...(grant.granteeMachineIdentityId
- ? { identityId: grant.granteeMachineIdentityId }
- : { userId: grant.granteeUserId }),
- $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] }
- },
- { 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
- });
- }
- }
- }
- }
+ if (!attrs?.accountId || !granteeFilter) return noSignals;
- return revoked;
+ // 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,
+ ...granteeFilter,
+ $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] }
+ },
+ { tx }
+ );
+ if (liveSessions.length === 0) return noSignals;
+
+ const actor = await userDAL.findById(actorId, tx);
+ const sendCancellationSignals = await terminatePamSessions({
+ sessions: liveSessions,
+ actorId,
+ actorEmail: actor?.email ?? "",
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+
+ return { revoked, sendCancellationSignals };
};
const revokeGrant = async ({ requestId, projectId, ...ctx }: TRevokeAccessRequestDTO) => {
@@ -1354,7 +1352,12 @@ export const pamAccessRequestServiceFactory = ({
throw new ForbiddenRequestError({ message: "You are not authorized to revoke this approval" });
}
- const revokedGrant = await revokeGrantRow(grant, ctx.actorId, "Revoked by admin");
+ const { revoked: revokedGrant, sendCancellationSignals } = await revokeGrantRow(
+ grant,
+ ctx.actorId,
+ "Revoked by admin"
+ );
+ sendCancellationSignals();
return { grant: revokedGrant, accountId, folderId: requestData?.requestData?.folderId, grantId: grant.id };
};
@@ -1386,6 +1389,8 @@ export const pamAccessRequestServiceFactory = ({
);
};
+ // Returns the callback that cuts the tunnels of the sessions it terminated. It runs inside the caller's
+ // delete transaction, which can still fail, so the signals are the caller's to fire after COMMIT.
const cleanupAccountResources = async (
{
accountId,
@@ -1394,7 +1399,7 @@ export const pamAccessRequestServiceFactory = ({
actorId
}: { accountId: string; folderId: string | null | undefined; projectId: string; actorId: string },
tx: Knex
- ) => {
+ ): Promise<() => void> => {
// Requests are folder-scoped with the account id in requestData JSON, so filter in memory.
if (folderId) {
const pending = await approvalRequestDAL.find(
@@ -1421,13 +1426,17 @@ export const pamAccessRequestServiceFactory = ({
{ type: ApprovalPolicyType.PamAccess, status: ApprovalRequestGrantStatus.Active, projectId },
{ tx }
);
+ const pendingSignals: (() => void)[] = [];
for (const grant of activeGrants) {
const attrs = grant.attributes as { accountId?: string } | null;
if (attrs?.accountId === accountId) {
// eslint-disable-next-line no-await-in-loop
- await revokeGrantRow(grant, actorId, "Account deleted", tx);
+ const { sendCancellationSignals } = await revokeGrantRow(grant, actorId, "Account deleted", tx);
+ pendingSignals.push(sendCancellationSignals);
}
}
+
+ return () => pendingSignals.forEach((send) => send());
};
const checkGrant = async ({
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index b87482a420..be467bace7 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -21,9 +21,10 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
import { testConnectionWithGateway } from "../gateway-v2/gateway-v2-fns";
-import { PamAccessStatus, PamAccountType, PamProductRole } from "../pam/pam-enums";
+import { PamAccessStatus, PamAccountType, PamProductRole, PamSessionStatus } from "../pam/pam-enums";
import {
checkAccountAccess,
checkFolderPermission,
@@ -43,6 +44,8 @@ import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-acces
import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
+import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
+import { terminatePamSessions } from "../pam-session/pam-session-fns";
import { buildGatewayConnectionTest, CLOUD_CONNECTION_VALIDATORS } from "./pam-account-connection-test";
import { TPamAccountDALFactory } from "./pam-account-dal";
import {
@@ -70,13 +73,18 @@ type TPamAccountServiceFactoryDep = {
pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "findById">;
membershipDAL: Pick<TMembershipDALFactory, "find" | "delete" | "findResourceMembershipsForActor">;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "delete" | "find">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "terminateSessionById">;
+ userDAL: Pick<TUserDALFactory, "findById">;
permissionService: Pick<
TPermissionServiceFactory,
"getProjectPermission" | "getResourcePermission" | "getOrgPermission"
>;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2Service: Pick<
+ TGatewayV2ServiceFactory,
+ "getPlatformConnectionDetailsByGatewayId" | "getPAMConnectionDetails"
+ >;
gatewayPoolService: Pick<
TGatewayPoolServiceFactory,
"resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId"
@@ -140,6 +148,8 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
pamAccountTemplateDAL,
membershipDAL,
membershipRoleDAL,
+ pamSessionDAL,
+ userDAL,
permissionService,
kmsService,
gatewayV2Service,
@@ -743,7 +753,11 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
);
try {
- return await pamAccountDAL.transaction(async (tx) => {
+ // Every session cancellation this delete triggers is held back until COMMIT: the delete can still
+ // fail on the rotationAccountId FK guard below, and a cut tunnel can't be brought back.
+ let sendSessionCancellations: (() => void) | undefined;
+
+ const deleted = await pamAccountDAL.transaction(async (tx) => {
const memberships = await membershipDAL.find(
{
scope: RESOURCE_SCOPE,
@@ -761,13 +775,43 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
await pamAccountDAL.updateById(accountId, { rotationAccountId: null }, tx);
- await deps.pamAccessRequestService.cleanupAccountResources(
+ const sendGrantCancellations = await deps.pamAccessRequestService.cleanupAccountResources(
{ accountId, folderId: existing.folderId, projectId, actorId: ctx.actorId },
tx
);
+ // Sweep every live session on the account, not just the ones grant revocation reached: an
+ // account in a folder with no approval policy has no grant rows at all, and a session can be
+ // held by someone who is not a grantee. The account row is about to disappear (pam_sessions
+ // keeps history with a null accountId), so there is no access left to re-evaluate.
+ const liveSessions = await pamSessionDAL.find(
+ { accountId, $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] } },
+ { tx }
+ );
+
+ let sendSweepCancellations: (() => void) | undefined;
+ if (liveSessions.length > 0) {
+ const actor = await userDAL.findById(ctx.actorId, tx);
+ sendSweepCancellations = await terminatePamSessions({
+ sessions: liveSessions,
+ actorId: ctx.actorId,
+ actorEmail: actor?.email ?? "",
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+ }
+
+ sendSessionCancellations = () => {
+ sendGrantCancellations();
+ sendSweepCancellations?.();
+ };
+
return pamAccountDAL.deleteById(accountId, tx);
});
+
+ sendSessionCancellations?.();
+ return deleted;
} catch (err) {
// The ON DELETE RESTRICT FK on rotationAccountId is the race-safe guard; on violation, look up the dependents
// to name them (rather than paying for that lookup on every delete).
diff --git a/backend/src/ee/services/pam-membership/pam-membership-service.ts b/backend/src/ee/services/pam-membership/pam-membership-service.ts
index 3b99334e6b..5736d69e84 100644
--- a/backend/src/ee/services/pam-membership/pam-membership-service.ts
+++ b/backend/src/ee/services/pam-membership/pam-membership-service.ts
@@ -2,7 +2,10 @@ import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
import { AccessScope, ActionProjectType, RESOURCE_SCOPE, ResourceType, TemporaryPermissionMode } 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 { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ResourcePermissionPamResourceActions,
@@ -12,6 +15,7 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/
import { ms } from "@app/lib/ms";
import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
import { ApprovalPolicyScope } from "@app/services/approval-policy/approval-policy-enums";
+import { ActorType } from "@app/services/auth/auth-type";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { PamIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
@@ -24,6 +28,8 @@ import { PamMemberKind, PamProductRole, PamResourceRole } from "../pam/pam-enums
import { getResourceIdsWithActions, TActorContext } from "../pam/pam-permission";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
+import { terminatePamSessionsWithoutLaunchAccess, TPamSessionActor } from "../pam-session/pam-session-access-fns";
+import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
import {
TAddPamAccountMemberDTO,
TAddPamFolderMemberDTO,
@@ -49,11 +55,15 @@ type TPamMembershipServiceFactoryDep = {
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteStepApproversBySubject">;
projectAccessRequestDAL: Pick<TProjectAccessRequestDALFactory, "delete">;
pamFolderDAL: Pick<TPamFolderDALFactory, "findById">;
- pamAccountDAL: Pick<TPamAccountDALFactory, "findById">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "find">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "terminateSessionById">;
userDAL: Pick<TUserDALFactory, "findById" | "find">;
groupDAL: Pick<TGroupDALFactory, "findById">;
identityDAL: Pick<TIdentityDALFactory, "findById" | "find">;
+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
};
@@ -89,10 +99,14 @@ export const pamMembershipServiceFactory = ({
projectAccessRequestDAL,
pamFolderDAL,
pamAccountDAL,
+ pamSessionDAL,
userDAL,
groupDAL,
+ userGroupMembershipDAL,
+ identityGroupMembershipDAL,
identityDAL,
permissionService,
+ gatewayV2Service,
usageMeteringService
}: TPamMembershipServiceFactoryDep) => {
// Shared helpers
@@ -251,6 +265,48 @@ export const pamMembershipServiceFactory = ({
);
};
+ // Removing or demoting a membership does nothing on its own to the sessions the member is already
+ // running, so every path that narrows someone's access closes the sessions that access was holding open.
+ // Call this last inside the membership transaction, so the re-check sees the write; it returns the
+ // tunnel-cancellation callback for the caller to fire after COMMIT.
+ const closeSessionsLosingAccess = async (
+ projectId: string,
+ subject: { userId?: string; groupId?: string; identityId?: string } & TActorContext,
+ tx: Knex
+ ): Promise<() => void> => {
+ const actors: TPamSessionActor[] = [];
+ if (subject.userId) {
+ actors.push({ type: ActorType.USER, id: subject.userId });
+ } else if (subject.identityId) {
+ // Machine identities can launch CLI sessions, so an identity membership has sessions to close too.
+ actors.push({ type: ActorType.IDENTITY, id: subject.identityId });
+ } else if (subject.groupId) {
+ // The group held the membership, so its members are the ones losing access through it — and a group
+ // carries both user and machine-identity members, each inheriting its resource access.
+ const userMembers = await userGroupMembershipDAL.find({ groupId: subject.groupId }, { tx });
+ const identityMembers = await identityGroupMembershipDAL.find({ groupId: subject.groupId }, { tx });
+ actors.push(
+ ...userMembers.map((member) => ({ type: ActorType.USER as const, id: member.userId })),
+ ...identityMembers.map((member) => ({ type: ActorType.IDENTITY as const, id: member.identityId }))
+ );
+ }
+ if (actors.length === 0) return () => {};
+
+ return terminatePamSessionsWithoutLaunchAccess({
+ projectId,
+ orgId: subject.actorOrgId,
+ actors,
+ actorId: subject.actorId,
+ membershipDAL,
+ membershipRoleDAL,
+ pamAccountDAL,
+ pamSessionDAL,
+ userDAL,
+ gatewayV2Service,
+ tx
+ });
+ };
+
const upsertRole = async (membershipId: string, role: string, tx: Knex) => {
const existing = await membershipRoleDAL.find({ membershipId }, { tx });
if (existing.length > 0) {
@@ -550,6 +606,8 @@ export const pamMembershipServiceFactory = ({
}
}
+ let sendSessionCancellations: () => void = () => {};
+
const result = await membershipDAL.transaction(async (tx) => {
const [membership] = await membershipDAL.find(
{ scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
@@ -594,6 +652,9 @@ export const pamMembershipServiceFactory = ({
await membershipDAL.deleteById(membership.id, tx);
+ // Leaving the product cascaded every folder and account membership above, so all launch access is gone.
+ sendSessionCancellations = await closeSessionsLosingAccess(projectId, dto, tx);
+
return {
membershipId: membership.id,
userId: kind === PamMemberKind.User ? id : undefined,
@@ -602,6 +663,8 @@ export const pamMembershipServiceFactory = ({
};
});
+ sendSessionCancellations();
+
usageMeteringService.emitForProject(projectId, PamIdentities.key);
return result;
};
@@ -722,7 +785,9 @@ export const pamMembershipServiceFactory = ({
const { column, id, kind } = resolveActorColumn(dto);
- return membershipDAL.transaction(async (tx) => {
+ let sendSessionCancellations: () => void = () => {};
+
+ const result = await membershipDAL.transaction(async (tx) => {
const [membership] = await membershipDAL.find(
{ ...resourceScope(projectId, resourceType, resourceId), [column]: id },
{ tx }
@@ -735,6 +800,9 @@ export const pamMembershipServiceFactory = ({
await upsertRole(membership.id, role, tx);
+ // A demotion (Connector to Auditor, say) drops LaunchSessions without removing the membership.
+ sendSessionCancellations = await closeSessionsLosingAccess(projectId, dto, tx);
+
return {
membershipId: membership.id,
[resourceKey]: resourceId,
@@ -744,6 +812,10 @@ export const pamMembershipServiceFactory = ({
role
};
});
+
+ sendSessionCancellations();
+
+ return result;
};
const removeResourceMember = async (
@@ -773,11 +845,17 @@ export const pamMembershipServiceFactory = ({
});
}
+ let sendSessionCancellations: () => void = () => {};
+
await membershipDAL.transaction(async (tx) => {
await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
await membershipDAL.deleteById(membership.id, tx);
+
+ sendSessionCancellations = await closeSessionsLosingAccess(projectId, dto, tx);
});
+ sendSessionCancellations();
+
return {
membershipId: membership.id,
[resourceKey]: resourceId,
@@ -850,6 +928,8 @@ export const pamMembershipServiceFactory = ({
});
}
+ let sendSessionCancellations: () => void = () => {};
+
await membershipDAL.transaction(async (tx) => {
await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
await membershipDAL.deleteById(membership.id, tx);
@@ -866,8 +946,13 @@ export const pamMembershipServiceFactory = ({
tx
);
}
+
+ // Folder access reaches every account in the folder, so this can strip launch access on any of them.
+ sendSessionCancellations = await closeSessionsLosingAccess(projectId, dto, tx);
});
+ sendSessionCancellations();
+
return {
membershipId: membership.id,
folderId,
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
new file mode 100644
index 0000000000..0a9504dedf
--- /dev/null
+++ b/backend/src/ee/services/pam-session/pam-session-access-fns.ts
@@ -0,0 +1,163 @@
+import { Knex } from "knex";
+
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
+
+import { PamSessionStatus } from "../pam/pam-enums";
+import { getResourceIdsWithActions } from "../pam/pam-permission";
+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";
+
+// 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
+// the kind alongside the id is what keeps a lookup from silently crossing the two.
+export type TPamSessionActor = { type: ActorType.USER | ActorType.IDENTITY; id: string };
+
+const actorKey = ({ type, id }: TPamSessionActor) => `${type}:${id}`;
+
+// Exactly one actor column is set per session row.
+export const resolveSessionActor = (session: {
+ userId?: string | null;
+ identityId?: string | null;
+}): TPamSessionActor | null => {
+ if (session.identityId) return { type: ActorType.IDENTITY, id: session.identityId };
+ if (session.userId) return { type: ActorType.USER, id: session.userId };
+ return null;
+};
+
+type TLaunchableResources = { folderIds: Set<string>; accountIds: Set<string> };
+
+// Mirrors checkAccountAccess's union: the account's folder carries the action, or a direct membership on
+// the account does. With no resolved memberships at all there is no access.
+export const hasLaunchAccessToAccount = (
+ launchable: TLaunchableResources | undefined,
+ account: { id: string; folderId?: string | null }
+) => {
+ if (!launchable) return false;
+ if (account.folderId && launchable.folderIds.has(account.folderId)) return true;
+ return launchable.accountIds.has(account.id);
+};
+
+type TTerminatePamSessionsWithoutLaunchAccessDTO = {
+ projectId: string;
+ orgId: string;
+ // The actors whose access just changed, users and machine identities alike.
+ actors: TPamSessionActor[];
+ // The admin who made the access change; named as the terminating actor on the gateway signal.
+ actorId: string;
+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "find">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "terminateSessionById">;
+ userDAL: Pick<TUserDALFactory, "findById">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
+ tx: Knex;
+};
+
+/**
+ * Closes the sessions an access change just invalidated, and returns the callback that cuts their tunnels.
+ *
+ * Losing a membership (or being demoted out of a role that carries LaunchSessions) does nothing on its own
+ * to a session that is already running: neither the gateway nor the web-access loop re-checks permissions
+ * mid-session, so a revoked Connector would keep their privileged tunnel until it expired. This re-derives
+ * LaunchSessions for every live session the given actors hold in the project and terminates the ones that
+ * no longer pass. Machine identities count: they can launch CLI sessions, so they lose them the same way.
+ *
+ * Re-deriving beats diffing the membership row that changed: the same launch access can also come from the
+ * account's folder, a second direct membership, or a group, so removing one row does not necessarily end
+ * access.
+ *
+ * Runs inside the caller's membership transaction and reads through `tx` throughout. That is what makes it
+ * correct rather than racy — the check has to see the caller's own uncommitted revocation, which a replica
+ * read would miss, and rolling back the membership change has to roll back the terminations with it. Only
+ * the tunnel-cancellation signals are deferred, since those cannot be undone; the caller fires the returned
+ * callback after COMMIT.
+ */
+export const terminatePamSessionsWithoutLaunchAccess = async ({
+ projectId,
+ orgId,
+ actors,
+ actorId,
+ membershipDAL,
+ membershipRoleDAL,
+ pamAccountDAL,
+ pamSessionDAL,
+ userDAL,
+ gatewayV2Service,
+ tx
+}: TTerminatePamSessionsWithoutLaunchAccessDTO): Promise<() => void> => {
+ const noop = () => {};
+ if (actors.length === 0) return noop;
+
+ const userIds = actors.filter((actor) => actor.type === ActorType.USER).map((actor) => actor.id);
+ const identityIds = actors.filter((actor) => actor.type === ActorType.IDENTITY).map((actor) => actor.id);
+ const liveStatuses = [PamSessionStatus.Active, PamSessionStatus.Starting];
+
+ // Two queries rather than one: the actor columns are mutually exclusive, and ormify's `$in` entries are
+ // ANDed together, so a single filter on both columns would match nothing.
+ const userSessions = userIds.length
+ ? await pamSessionDAL.find({ projectId, $in: { userId: userIds, status: liveStatuses } }, { tx })
+ : [];
+ const identitySessions = identityIds.length
+ ? await pamSessionDAL.find({ projectId, $in: { identityId: identityIds, status: liveStatuses } }, { tx })
+ : [];
+
+ // A session whose account was deleted keeps its history with a null accountId and has no access left to
+ // re-check; the account delete path terminated it already.
+ const sessions = [...userSessions, ...identitySessions].flatMap((session) => {
+ const sessionActor = resolveSessionActor(session);
+ if (!session.accountId || !sessionActor) return [];
+ return [{ ...session, accountId: session.accountId, sessionActor }];
+ });
+ if (sessions.length === 0) return noop;
+
+ const accounts = await pamAccountDAL.find(
+ {
+ projectId,
+ $in: { id: [...new Set(sessions.map((session) => session.accountId))] }
+ },
+ { tx }
+ );
+ const accountById = new Map(accounts.map((account) => [account.id, account]));
+
+ // One membership resolution per actor, not per session, since an actor's grants cover every account.
+ const launchableByActor = new Map<string, TLaunchableResources>();
+ for (const sessionActor of new Map(sessions.map((s) => [actorKey(s.sessionActor), s.sessionActor])).values()) {
+ // eslint-disable-next-line no-await-in-loop
+ const { folderIds, accountIds } = await getResourceIdsWithActions(
+ membershipDAL,
+ membershipRoleDAL,
+ projectId,
+ { allOf: [ResourcePermissionPamResourceActions.LaunchSessions] },
+ { actor: sessionActor.type, actorId: sessionActor.id, actorOrgId: orgId, actorAuthMethod: null },
+ tx
+ );
+ launchableByActor.set(actorKey(sessionActor), {
+ folderIds: new Set(folderIds),
+ accountIds: new Set(accountIds)
+ });
+ }
+
+ const revoked = sessions.filter((session) => {
+ const account = accountById.get(session.accountId);
+ // The account is gone from under the session; its own delete path owns closing it.
+ if (!account) return false;
+ return !hasLaunchAccessToAccount(launchableByActor.get(actorKey(session.sessionActor)), account);
+ });
+ if (revoked.length === 0) return noop;
+
+ const actor = await userDAL.findById(actorId, tx);
+ return terminatePamSessions({
+ sessions: revoked,
+ actorId,
+ actorEmail: actor?.email ?? "",
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+ });
+};
diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.ts
index ae7cd893c4..b942dae43f 100644
--- a/backend/src/ee/services/pam-session/pam-session-fns.ts
+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts
@@ -1,3 +1,4 @@
+import { Knex } from "knex";
import net from "net";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -10,6 +11,7 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { PamAccessMethod, PamAccountType, PamSessionEndReason } from "../pam/pam-enums";
+import { TPamSessionDALFactory } from "./pam-session-dal";
export const resolvePamSessionDistinctId = async ({
session,
@@ -126,3 +128,45 @@ export const sendPamSessionCancellationSignal = ({
}
})();
};
+
+// Flips a set of session rows to terminated and returns the callback that cuts their live tunnels. The
+// two halves are deliberately separate: the row update is undone by a rollback, the ALPN signal is not.
+// A caller inside a transaction that can still fail (account deletion, which can be blocked by the
+// rotationAccountId FK guard) must pass `tx` and invoke the returned callback only after COMMIT, or a
+// failed operation kills privileged tunnels it then claims never to have touched. Callers with no
+// transaction can invoke it immediately.
+export const terminatePamSessions = async ({
+ sessions,
+ actorId,
+ actorEmail,
+ pamSessionDAL,
+ gatewayV2Service,
+ tx
+}: {
+ sessions: { id: string; gatewayId?: string | null; accountType: string }[];
+ actorId: string;
+ actorEmail: string;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "terminateSessionById">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
+ tx?: Knex;
+}) => {
+ for (const session of sessions) {
+ // eslint-disable-next-line no-await-in-loop
+ await pamSessionDAL.terminateSessionById(session.id, tx);
+ }
+
+ return () => {
+ for (const session of sessions) {
+ if (session.gatewayId) {
+ sendPamSessionCancellationSignal({
+ sessionId: session.id,
+ gatewayId: session.gatewayId,
+ accountType: session.accountType,
+ actorId,
+ actorEmail,
+ gatewayV2Service
+ });
+ }
+ }
+ };
+};
diff --git a/backend/src/ee/services/pam/pam-permission.ts b/backend/src/ee/services/pam/pam-permission.ts
index e5733e02ed..827ba510e1 100644
--- a/backend/src/ee/services/pam/pam-permission.ts
+++ b/backend/src/ee/services/pam/pam-permission.ts
@@ -1,5 +1,6 @@
import { createMongoAbility, ForbiddenError, MongoAbility, RawRuleOf } from "@casl/ability";
import { PackRule, packRules } from "@casl/ability/extra";
+import { Knex } from "knex";
import { ActionProjectType, ResourceType } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -101,6 +102,8 @@ export const checkAccountAccess = async (
ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);
};
+// `tx` is for callers that must see their own uncommitted membership writes (revoking access and closing
+// the sessions it was holding open, in one transaction). Without it these are replica reads.
export const getResourceIdsWithActions = async (
membershipDAL: TMembershipDep,
membershipRoleDAL: TMembershipRoleDep,
@@ -109,21 +112,28 @@ export const getResourceIdsWithActions = async (
allOf?: ResourcePermissionPamResourceActions[];
anyOf?: ResourcePermissionPamResourceActions[];
},
- ctx: TActorContext
+ ctx: TActorContext,
+ tx?: Knex
) => {
const [folderMemberships, accountMemberships] = await Promise.all([
- membershipDAL.findResourceMembershipsForActor({
- projectId,
- resourceType: ResourceType.PamFolder,
- actorType: ctx.actor,
- actorId: ctx.actorId
- }),
- membershipDAL.findResourceMembershipsForActor({
- projectId,
- resourceType: ResourceType.PamAccount,
- actorType: ctx.actor,
- actorId: ctx.actorId
- })
+ membershipDAL.findResourceMembershipsForActor(
+ {
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ },
+ tx
+ ),
+ membershipDAL.findResourceMembershipsForActor(
+ {
+ projectId,
+ resourceType: ResourceType.PamAccount,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ },
+ tx
+ )
]);
const activeFolderMemberships = folderMemberships.filter((m) => m.isActive);
@@ -134,9 +144,12 @@ export const getResourceIdsWithActions = async (
return { folderIds: [], accountIds: [] };
}
- const roles = await membershipRoleDAL.find({
- $in: { membershipId: allMemberships.map((m) => m.id) }
- });
+ const roles = await membershipRoleDAL.find(
+ {
+ $in: { membershipId: allMemberships.map((m) => m.id) }
+ },
+ { tx }
+ );
const now = new Date();
const activeRoles = roles.filter(
(r) => !r.isTemporary || (r.temporaryAccessEndTime && now < new Date(r.temporaryAccessEndTime))
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 93a4659c9d..b9fa2ab560 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1720,20 +1720,6 @@ export const registerRoutes = async (
const pamFolderDAL = pamFolderDALFactory(db);
const pamFolderNotificationConfigDAL = pamFolderNotificationConfigDALFactory(db);
- const pamMembershipService = pamMembershipServiceFactory({
- membershipDAL,
- membershipRoleDAL,
- approvalPolicyDAL,
- projectAccessRequestDAL,
- pamFolderDAL,
- pamAccountDAL,
- userDAL,
- groupDAL,
- identityDAL,
- permissionService,
- usageMeteringService
- });
-
const certManagerInstanceService = certManagerInstanceServiceFactory({
db,
orgDAL,
@@ -1859,6 +1845,26 @@ export const registerRoutes = async (
const pamSessionDAL = pamSessionDALFactory(db);
const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);
+ // Wired after pamSessionDAL/gatewayV2Service: narrowing a member's access has to close the PAM
+ // sessions that access was holding open.
+ const pamMembershipService = pamMembershipServiceFactory({
+ membershipDAL,
+ membershipRoleDAL,
+ approvalPolicyDAL,
+ projectAccessRequestDAL,
+ pamFolderDAL,
+ pamAccountDAL,
+ pamSessionDAL,
+ userDAL,
+ groupDAL,
+ userGroupMembershipDAL,
+ identityGroupMembershipDAL,
+ identityDAL,
+ permissionService,
+ gatewayV2Service,
+ usageMeteringService
+ });
+
const pamSessionExpirationService = pamSessionExpirationServiceFactory({
queueService,
pamSessionDAL,
@@ -1911,6 +1917,8 @@ export const registerRoutes = async (
pamAccountTemplateDAL,
membershipDAL,
membershipRoleDAL,
+ pamSessionDAL,
+ userDAL,
permissionService,
kmsService,
gatewayV2DAL,
diff --git a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
index ae54eed367..7e5f24e953 100644
--- a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
+++ b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
@@ -46,18 +46,22 @@ export const registerApprovalPolicyEndpoints = ({
requestResponseSchema,
grantResponseSchema,
inputsSchema,
- checkPolicyMatchResponseSchema
+ checkPolicyMatchResponseSchema,
+ allowRequestCreation = true
}: {
server: FastifyZodProvider;
policyType: ApprovalPolicyType;
createPolicySchema: TCreatePolicySchema;
updatePolicySchema: TUpdatePolicySchema;
policyResponseSchema: z.ZodObject<z.ZodRawShape>;
- createRequestSchema: z.ZodType<TCreateRequestDTO>;
+ createRequestSchema?: z.ZodType<TCreateRequestDTO>;
requestResponseSchema: z.ZodObject<z.ZodRawShape>;
grantResponseSchema: z.ZodObject<z.ZodRawShape>;
inputsSchema: z.ZodType<TApprovalPolicyInputs>;
checkPolicyMatchResponseSchema: z.ZodObject<z.ZodRawShape>;
+ // Whether callers may open an approval request directly. Policy types whose requests are
+ // only ever created server-side, as part of the flow being gated, must leave this off.
+ allowRequestCreation?: boolean;
}) => {
// Policies
server.route({
@@ -331,67 +335,73 @@ export const registerApprovalPolicyEndpoints = ({
}
});
- server.route({
- method: "POST",
- url: "/requests",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: "createApprovalRequest",
- description: "Create approval request",
- body: createRequestSchema,
- response: {
- 200: z.object({
- request: requestResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- let requesterName: string;
- let requesterEmail: string;
- let machineIdentityId: string | undefined;
-
- if (req.auth.authMode === AuthMode.JWT) {
- requesterName = `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim();
- requesterEmail = req.auth.user.email ?? "";
- } else if (req.auth.authMode === AuthMode.IDENTITY_ACCESS_TOKEN) {
- requesterName = req.auth.identityName ?? "Machine Identity";
- requesterEmail = "";
- machineIdentityId = req.auth.identityId;
- } else {
- throw new BadRequestError({ message: "Unsupported auth mode for approval requests." });
- }
+ if (allowRequestCreation) {
+ if (!createRequestSchema) {
+ throw new Error(`createRequestSchema is required when request creation is enabled for ${policyType}`);
+ }
- const { request } = await server.services.approvalPolicy.createRequest(
- policyType,
- {
- requesterName,
- requesterEmail,
- machineIdentityId,
- ...req.body
- },
- req.permission
- );
+ server.route({
+ method: "POST",
+ url: "/requests",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "createApprovalRequest",
+ description: "Create approval request",
+ body: createRequestSchema,
+ response: {
+ 200: z.object({
+ request: requestResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ let requesterName: string;
+ let requesterEmail: string;
+ let machineIdentityId: string | undefined;
+
+ if (req.auth.authMode === AuthMode.JWT) {
+ requesterName = `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim();
+ requesterEmail = req.auth.user.email ?? "";
+ } else if (req.auth.authMode === AuthMode.IDENTITY_ACCESS_TOKEN) {
+ requesterName = req.auth.identityName ?? "Machine Identity";
+ requesterEmail = "";
+ machineIdentityId = req.auth.identityId;
+ } else {
+ throw new BadRequestError({ message: "Unsupported auth mode for approval requests." });
+ }
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: request.projectId,
- event: {
- type: EventType.APPROVAL_REQUEST_CREATE,
- metadata: {
- policyType,
- justification: req.body.justification || undefined,
- requestDuration: req.body.requestDuration || "infinite"
+ const { request } = await server.services.approvalPolicy.createRequest(
+ policyType,
+ {
+ requesterName,
+ requesterEmail,
+ machineIdentityId,
+ ...req.body
+ },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: request.projectId,
+ event: {
+ type: EventType.APPROVAL_REQUEST_CREATE,
+ metadata: {
+ policyType,
+ justification: req.body.justification || undefined,
+ requestDuration: req.body.requestDuration || "infinite"
+ }
}
- }
- });
+ });
- return { request };
- }
- });
+ return { request };
+ }
+ });
+ }
server.route({
method: "GET",
diff --git a/backend/src/server/routes/v1/approval-policy-routers/index.ts b/backend/src/server/routes/v1/approval-policy-routers/index.ts
index 00d2ccd3a8..980a1e9fe0 100644
--- a/backend/src/server/routes/v1/approval-policy-routers/index.ts
+++ b/backend/src/server/routes/v1/approval-policy-routers/index.ts
@@ -6,7 +6,6 @@ import {
CertRequestRequestGrantSchema,
CertRequestRequestSchema,
CreateCertRequestPolicySchema,
- CreateCertRequestRequestSchema,
UpdateCertRequestPolicySchema
} from "@app/services/approval-policy/cert-request/cert-request-policy-schemas";
import {
@@ -32,11 +31,17 @@ export const APPROVAL_POLICY_REGISTER_ROUTER_MAP: Partial<
createPolicySchema: CreateCertRequestPolicySchema,
updatePolicySchema: UpdateCertRequestPolicySchema,
policyResponseSchema: CertRequestPolicySchema,
- createRequestSchema: CreateCertRequestRequestSchema,
requestResponseSchema: CertRequestRequestSchema,
grantResponseSchema: CertRequestRequestGrantSchema,
inputsSchema: CertRequestPolicyInputsSchema,
- checkPolicyMatchResponseSchema: BaseCheckPolicyMatchResponseSchema
+ checkPolicyMatchResponseSchema: BaseCheckPolicyMatchResponseSchema,
+ // Certificate approval requests are only ever opened server-side by the issuance flow
+ // (certificate-v3-service -> createRequestFromPolicy), atomically with the certificate
+ // request row they gate. There is no caller-driven path: a request cannot be opened
+ // before its certificate request row exists, and once it exists the row already carries
+ // its own approval request. Exposing creation would let a caller pick which policy gates
+ // a certificate request they did not create, so it stays off.
+ allowRequestCreation: false
});
},
[ApprovalPolicyType.CertCodeSigning]: async (server: FastifyZodProvider) => {
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-fns.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-fns.ts
index adb502df96..30443e40d5 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-fns.ts
@@ -32,6 +32,7 @@ import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";
import { CaStatus } from "../certificate-authority-enums";
import {
buildCrlDistributionPointUrls,
+ createDistinguishedName,
createSerialNumber,
getCaCertChain,
getCaCredentials,
@@ -125,7 +126,7 @@ export const InternalCertificateAuthorityFns = ({
: x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment;
const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
- name: `CN=${subscriber.commonName}`,
+ name: createDistinguishedName({ commonName: subscriber.commonName }),
keys: leafKeys,
signingAlgorithm: alg,
extensions: [new x509.KeyUsagesExtension(csrKeyUsages)],
@@ -378,7 +379,7 @@ export const InternalCertificateAuthorityFns = ({
: x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment;
const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
- name: `CN=${commonName}`,
+ name: createDistinguishedName({ commonName }),
keys: leafKeys,
signingAlgorithm: alg,
extensions: [new x509.KeyUsagesExtension(templateCsrKeyUsages)],
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index fc9b631a1c..e0d57472da 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -230,7 +230,11 @@ export const internalCertificateAuthorityServiceFactory = ({
pathLength?: number | null;
caCertObj: x509.X509Certificate;
}): x509.BasicConstraintsExtension => {
- const shouldIssueCaCertificate = basicConstraints !== undefined && basicConstraints !== null;
+ // Decide from the value, never from presence. An explicit { isCA: false } reaches here from stored
+ // certificate requests and CSR-derived constraints, and every upstream policy gate keys on
+ // isCA === true. Treating a present-but-false object as a CA request would stamp a critical
+ // CA:TRUE extension onto a request that asked for a leaf and that no gate had cause to reject.
+ const shouldIssueCaCertificate = basicConstraints?.isCA === true;
if (!shouldIssueCaCertificate) {
return new x509.BasicConstraintsExtension(false);