Skip to content

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

fix(pam): address review feedback on access request approvals

bernie-g1133cea3384c
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index fdb553d772..b56dde0606 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -35,12 +35,12 @@ import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-con
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TLicenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2-service";
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
+import { TPamAccessRequestServiceFactory } from "@app/ee/services/pam-access-request/pam-access-request-service";
import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";
import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
import { TPamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";
import { TPamProjectResolverFactory } from "@app/ee/services/pam-project/pam-project-resolver";
-import { TPamAccessRequestServiceFactory } from "@app/ee/services/pam-access-request/pam-access-request-service";
import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
import { TPamSessionChunkServiceFactory } from "@app/ee/services/pam-session-recording/pam-recording-chunk-service";
import { TPamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";
diff --git a/backend/src/db/migrations/20260612142201_pam-revamp.ts b/backend/src/db/migrations/20260612142201_pam-revamp.ts
index d7e17f1555..e06eba1d34 100644
--- a/backend/src/db/migrations/20260612142201_pam-revamp.ts
+++ b/backend/src/db/migrations/20260612142201_pam-revamp.ts
@@ -380,6 +380,7 @@ export async function up(knex: Knex): Promise<void> {
// Migrated non-admins get product membership only (no standing folder/account access); they
// request access through the approval flow. Only old-project admins keep a folder-Admin
// membership so the migrated folder remains manageable.
+ // eslint-disable-next-line no-continue
if (!isAdmin) continue;
const [folderMembership] = await knex(TableName.Membership)
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
index dd5f31ba25..91d92c0d0a 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
@@ -396,10 +396,10 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
accountType: true
}).extend({
canLaunch: z.boolean().describe("Whether the caller can launch a session for this account"),
- requiresApproval: z.boolean().describe("Whether this account requires approval before launching a session"),
- accessStatus: z
- .enum(["none", "pending", "granted"])
- .describe("Current approval status for the caller"),
+ requiresApproval: z
+ .boolean()
+ .describe("Whether this account requires approval before launching a session"),
+ accessStatus: z.enum(["none", "pending", "granted"]).describe("Current approval status for the caller"),
grantExpiresAt: z.date().nullable().describe("When the current grant expires, if granted"),
disabledReason: z.string().nullable().describe("Why this account is disabled, or null if usable")
})
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 99257cd3ca..e116b553d4 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
@@ -1,4 +1,5 @@
import { ForbiddenError } from "@casl/ability";
+import { Knex } from "knex";
import { RESOURCE_SCOPE, ResourceType, TApprovalRequestGrants } from "@app/db/schemas";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
@@ -11,7 +12,6 @@ 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 { OrgServiceActor } from "@app/lib/types";
import {
TApprovalPolicyDALFactory,
TApprovalPolicyStepApproversDALFactory,
@@ -38,15 +38,20 @@ import {
notifyApproversForStep
} from "@app/services/approval-policy/approval-request-fns";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
-import { NotificationType } from "@app/services/notification/notification-types";
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 { resolveAccountByPath } from "../pam/pam-fns";
-import { checkAccountAccess, checkFolderPermission, TActorContext, verifyProductMembership } from "../pam/pam-permission";
+import {
+ checkAccountAccess,
+ checkFolderPermission,
+ TActorContext,
+ verifyProductMembership
+} from "../pam/pam-permission";
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";
@@ -88,6 +93,7 @@ type TPamAccessRequestServiceFactoryDep = {
| "findById"
| "findByIdForUpdate"
| "create"
+ | "update"
| "updateById"
| "transaction"
| "findStepsByRequestId"
@@ -102,6 +108,7 @@ type TPamAccessRequestServiceFactoryDep = {
pamFolderDAL: Pick<TPamFolderDALFactory, "findById" | "find" | "findOne">;
pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "terminateSessionById">;
membershipDAL: Pick<TMembershipDALFactory, "find">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
projectDAL: Pick<TProjectDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
@@ -126,6 +133,7 @@ export const pamAccessRequestServiceFactory = ({
pamFolderDAL,
pamSessionDAL,
membershipDAL,
+ membershipRoleDAL,
projectDAL,
permissionService,
notificationService,
@@ -173,6 +181,27 @@ export const pamAccessRequestServiceFactory = ({
return new Set(memberships.map((m) => m.groupId));
};
+ // Temporary membership expiry is enforced lazily (rows are not deleted when access lapses), so
+ // approver eligibility must filter to memberships that still carry an active role.
+ const findActiveFolderMemberships = async (projectId: string, folderId: string) => {
+ const memberships = await membershipDAL.find({
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.PamFolder,
+ scopeResourceId: folderId
+ });
+ if (!memberships.length) return [];
+
+ const roles = await membershipRoleDAL.find({ $in: { membershipId: memberships.map((m) => m.id) } });
+ const now = new Date();
+ const activeMembershipIds = new Set(
+ roles
+ .filter((r) => !r.isTemporary || (r.temporaryAccessEndTime && now < new Date(r.temporaryAccessEndTime)))
+ .map((r) => r.membershipId)
+ );
+ return memberships.filter((m) => m.isActive && activeMembershipIds.has(m.id));
+ };
+
const enrichRequestsWithNames = async <T extends { requestData?: unknown }>(requests: T[]) => {
const accountIds = new Set<string>();
const folderIds = new Set<string>();
@@ -220,7 +249,9 @@ export const pamAccessRequestServiceFactory = ({
const grantByRequestId = new Map<string, { expiresAt: Date | null; status: string }>();
grants
.filter((g) => g.requestId)
- .forEach((g) => grantByRequestId.set(g.requestId as string, { expiresAt: g.expiresAt ?? null, status: g.status }));
+ .forEach((g) =>
+ grantByRequestId.set(g.requestId as string, { expiresAt: g.expiresAt ?? null, status: g.status })
+ );
return requests.map((r) => {
const grant = grantByRequestId.get(r.id);
@@ -260,17 +291,12 @@ export const pamAccessRequestServiceFactory = ({
throw new BadRequestError({ message: "Phase 1 only supports a single approval step" });
}
- // Approvers must be members of the folder. This keeps the approver list in sync with membership so
- // that removing someone from the folder (which strips their approver rows) can't be circumvented by
- // designating a non-member as an approver.
+ // Approvers must be active members of the folder. This keeps the approver list in sync with
+ // membership so that removing someone from the folder (which strips their approver rows) can't be
+ // circumvented by designating a non-member or expired member as an approver.
const requestedApprovers = steps.flatMap((s) => s.approvers);
if (requestedApprovers.length > 0) {
- const memberships = await membershipDAL.find({
- scope: RESOURCE_SCOPE,
- scopeProjectId: projectId,
- scopeResourceType: ResourceType.PamFolder,
- scopeResourceId: folderId
- });
+ const memberships = await findActiveFolderMemberships(projectId, folderId);
const memberUserIds = new Set(memberships.map((m) => m.actorUserId).filter(Boolean));
const memberGroupIds = new Set(memberships.map((m) => m.actorGroupId).filter(Boolean));
@@ -302,7 +328,8 @@ export const pamAccessRequestServiceFactory = ({
await approvalPolicyDAL.transaction(async (tx) => {
await approvalPolicyStepsDAL.delete({ policyId: existingPolicy.id }, tx);
- for (let i = 0; i < steps.length; i++) {
+ for (let i = 0; i < steps.length; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
const newStep = await approvalPolicyStepsDAL.create(
{
policyId: existingPolicy.id,
@@ -314,6 +341,7 @@ export const pamAccessRequestServiceFactory = ({
);
for (const approver of steps[i].approvers) {
+ // eslint-disable-next-line no-await-in-loop
await approvalPolicyStepApproversDAL.create(
{
policyStepId: newStep.id,
@@ -345,7 +373,8 @@ export const pamAccessRequestServiceFactory = ({
tx
);
- for (let i = 0; i < steps.length; i++) {
+ for (let i = 0; i < steps.length; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
const step = await approvalPolicyStepsDAL.create(
{
policyId: policy.id,
@@ -357,6 +386,7 @@ export const pamAccessRequestServiceFactory = ({
);
for (const approver of steps[i].approvers) {
+ // eslint-disable-next-line no-await-in-loop
await approvalPolicyStepApproversDAL.create(
{
policyStepId: step.id,
@@ -442,9 +472,17 @@ export const pamAccessRequestServiceFactory = ({
}
const policySteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);
+
+ // A step with no approvers can never be reviewed, wedging the request forever. The dashboard hides
+ // the request action in this case, but that guard must also hold for the CLI and direct API callers.
+ if (policySteps.length === 0 || policySteps.some((s) => s.approvers.length === 0)) {
+ throw new BadRequestError({ message: "This folder's approval policy has no approvers configured" });
+ }
+
const stepsForRequest = policySteps.map((s) => ({
name: s.name ?? null,
requiredApprovals: s.requiredApprovals,
+ notifyApprovers: s.notifyApprovers ?? true,
approvers: s.approvers
}));
@@ -493,9 +531,7 @@ export const pamAccessRequestServiceFactory = ({
try {
const approverUserIds = new Set<string>();
- firstStep.approvers
- .filter((a) => a.type === ApproverType.User)
- .forEach((a) => approverUserIds.add(a.id));
+ firstStep.approvers.filter((a) => a.type === ApproverType.User).forEach((a) => approverUserIds.add(a.id));
const groupMemberLists = await Promise.all(
firstStep.approvers
@@ -504,8 +540,7 @@ export const pamAccessRequestServiceFactory = ({
);
groupMemberLists.forEach((members) => members.forEach((m) => approverUserIds.add(m.userId)));
- const approverUsers =
- approverUserIds.size > 0 ? await userDAL.find({ $in: { id: [...approverUserIds] } }) : [];
+ const approverUsers = approverUserIds.size > 0 ? await userDAL.find({ $in: { id: [...approverUserIds] } }) : [];
const recipients = approverUsers.filter((u) => u.email).map((u) => u.email as string);
if (recipients.length > 0) {
@@ -576,30 +611,22 @@ export const pamAccessRequestServiceFactory = ({
const userGroupIds = await getUserGroupIds(ctx.actorId, ctx.actorOrgId);
- // Only requests still awaiting a response belong in an approver's queue.
- const filter: Record<string, unknown> = {
- type: ApprovalPolicyType.PamAccess,
- projectId,
- status: ApprovalRequestStatus.Pending
- };
+ const requests = await approvalRequestDAL.findByProjectId(ApprovalPolicyType.PamAccess, projectId);
- const requests = await approvalRequestDAL.find(filter);
+ // Only requests still awaiting a response belong in an approver's queue.
+ const result = requests.filter((request) => {
+ if (request.status !== ApprovalRequestStatus.Pending) return false;
- const result = [];
- for (const request of requests) {
if (folderId) {
const data = request.requestData as { version: number; requestData: TPamAccessRequestData } | null;
- if (data?.requestData?.folderId !== folderId) continue;
+ if (data?.requestData?.folderId !== folderId) return false;
}
- const steps = await approvalRequestDAL.findStepsByRequestId(request.id);
- const currentStep = steps.find((s) => s.stepNumber === request.currentStep);
- if (!currentStep) continue;
+ const currentStep = request.steps.find((s) => s.stepNumber === request.currentStep);
+ if (!currentStep) return false;
- if (isUserEligibleApprover(currentStep.approvers, ctx.actorId, userGroupIds)) {
- result.push({ ...request, steps });
- }
- }
+ return isUserEligibleApprover(currentStep.approvers, ctx.actorId, userGroupIds);
+ });
return { requests: await attachGrantExpiry(await enrichRequestsWithNames(result)) };
};
@@ -689,6 +716,16 @@ export const pamAccessRequestServiceFactory = ({
if (!isCurrentApprover) {
throw new ForbiddenRequestError({ message: "You are no longer an eligible approver for this folder" });
}
+
+ // Approver rows are only stripped on explicit removal from the folder, not when a temporary
+ // membership lapses, so re-check that the actor still holds an active folder membership.
+ const activeMemberships = await findActiveFolderMemberships(projectId, folderId);
+ const hasActiveMembership = activeMemberships.some(
+ (m) => m.actorUserId === ctx.actorId || (m.actorGroupId && userGroupIds.has(m.actorGroupId))
+ );
+ if (!hasActiveMembership) {
+ throw new ForbiddenRequestError({ message: "You are no longer an eligible approver for this folder" });
+ }
}
const hasAlreadyReviewed = currentStep.approvals.some(
@@ -825,6 +862,41 @@ export const pamAccessRequestServiceFactory = ({
return { request: updatedRequest };
};
+ // 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.
+ const revokeGrantRow = async (
+ grant: TApprovalRequestGrants,
+ actorId: string,
+ reason: string,
+ tx?: Knex
+ ): Promise<TApprovalRequestGrants> => {
+ const revoked = await approvalRequestGrantsDAL.updateById(
+ grant.id,
+ {
+ status: ApprovalRequestGrantStatus.Revoked,
+ revokedByUserId: actorId,
+ revokedAt: new Date(),
+ revocationReason: reason
+ },
+ tx
+ );
+
+ 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" },
+ { tx }
+ );
+ for (const session of activeSessions) {
+ // eslint-disable-next-line no-await-in-loop
+ await pamSessionDAL.terminateSessionById(session.id, tx);
+ }
+ }
+
+ return revoked;
+ };
+
const revokeGrant = async ({ requestId, projectId, ...ctx }: TRevokeAccessRequestDTO) => {
const { hasRole } = await verifyProductMembership(permissionService, projectId, ctx);
@@ -861,28 +933,80 @@ export const pamAccessRequestServiceFactory = ({
throw new ForbiddenRequestError({ message: "You are not authorized to revoke this grant" });
}
- const revokedGrant = await approvalRequestGrantsDAL.updateById(grant.id, {
- status: ApprovalRequestGrantStatus.Revoked,
- revokedByUserId: ctx.actorId,
- revokedAt: new Date(),
- revocationReason: "Revoked by admin"
- });
+ const revokedGrant = await revokeGrantRow(grant, ctx.actorId, "Revoked by admin");
- // An undefined userId in the filter would throw in knex; granteeUserId is null when the
- // grantee user was deleted, and their sessions carry a null userId too
- if (accountId) {
- const activeSessions = await pamSessionDAL.find({
- accountId,
- userId: grant.granteeUserId ?? null,
- status: "active"
- });
+ return { grant: revokedGrant };
+ };
- for (const session of activeSessions) {
- await pamSessionDAL.terminateSessionById(session.id);
+ // Approval policies, requests, and grants reference folders/accounts by scopeId or by a JSON id
+ // with no FK, so deleting a folder or account leaves them orphaned. These run inside the folder/
+ // account delete transaction to keep the approval state consistent.
+
+ const cleanupFolderResources = async (folderId: string, tx: Knex) => {
+ // Deleting the policy cascades to its steps and approvers, which also stops the now-defunct
+ // folder from keeping its approvers "active" for approver-eligibility scans.
+ const policy = await approvalPolicyDAL.findOne(
+ { type: ApprovalPolicyType.PamAccess, scopeType: PAM_FOLDER_SCOPE_TYPE, scopeId: folderId },
+ tx
+ );
+ if (policy) {
+ await approvalPolicyDAL.deleteById(policy.id, tx);
+ }
+
+ await approvalRequestDAL.update(
+ {
+ type: ApprovalPolicyType.PamAccess,
+ scopeType: PAM_FOLDER_SCOPE_TYPE,
+ scopeId: folderId,
+ status: ApprovalRequestStatus.Pending
+ },
+ { status: ApprovalRequestStatus.Cancelled },
+ tx
+ );
+ };
+
+ const cleanupAccountResources = async (
+ {
+ accountId,
+ folderId,
+ projectId,
+ actorId
+ }: { accountId: string; folderId: string | null | undefined; projectId: string; actorId: string },
+ tx: Knex
+ ) => {
+ // Requests are folder-scoped with the account id in requestData JSON, so filter in memory.
+ if (folderId) {
+ const pending = await approvalRequestDAL.find(
+ {
+ type: ApprovalPolicyType.PamAccess,
+ scopeType: PAM_FOLDER_SCOPE_TYPE,
+ scopeId: folderId,
+ status: ApprovalRequestStatus.Pending
+ },
+ { tx }
+ );
+ const staleIds = pending
+ .filter((r) => {
+ const data = r.requestData as { version: number; requestData: TPamAccessRequestData } | null;
+ return data?.requestData?.accountId === accountId;
+ })
+ .map((r) => r.id);
+ if (staleIds.length > 0) {
+ await approvalRequestDAL.update({ $in: { id: staleIds } }, { status: ApprovalRequestStatus.Cancelled }, tx);
}
}
- return { grant: revokedGrant };
+ const activeGrants = await approvalRequestGrantsDAL.find(
+ { type: ApprovalPolicyType.PamAccess, status: ApprovalRequestGrantStatus.Active, projectId },
+ { tx }
+ );
+ 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 checkGrant = async ({
@@ -925,9 +1049,9 @@ export const pamAccessRequestServiceFactory = ({
});
for (const grant of activeGrants) {
- if (grant.expiresAt && new Date(grant.expiresAt) <= now) continue;
+ const isExpired = Boolean(grant.expiresAt && new Date(grant.expiresAt) <= now);
const attrs = grant.attributes as { accountId?: string } | null;
- if (attrs?.accountId && accountIds.includes(attrs.accountId)) {
+ if (!isExpired && attrs?.accountId && accountIds.includes(attrs.accountId)) {
result.set(attrs.accountId, {
accessStatus: "granted",
grantExpiresAt: grant.expiresAt ? new Date(grant.expiresAt) : null
@@ -976,6 +1100,8 @@ export const pamAccessRequestServiceFactory = ({
revokeGrant,
checkGrant,
getAccessStatusBatch,
- getFolderPolicyConfigured
+ getFolderPolicyConfigured,
+ cleanupFolderResources,
+ cleanupAccountResources
};
};
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 bb2122cadb..f3752f12ef 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -35,9 +35,9 @@ import {
validateGatewayAttachment,
validateRecordingConnection
} from "../pam/pam-validators";
+import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
-import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { TPamAccountDALFactory } from "./pam-account-dal";
import {
getAccountAccessibilityIssues,
@@ -74,7 +74,7 @@ type TPamAccountServiceFactoryDep = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findOne" | "findById">;
pamAccessRequestService: Pick<
TPamAccessRequestServiceFactory,
- "getAccessStatusBatch" | "getFolderPolicyConfigured"
+ "getAccessStatusBatch" | "getFolderPolicyConfigured" | "cleanupAccountResources"
>;
};
@@ -483,6 +483,11 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
await membershipDAL.delete({ $in: { id: ids } }, tx);
}
+ await deps.pamAccessRequestService.cleanupAccountResources(
+ { accountId, folderId: existing.folderId, projectId, actorId: ctx.actorId },
+ tx
+ );
+
return pamAccountDAL.deleteById(accountId, tx);
});
};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-service.ts b/backend/src/ee/services/pam-folder/pam-folder-service.ts
index 133121cab0..5d0a75adb9 100644
--- a/backend/src/ee/services/pam-folder/pam-folder-service.ts
+++ b/backend/src/ee/services/pam-folder/pam-folder-service.ts
@@ -15,6 +15,7 @@ import { TMembershipRoleDALFactory } from "@app/services/membership/membership-r
import { PamProductRole, PamResourceRole } from "../pam/pam-enums";
import { getResourceIdsWithActions, TActorContext, verifyProductMembership } from "../pam/pam-permission";
+import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { TPamFolderDALFactory } from "./pam-folder-dal";
import {
TCreatePamFolderDTO,
@@ -32,6 +33,7 @@ type TPamFolderServiceFactoryDep = {
>;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "delete" | "find">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+ pamAccessRequestService: Pick<TPamAccessRequestServiceFactory, "cleanupFolderResources">;
};
export type TPamFolderServiceFactory = ReturnType<typeof pamFolderServiceFactory>;
@@ -40,7 +42,8 @@ export const pamFolderServiceFactory = ({
pamFolderDAL,
membershipDAL,
membershipRoleDAL,
- permissionService
+ permissionService,
+ pamAccessRequestService
}: TPamFolderServiceFactoryDep) => {
const verifyMembership = (projectId: string, ctx: TActorContext) =>
verifyProductMembership(permissionService, projectId, ctx);
@@ -187,6 +190,8 @@ export const pamFolderServiceFactory = ({
await membershipDAL.delete({ $in: { id: ids } }, tx);
}
+ await pamAccessRequestService.cleanupFolderResources(folderId, tx);
+
return pamFolderDAL.deleteById(folderId, tx);
});
};
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 e0c87562ee..b111f5ab82 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -38,6 +38,7 @@ import {
resolvePolicy,
splitPatternString
} from "../pam/pam-policies";
+import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import {
buildSessionGatewayConnectionDetails,
@@ -53,7 +54,6 @@ import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";
import { generateSessionRecordingSecrets } from "../pam-session-recording/pam-recording-secrets";
import { ResourcePermissionPamResourceActions } from "../permission/resource-permission";
-import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import {
AWS_STS_MIN_DURATION_SECONDS,
exchangeCredentialsForConsoleUrl,
@@ -412,14 +412,17 @@ export const pamSessionServiceFactory = ({
message: "Access request required"
});
}
- const grantRemainingMs = new Date(grant.expiresAt!).getTime() - Date.now();
- if (grantRemainingMs <= 0) {
- throw new ForbiddenRequestError({
- name: "PAM_APPROVAL_REQUIRED",
- message: "Access grant has expired"
- });
+ // A null expiresAt means a never-expiring grant per the checkGrant contract
+ if (grant.expiresAt) {
+ const grantRemainingMs = new Date(grant.expiresAt).getTime() - Date.now();
+ if (grantRemainingMs <= 0) {
+ throw new ForbiddenRequestError({
+ name: "PAM_APPROVAL_REQUIRED",
+ message: "Access grant has expired"
+ });
+ }
+ sessionDurationMs = Math.min(sessionDurationMs, grantRemainingMs);
}
- sessionDurationMs = Math.min(sessionDurationMs, grantRemainingMs);
}
// AWS IAM: no gateway, no proxy -- generate STS credentials directly
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
index fcadb5f68b..90ed048fb8 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
@@ -189,9 +189,12 @@ export const pamWebAccessServiceFactory = ({
if (!grant) {
throw new ForbiddenRequestError({ name: "PAM_APPROVAL_REQUIRED", message: "Access request required" });
}
- grantRemainingMs = new Date(grant.expiresAt!).getTime() - Date.now();
- if (grantRemainingMs <= 0) {
- throw new ForbiddenRequestError({ name: "PAM_APPROVAL_REQUIRED", message: "Access grant has expired" });
+ // A null expiresAt means a never-expiring grant per the checkGrant contract
+ if (grant.expiresAt) {
+ grantRemainingMs = new Date(grant.expiresAt).getTime() - Date.now();
+ if (grantRemainingMs <= 0) {
+ throw new ForbiddenRequestError({ name: "PAM_APPROVAL_REQUIRED", message: "Access grant has expired" });
+ }
}
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index affc78beed..8eaad67730 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1650,13 +1650,6 @@ export const registerRoutes = async (
const pamAccountTemplateDAL = pamAccountTemplateDALFactory(db);
const pamFolderDAL = pamFolderDALFactory(db);
- const pamFolderService = pamFolderServiceFactory({
- pamFolderDAL,
- membershipDAL,
- membershipRoleDAL,
- permissionService
- });
-
const pamMembershipService = pamMembershipServiceFactory({
membershipDAL,
membershipRoleDAL,
@@ -1825,6 +1818,7 @@ export const registerRoutes = async (
pamFolderDAL,
pamSessionDAL,
membershipDAL,
+ membershipRoleDAL,
projectDAL,
permissionService,
notificationService,
@@ -1833,6 +1827,14 @@ export const registerRoutes = async (
userDAL
});
+ const pamFolderService = pamFolderServiceFactory({
+ pamFolderDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService,
+ pamAccessRequestService
+ });
+
const pamAccountService = pamAccountServiceFactory({
pamAccountDAL,
pamFolderDAL,
diff --git a/backend/src/services/approval-policy/approval-request-dal.ts b/backend/src/services/approval-policy/approval-request-dal.ts
index 19a2023351..d37205b5ab 100644
--- a/backend/src/services/approval-policy/approval-request-dal.ts
+++ b/backend/src/services/approval-policy/approval-request-dal.ts
@@ -1,7 +1,7 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TApprovalRequestApprovals } from "@app/db/schemas";
+import { TableName, TApprovalRequestApprovals, TApprovalRequestSteps } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
@@ -11,7 +11,6 @@ import {
ApprovalRequestStatus,
ApproverType
} from "./approval-policy-enums";
-import { ApprovalPolicyStep } from "./approval-policy-types";
// Approval Request
export type TApprovalRequestDALFactory = ReturnType<typeof approvalRequestDALFactory>;
@@ -98,7 +97,13 @@ export const approvalRequestDALFactory = (db: TDbClient) => {
.whereIn("requestId", requestIds)
.orderBy("stepNumber", "asc");
- const stepsByRequestId: Record<string, ApprovalPolicyStep[]> = {};
+ const stepsByRequestId: Record<
+ string,
+ (TApprovalRequestSteps & {
+ approvers: { type: ApproverType; id: string }[];
+ approvals: TApprovalRequestApprovals[];
+ })[]
+ > = {};
if (steps.length) {
const stepIds = steps.map((step) => step.id);
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index 60764bdc1a..795fdf843a 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -5,10 +5,6 @@ import { projectKeys } from "@app/hooks/api/projects/query-keys";
import { pamKeys } from "./queries";
import {
- TCreatePamAccessRequestDTO,
- TReviewPamAccessRequestDTO,
- TRevokePamAccessRequestDTO,
- TSetPamApprovalConfigDTO,
TAddAccountGroupMemberDTO,
TAddAccountIdentityMemberDTO,
TAddAccountUserMemberDTO,
@@ -16,6 +12,7 @@ import {
TAddFolderIdentityMemberDTO,
TAddFolderUserMemberDTO,
TAddPamProductIdentityMemberDTO,
+ TCreatePamAccessRequestDTO,
TCreatePamAccountDTO,
TCreatePamAccountTemplateDTO,
TCreatePamFolderDTO,
@@ -33,6 +30,9 @@ import {
TRemoveFolderIdentityMemberDTO,
TRemoveFolderMemberDTO,
TRemovePamProductIdentityMemberDTO,
+ TReviewPamAccessRequestDTO,
+ TRevokePamAccessRequestDTO,
+ TSetPamApprovalConfigDTO,
TUpdateAccountGroupMemberRoleDTO,
TUpdateAccountIdentityMemberRoleDTO,
TUpdateAccountMemberRoleDTO,
@@ -585,10 +585,10 @@ export const useReviewPamAccessRequest = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ requestId, status, comment }: TReviewPamAccessRequestDTO) => {
- const { data } = await apiRequest.post(
- `/api/v1/pam/access-requests/${requestId}/review`,
- { status, comment }
- );
+ const { data } = await apiRequest.post(`/api/v1/pam/access-requests/${requestId}/review`, {
+ status,
+ comment
+ });
return data;
},
onSuccess: () => {
@@ -602,9 +602,7 @@ export const useRevokePamAccessRequest = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ requestId }: TRevokePamAccessRequestDTO) => {
- const { data } = await apiRequest.post(
- `/api/v1/pam/access-requests/${requestId}/revoke`
- );
+ const { data } = await apiRequest.post(`/api/v1/pam/access-requests/${requestId}/revoke`);
return data;
},
onSuccess: () => {
diff --git a/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx b/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx
index ff66df7ad1..d26b65eeb8 100644
--- a/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx
+++ b/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx
@@ -35,6 +35,83 @@ export const AccountRow = ({ account, search, onLaunch, onRequestAccess, indente
const canLaunchNow = canLaunch || isGranted;
const canClick = canLaunchNow && !needsApproval && !isDisabled;
+ const renderAction = () => {
+ if (isDisabled) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button variant="neutral" size="xs" isDisabled>
+ <Rocket className="size-3" />
+ Launch
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>{disabledReason}</TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ if (needsApproval) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ variant="neutral"
+ size="xs"
+ onClick={(e) => {
+ e.stopPropagation();
+ if (!isPending) onRequestAccess(account);
+ }}
+ isDisabled={isPending}
+ >
+ {isPending ? (
+ <>
+ <Clock className="size-3" />
+ Pending Approval
+ </>
+ ) : (
+ <>
+ <LockKeyhole className="size-3" />
+ Request Access
+ </>
+ )}
+ </Button>
+ </div>
+ </TooltipTrigger>
+ {isPending && <TooltipContent>Your access request is awaiting approval</TooltipContent>}
+ </Tooltip>
+ );
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ variant="pam"
+ size="xs"
+ onClick={(e) => {
+ e.stopPropagation();
+ onLaunch(account);
+ }}
+ isDisabled={!canLaunchNow}
+ >
+ <Rocket className="size-3" />
+ Launch
+ </Button>
+ </div>
+ </TooltipTrigger>
+ {!canLaunchNow && (
+ <TooltipContent>
+ You don&apos;t have permission to launch sessions for this account
+ </TooltipContent>
+ )}
+ </Tooltip>
+ );
+ };
+
return (
<TableRow
className={canClick ? "cursor-pointer" : ""}
@@ -50,76 +127,7 @@ export const AccountRow = ({ account, search, onLaunch, onRequestAccess, indente
</div>
</TableCell>
<TableCell className="w-32">
- <div className="flex items-center justify-end">
- {isDisabled ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button variant="neutral" size="xs" isDisabled>
- <Rocket className="size-3" />
- Launch
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>{disabledReason}</TooltipContent>
- </Tooltip>
- ) : needsApproval ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- variant="neutral"
- size="xs"
- onClick={(e) => {
- e.stopPropagation();
- if (!isPending) onRequestAccess(account);
- }}
- isDisabled={isPending}
- >
- {isPending ? (
- <>
- <Clock className="size-3" />
- Pending Approval
- </>
- ) : (
- <>
- <LockKeyhole className="size-3" />
- Request Access
- </>
- )}
- </Button>
- </div>
- </TooltipTrigger>
- {isPending && (
- <TooltipContent>Your access request is awaiting approval</TooltipContent>
- )}
- </Tooltip>
- ) : (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- variant="pam"
- size="xs"
- onClick={(e) => {
- e.stopPropagation();
- onLaunch(account);
- }}
- isDisabled={!canLaunchNow}
- >
- <Rocket className="size-3" />
- Launch
- </Button>
- </div>
- </TooltipTrigger>
- {!canLaunchNow && (
- <TooltipContent>
- You don&apos;t have permission to launch sessions for this account
- </TooltipContent>
- )}
- </Tooltip>
- )}
- </div>
+ <div className="flex items-center justify-end">{renderAction()}</div>
</TableCell>
</TableRow>
);
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx
index 41c15c3695..9b84442ff6 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx
@@ -54,7 +54,7 @@ import {
import { TPamAccessRequest } from "@app/hooks/api/pam/types";
import { useGetOrgUsers } from "@app/hooks/api/users/queries";
-import { getRequestStatusInfo } from "../../components/approvalRequestStatus";
+import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";
import { formatRelativeExpiry } from "../../components/PamDetailSheet";
import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
import { ApprovalRequestDetailSheet } from "../../PamApprovalRequestsPage/components/ApprovalRequestDetailSheet";
@@ -201,7 +201,10 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {
.map((g) => ({ value: g.id, label: g.name, kind: "group" as const, subtitle: "Group" }));
const users: ApproverOption[] = (orgUsers ?? [])
- .filter((ou) => ou.user.id && memberUserIds.has(ou.user.id) && !selectedIds.has(`user:${ou.user.id}`))
+ .filter(
+ (ou) =>
+ ou.user.id && memberUserIds.has(ou.user.id) && !selectedIds.has(`user:${ou.user.id}`)
+ )
.map((ou) => {
const name = [ou.user.firstName, ou.user.lastName].filter(Boolean).join(" ");
return {
@@ -389,74 +392,74 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {
</div>
) : (
<div className="overflow-x-auto">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>Requester</TableHead>
- <TableHead>Account</TableHead>
- <TableHead>Requested</TableHead>
- <TableHead>Status</TableHead>
- {canRevoke && <TableHead className="w-12" />}
- </TableRow>
- </TableHeader>
- <TableBody>
- {folderRequests.map((request) => {
- const status = getRequestStatusInfo(request);
- const duration = request.requestData?.requestData?.duration;
- return (
- <TableRow
- key={request.id}
- className="cursor-pointer"
- onClick={() => setSelectedRequest(request)}
- >
- <TableCell className="h-[50px]">
- <div className="flex flex-col">
- <span className="text-sm font-medium">{request.requesterName}</span>
- <span className="text-xs text-muted">{request.requesterEmail}</span>
- </div>
- </TableCell>
- <TableCell className="text-sm">
- <div className="flex items-center gap-2">
- {request.accountType && (
- <AccountPlatformIcon accountType={request.accountType} size={16} />
- )}
- {request.accountName ?? "-"}
- </div>
- </TableCell>
- <TableCell className="text-sm">
- <div className="flex flex-col">
- <RelativeTime date={request.createdAt} />
- {duration && <span className="text-xs text-muted">for {duration}</span>}
- </div>
- </TableCell>
- <TableCell>
- <Badge variant={status.variant}>{status.label}</Badge>
- </TableCell>
- {canRevoke && (
- <TableCell onClick={(e) => e.stopPropagation()}>
- {status.label === "Approved" && (
- <Tooltip>
- <TooltipTrigger asChild>
- <IconButton
- variant="ghost"
- size="xs"
- aria-label="Revoke access"
- className="text-muted hover:text-danger"
- onClick={() => setRequestToRevoke(request)}
- >
- <Ban className="size-4" />
- </IconButton>
- </TooltipTrigger>
- <TooltipContent>Revoke access</TooltipContent>
- </Tooltip>
- )}
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Requester</TableHead>
+ <TableHead>Account</TableHead>
+ <TableHead>Requested</TableHead>
+ <TableHead>Status</TableHead>
+ {canRevoke && <TableHead className="w-12" />}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {folderRequests.map((request) => {
+ const status = getRequestStatusInfo(request);
+ const duration = request.requestData?.requestData?.duration;
+ return (
+ <TableRow
+ key={request.id}
+ className="cursor-pointer"
+ onClick={() => setSelectedRequest(request)}
+ >
+ <TableCell className="h-[50px]">
+ <div className="flex flex-col">
+ <span className="text-sm font-medium">{request.requesterName}</span>
+ <span className="text-xs text-muted">{request.requesterEmail}</span>
+ </div>
</TableCell>
- )}
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
+ <TableCell className="text-sm">
+ <div className="flex items-center gap-2">
+ {request.accountType && (
+ <AccountPlatformIcon accountType={request.accountType} size={16} />
+ )}
+ {request.accountName ?? "-"}
+ </div>
+ </TableCell>
+ <TableCell className="text-sm">
+ <div className="flex flex-col">
+ <RelativeTime date={request.createdAt} />
+ {duration && <span className="text-xs text-muted">for {duration}</span>}
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant={status.variant}>{status.label}</Badge>
+ </TableCell>
+ {canRevoke && (
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ {isGrantActive(request) && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Revoke access"
+ className="text-muted hover:text-danger"
+ onClick={() => setRequestToRevoke(request)}
+ >
+ <Ban className="size-4" />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Revoke access</TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ )}
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
</div>
)}
{requestsTotalCount > requestsPerPage && (
diff --git a/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx b/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx
index fa0041b6f2..3953d68029 100644
--- a/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx
+++ b/frontend/src/pages/pam/PamApprovalRequestsPage/PamApprovalRequestsPage.tsx
@@ -181,7 +181,9 @@ export const PamApprovalRequestsPage = () => {
const clearRequestIdParam = () => {
if (!requestId) return;
- const rest = Object.fromEntries(Object.entries(searchParams).filter(([k]) => k !== "requestId"));
+ const rest = Object.fromEntries(
+ Object.entries(searchParams).filter(([k]) => k !== "requestId")
+ );
// eslint-disable-next-line @typescript-eslint/no-explicit-any
navigate({ search: rest as any, replace: true });
};
diff --git a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx
index 28f180a271..e5223a4953 100644
--- a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx
@@ -9,7 +9,7 @@ import { Button, Tabs, TabsContent, TabsList, TabsTrigger, TextArea } from "@app
import { useReviewPamAccessRequest, useRevokePamAccessRequest } from "@app/hooks/api/pam";
import { TPamAccessRequest } from "@app/hooks/api/pam/types";
-import { getRequestStatusInfo } from "../../components/approvalRequestStatus";
+import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";
import { PamDetailSheet } from "../../components/PamDetailSheet";
import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
@@ -39,8 +39,7 @@ export const ApprovalRequestDetailSheet = ({ request, isOpen, onOpenChange }: Pr
const status = getRequestStatusInfo(request ?? { status: "pending", grantExpiresAt: null });
const requestData = request?.requestData?.requestData;
const isPending = request?.status === "pending";
- // Revocation is only possible while the grant is still active (not already revoked or expired).
- const isGrantActive = status.label === "Approved";
+ const canRevoke = isGrantActive(request);
const handleReview = (decision: "approved" | "rejected") => {
if (!request) return;
@@ -82,113 +81,113 @@ export const ApprovalRequestDetailSheet = ({ request, isOpen, onOpenChange }: Pr
onDeleteApproved={handleRevoke}
/>
<PamDetailSheet
- isOpen={isOpen}
- onOpenChange={onOpenChange}
- isLoading={!request}
- icon={
- request?.accountType ? (
- <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
- <AccountPlatformIcon accountType={request.accountType} size={40} />
- </div>
- ) : (
- <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
- <ShieldCheck className="size-9 text-product-pam" />
- </div>
- )
- }
- title={request?.accountName ?? "Access Request"}
- subtitle={request ? `Request from ${request.requesterName}` : undefined}
- typeBadge={status.label}
- metadata={[
- { label: "Requester", value: request?.requesterName ?? "-" },
- { label: "Email", value: request?.requesterEmail ?? "-" },
- { label: "Folder", value: request?.folderName ?? "-" },
- ...(request?.host ? [{ label: "Host", value: request.host }] : []),
- {
- label: "Requested At",
- value: request ? format(new Date(request.createdAt), "MMM d, yyyy h:mm a") : "-"
- },
- ...(request?.grantExpiresAt
- ? [
- {
- label: "Expires",
- value: format(new Date(request.grantExpiresAt), "MMM d, yyyy h:mm a")
- }
- ]
- : []),
- { label: "Reason", value: requestData?.reason || "No reason provided" }
- ]}
- >
- <Tabs defaultValue="review" className="flex h-full flex-col">
- <TabsList variant="pam" className="shrink-0 bg-popover">
- <TabsTrigger value="review">
- <Check className="size-4" />
- Review
- </TabsTrigger>
- </TabsList>
- <TabsContent value="review" className="m-0 flex flex-1 flex-col p-6">
- <div className="flex flex-1 flex-col gap-6">
- {isPending && (
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ isLoading={!request}
+ icon={
+ request?.accountType ? (
+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
+ <AccountPlatformIcon accountType={request.accountType} size={40} />
+ </div>
+ ) : (
+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
+ <ShieldCheck className="size-9 text-product-pam" />
+ </div>
+ )
+ }
+ title={request?.accountName ?? "Access Request"}
+ subtitle={request ? `Request from ${request.requesterName}` : undefined}
+ typeBadge={status.label}
+ metadata={[
+ { label: "Requester", value: request?.requesterName ?? "-" },
+ { label: "Email", value: request?.requesterEmail ?? "-" },
+ { label: "Folder", value: request?.folderName ?? "-" },
+ ...(request?.host ? [{ label: "Host", value: request.host }] : []),
+ {
+ label: "Requested At",
+ value: request ? format(new Date(request.createdAt), "MMM d, yyyy h:mm a") : "-"
+ },
+ ...(request?.grantExpiresAt
+ ? [
+ {
+ label: "Expires",
+ value: format(new Date(request.grantExpiresAt), "MMM d, yyyy h:mm a")
+ }
+ ]
+ : []),
+ { label: "Reason", value: requestData?.reason || "No reason provided" }
+ ]}
+ >
+ <Tabs defaultValue="review" className="flex h-full flex-col">
+ <TabsList variant="pam" className="shrink-0 bg-popover">
+ <TabsTrigger value="review">
+ <Check className="size-4" />
+ Review
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="review" className="m-0 flex flex-1 flex-col p-6">
+ <div className="flex flex-1 flex-col gap-6">
+ {isPending && (
+ <div>
+ <p className="mb-2 text-sm font-medium text-foreground">Approval comment</p>
+ <TextArea
+ value={comment}
+ onChange={(e) => setComment(e.target.value)}
+ rows={4}
+ placeholder="Optional context for the requester"
+ />
+ <p className="mt-1.5 text-xs text-muted">
+ Visible to the requester and recorded in audit logs
+ </p>
+ </div>
+ )}
+
<div>
- <p className="mb-2 text-sm font-medium text-foreground">Approval comment</p>
- <TextArea
- value={comment}
- onChange={(e) => setComment(e.target.value)}
- rows={4}
- placeholder="Optional context for the requester"
- />
- <p className="mt-1.5 text-xs text-muted">
- Visible to the requester and recorded in audit logs
- </p>
+ <p className="mb-2 text-sm font-medium text-foreground">Access duration</p>
+ <div className="flex items-center gap-2 rounded-md border border-border bg-container px-3 py-2.5 text-sm text-foreground">
+ <Clock className="size-4 text-muted" />
+ {formatDuration(requestData?.duration)}
+ </div>
</div>
- )}
- <div>
- <p className="mb-2 text-sm font-medium text-foreground">Access duration</p>
- <div className="flex items-center gap-2 rounded-md border border-border bg-container px-3 py-2.5 text-sm text-foreground">
- <Clock className="size-4 text-muted" />
- {formatDuration(requestData?.duration)}
- </div>
+ {!isPending && !canRevoke && (
+ <p className="text-sm text-muted">
+ This request has been {status.label.toLowerCase()} and can no longer be actioned.
+ </p>
+ )}
</div>
- {!isPending && !isGrantActive && (
- <p className="text-sm text-muted">
- This request has been {status.label.toLowerCase()} and can no longer be actioned.
- </p>
- )}
- </div>
-
- {(isPending || isGrantActive) && (
- <div className="flex items-center justify-end gap-2 border-t border-border pt-4">
- {isPending && (
- <>
- <Button
- variant="outline"
- onClick={() => handleReview("rejected")}
- isPending={reviewMutation.isPending}
- >
- <X className="mr-1.5 size-4" />
- Deny
- </Button>
- <Button
- variant="pam"
- onClick={() => handleReview("approved")}
- isPending={reviewMutation.isPending}
- >
- <Check className="mr-1.5 size-4" />
- Approve
+ {(isPending || canRevoke) && (
+ <div className="flex items-center justify-end gap-2 border-t border-border pt-4">
+ {isPending && (
+ <>
+ <Button
+ variant="outline"
+ onClick={() => handleReview("rejected")}
+ isPending={reviewMutation.isPending}
+ >
+ <X className="mr-1.5 size-4" />
+ Deny
+ </Button>
+ <Button
+ variant="pam"
+ onClick={() => handleReview("approved")}
+ isPending={reviewMutation.isPending}
+ >
+ <Check className="mr-1.5 size-4" />
+ Approve
+ </Button>
+ </>
+ )}
+ {canRevoke && (
+ <Button variant="danger" onClick={() => setIsRevokeConfirmOpen(true)}>
+ Revoke Access
</Button>
- </>
- )}
- {isGrantActive && (
- <Button variant="danger" onClick={() => setIsRevokeConfirmOpen(true)}>
- Revoke Access
- </Button>
- )}
- </div>
- )}
- </TabsContent>
- </Tabs>
+ )}
+ </div>
+ )}
+ </TabsContent>
+ </Tabs>
</PamDetailSheet>
</>
);
diff --git a/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx b/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx
index aa6a0fdb20..eb80a254cb 100644
--- a/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx
+++ b/frontend/src/pages/pam/components/AccountAccessibilityBadge.tsx
@@ -7,7 +7,8 @@ const ISSUE_LABELS: Record<PamAccountAccessibilityIssue, string> = {
[PamAccountAccessibilityIssue.NoGateway]: "No gateway is configured",
[PamAccountAccessibilityIssue.NoRecordingConfig]: "No recording bucket is configured",
[PamAccountAccessibilityIssue.NoCredential]: "No password is set",
- [PamAccountAccessibilityIssue.NoApprovalConfig]: "No approval policy is configured for this folder"
+ [PamAccountAccessibilityIssue.NoApprovalConfig]:
+ "No approval policy is configured for this folder"
};
type Props = {
diff --git a/frontend/src/pages/pam/components/approvalRequestStatus.ts b/frontend/src/pages/pam/components/approvalRequestStatus.ts
index 85e7c50d1a..f705225549 100644
--- a/frontend/src/pages/pam/components/approvalRequestStatus.ts
+++ b/frontend/src/pages/pam/components/approvalRequestStatus.ts
@@ -17,9 +17,18 @@ export const getRequestStatusInfo = (
): StatusInfo => {
if (request.status === "approved") {
if (request.grantStatus === "revoked") return STATUS_BADGE.revoked;
- const grantExpired = !!request.grantExpiresAt && new Date(request.grantExpiresAt).getTime() <= Date.now();
+ const grantExpired =
+ !!request.grantExpiresAt && new Date(request.grantExpiresAt).getTime() <= Date.now();
if (grantExpired) return STATUS_BADGE.expired;
}
return STATUS_BADGE[request.status] ?? STATUS_BADGE.pending;
};
+
+// A grant is revocable while the request is approved and the grant is neither revoked nor expired.
+export const isGrantActive = (
+ request: Pick<TPamAccessRequest, "status" | "grantExpiresAt" | "grantStatus"> | null
+): boolean =>
+ request?.status === "approved" &&
+ request.grantStatus !== "revoked" &&
+ !(request.grantExpiresAt && new Date(request.grantExpiresAt).getTime() <= Date.now());