Skip to content

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

Fix approval redirection

Carlos Monastyrski8e4366c93a66
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index b7da1f8348..105cfbd1ee 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -53,6 +53,7 @@ import { TCertificateRequestServiceFactory } from "@app/services/certificate-req
import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";
import { resolveEffectiveTtl } from "@app/services/certificate-v3/certificate-v3-fns";
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
+import { TAcmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -154,6 +155,7 @@ type TPkiAcmeServiceFactoryDep = {
approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "create" | "updateById">;
pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOne">;
+ acmeEnrollmentConfigDAL: Pick<TAcmeEnrollmentConfigDALFactory, "findById">;
};
export const pkiAcmeServiceFactory = ({
@@ -179,7 +181,8 @@ export const pkiAcmeServiceFactory = ({
approvalPolicyDAL,
approvalPolicyService,
certificateRequestDAL,
- pkiApplicationProfileDAL
+ pkiApplicationProfileDAL,
+ acmeEnrollmentConfigDAL
}: TPkiAcmeServiceFactoryDep): TPkiAcmeServiceFactory => {
const validateAcmeProfile = async (profileId: string): Promise<TCertificateProfileWithConfigs> => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
@@ -469,6 +472,13 @@ export const pkiAcmeServiceFactory = ({
const profile = await validateAcmeProfile(profileId);
const publicKeyThumbprint = await calculateJwkThumbprint(jwk, "sha256");
+ const junctionRow = applicationId ? await pkiApplicationProfileDAL.findOne(applicationId, profile.id) : null;
+ const junctionAcmeConfig = junctionRow?.acmeConfigId
+ ? await acmeEnrollmentConfigDAL.findById(junctionRow.acmeConfigId)
+ : null;
+ const effectiveAcmeConfig = applicationId ? junctionAcmeConfig : (profile.acmeConfig ?? null);
+ const expectedEabKid = applicationId ? junctionAcmeConfig?.id : profile.id;
+
const existingAccount: TPkiAcmeAccounts | null = await acmeAccountDAL.findByProfileIdAndPublicKeyThumbprintAndAlg(
profileId,
alg,
@@ -483,17 +493,17 @@ export const pkiAcmeServiceFactory = ({
body: {
status: "valid",
contact: existingAccount.emails,
- orders: buildUrl(profile.id, `/accounts/${existingAccount.id}/orders`)
+ orders: buildUrl(profile.id, `/accounts/${existingAccount.id}/orders`, applicationId)
},
headers: {
- Location: buildUrl(profile.id, `/accounts/${existingAccount.id}`),
- Link: `<${buildUrl(profile.id, "/directory")}>;rel="index"`
+ Location: buildUrl(profile.id, `/accounts/${existingAccount.id}`, applicationId),
+ Link: `<${buildUrl(profile.id, "/directory", applicationId)}>;rel="index"`
}
};
}
// Check if EAB is required for this profile (EAB is required by default unless skipEabBinding is true)
- const skipEabBinding = profile.acmeConfig?.skipEabBinding ?? false;
+ const skipEabBinding = effectiveAcmeConfig?.skipEabBinding ?? false;
// Note: We only check EAB for the new account request. This is a very special case for cert-manager.
// There's a bug in their ACME client implementation, they don't take the account KID value they have
@@ -534,16 +544,19 @@ export const pkiAcmeServiceFactory = ({
body: {
status: "valid",
contact: existingAccount.emails,
- orders: buildUrl(profile.id, `/accounts/${existingAccount.id}/orders`)
+ orders: buildUrl(profile.id, `/accounts/${existingAccount.id}/orders`, applicationId)
},
headers: {
- Location: buildUrl(profile.id, `/accounts/${existingAccount.id}`),
- Link: `<${buildUrl(profile.id, "/directory")}>;rel="index"`
+ Location: buildUrl(profile.id, `/accounts/${existingAccount.id}`, applicationId),
+ Link: `<${buildUrl(profile.id, "/directory", applicationId)}>;rel="index"`
}
};
}
if (externalAccountBinding && !skipEabBinding) {
+ if (!effectiveAcmeConfig?.encryptedEabSecret) {
+ throw new AcmeExternalAccountRequiredError({ message: "External account binding is not configured" });
+ }
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
projectId: profile.projectId,
projectDAL,
@@ -552,7 +565,7 @@ export const pkiAcmeServiceFactory = ({
const kmsDecryptor = await kmsService.decryptWithKmsKey({
kmsId: certificateManagerKmsId
});
- const eabSecret = await kmsDecryptor({ cipherTextBlob: profile.acmeConfig!.encryptedEabSecret! });
+ const eabSecret = await kmsDecryptor({ cipherTextBlob: effectiveAcmeConfig.encryptedEabSecret });
const { eabPayload, eabProtectedHeader } = await (async () => {
try {
const result = await flattenedVerify(externalAccountBinding, eabSecret);
@@ -572,14 +585,14 @@ export const pkiAcmeServiceFactory = ({
message: "Invalid algorithm for external account binding JWS payload"
});
}
- // Make sure the KID in the EAB payload matches the profile ID
- if (eabKid !== profile.id) {
+ // Make sure the KID in the EAB payload matches the expected scope (profile or junction)
+ if (eabKid !== expectedEabKid) {
throw new AcmeExternalAccountRequiredError({ message: "External account binding KID mismatch" });
}
// Make sure the URL matches the expected URL
const url = eabProtectedHeader!.url!;
- if (url !== buildUrl(profile.id, "/new-account")) {
+ if (url !== buildUrl(profile.id, "/new-account", applicationId)) {
throw new AcmeExternalAccountRequiredError({ message: "External account binding URL mismatch" });
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index cda7aeac88..9ddaf258f0 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2658,6 +2658,7 @@ export const registerRoutes = async (
approvalPolicyStepApproversDAL,
permissionService,
projectMembershipDAL,
+ membershipDAL,
approvalRequestDAL,
approvalRequestStepsDAL,
approvalRequestStepEligibleApproversDAL,
@@ -2784,7 +2785,8 @@ export const registerRoutes = async (
approvalPolicyDAL,
approvalPolicyService,
certificateRequestDAL,
- pkiApplicationProfileDAL
+ pkiApplicationProfileDAL,
+ acmeEnrollmentConfigDAL
});
const pkiSubscriberService = pkiSubscriberServiceFactory({
diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.ts
index 9a9e436aad..9cc915b782 100644
--- a/backend/src/services/approval-policy/approval-policy-service.ts
+++ b/backend/src/services/approval-policy/approval-policy-service.ts
@@ -3,6 +3,7 @@ import { ForbiddenError } from "@casl/ability";
import {
ActionProjectType,
ProjectMembershipRole,
+ RESOURCE_SCOPE,
ResourceType,
TApprovalPolicies,
TApprovalRequests
@@ -27,6 +28,7 @@ import { TCertificateRequestDALFactory } from "@app/services/certificate-request
import { TCertificateApprovalService } from "@app/services/certificate-v3/certificate-approval-fns";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { TMembershipDALFactory } from "../membership/membership-dal";
import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";
import {
TApprovalPolicyDALFactory,
@@ -77,6 +79,7 @@ type TApprovalPolicyServiceFactoryDep = {
"getProjectPermission" | "getOrgPermission" | "getResourcePermission"
>;
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserIds">;
+ membershipDAL: Pick<TMembershipDALFactory, "find">;
certificateApprovalService: TCertificateApprovalService;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;
};
@@ -95,6 +98,7 @@ export const approvalPolicyServiceFactory = ({
notificationService,
permissionService,
projectMembershipDAL,
+ membershipDAL,
certificateApprovalService,
certificateRequestDAL
}: TApprovalPolicyServiceFactoryDep) => {
@@ -150,6 +154,38 @@ export const approvalPolicyServiceFactory = ({
}
};
+ const $verifyApplicationApproverMembership = async (
+ approvers: { type: ApproverType; id: string }[],
+ projectId: string,
+ applicationId: string
+ ) => {
+ const userIds = [...new Set(approvers.filter((a) => a.type === ApproverType.User).map((a) => a.id))];
+ const groupIds = [...new Set(approvers.filter((a) => a.type === ApproverType.Group).map((a) => a.id))];
+ if (userIds.length === 0 && groupIds.length === 0) return;
+
+ const memberships = await membershipDAL.find({
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.CertificateApplication,
+ scopeResourceId: applicationId
+ });
+
+ const memberUserIds = new Set(memberships.map((m) => m.actorUserId).filter((id): id is string => Boolean(id)));
+ const memberGroupIds = new Set(memberships.map((m) => m.actorGroupId).filter((id): id is string => Boolean(id)));
+
+ const usersNotInApp = userIds.filter((id) => !memberUserIds.has(id));
+ const groupsNotInApp = groupIds.filter((id) => !memberGroupIds.has(id));
+
+ if (usersNotInApp.length > 0 || groupsNotInApp.length > 0) {
+ const parts: string[] = [];
+ if (usersNotInApp.length > 0) parts.push(`users: ${usersNotInApp.join(", ")}`);
+ if (groupsNotInApp.length > 0) parts.push(`groups: ${groupsNotInApp.join(", ")}`);
+ throw new BadRequestError({
+ message: `Approvers must be members of the Application. Not in Application — ${parts.join("; ")}`
+ });
+ }
+ };
+
const create = async (
policyType: ApprovalPolicyType,
{
@@ -166,11 +202,15 @@ export const approvalPolicyServiceFactory = ({
) => {
await $assertCanManagePolicy(projectId, applicationId, actor, ResourcePermissionApprovalPolicyActions.Create);
- const approverUserIds = steps
- .flatMap((step) => step.approvers ?? [])
- .filter((approver) => approver.type === ApproverType.User)
- .map((approver) => approver.id);
- await $verifyProjectUserMembership(approverUserIds, actor.orgId, projectId);
+ const allApprovers = steps.flatMap((step) => step.approvers ?? []);
+ if (applicationId) {
+ await $verifyApplicationApproverMembership(allApprovers, projectId, applicationId);
+ } else {
+ const approverUserIds = allApprovers
+ .filter((approver) => approver.type === ApproverType.User)
+ .map((approver) => approver.id);
+ await $verifyProjectUserMembership(approverUserIds, actor.orgId, projectId);
+ }
const policy = await approvalPolicyDAL.transaction(async (tx) => {
const newPolicy = await approvalPolicyDAL.create(
@@ -301,12 +341,15 @@ export const approvalPolicyServiceFactory = ({
}
if (steps !== undefined) {
- // Verify all users are part of project
- const approverUserIds = steps
- .flatMap((step) => step.approvers ?? [])
- .filter((approver) => approver.type === ApproverType.User)
- .map((approver) => approver.id);
- await $verifyProjectUserMembership(approverUserIds, actor.orgId, policy.projectId);
+ const allApprovers = steps.flatMap((step) => step.approvers ?? []);
+ if (targetAppId) {
+ await $verifyApplicationApproverMembership(allApprovers, policy.projectId, targetAppId);
+ } else {
+ const approverUserIds = allApprovers
+ .filter((approver) => approver.type === ApproverType.User)
+ .map((approver) => approver.id);
+ await $verifyProjectUserMembership(approverUserIds, actor.orgId, policy.projectId);
+ }
}
const updatedPolicy = await approvalPolicyDAL.transaction(async (tx) => {
diff --git a/frontend/src/hooks/api/approvalRequests/queries.tsx b/frontend/src/hooks/api/approvalRequests/queries.tsx
index 3b4abddcc9..80de955750 100644
--- a/frontend/src/hooks/api/approvalRequests/queries.tsx
+++ b/frontend/src/hooks/api/approvalRequests/queries.tsx
@@ -28,7 +28,8 @@ export const approvalRequestQuery = {
requests: TApprovalRequest[];
}>(`/api/v1/approval-policies/${params.policyType}/requests`, {
params: {
- projectId: params.projectId
+ projectId: params.projectId,
+ ...(params.applicationId ? { applicationId: params.applicationId } : {})
}
});
return data.requests;
diff --git a/frontend/src/hooks/api/approvalRequests/types.ts b/frontend/src/hooks/api/approvalRequests/types.ts
index 5750240d9e..f88a7e0487 100644
--- a/frontend/src/hooks/api/approvalRequests/types.ts
+++ b/frontend/src/hooks/api/approvalRequests/types.ts
@@ -129,6 +129,7 @@ export type TGetApprovalRequestByIdDTO = {
export type TListApprovalRequestsDTO = {
policyType: ApprovalPolicyType;
projectId: string;
+ applicationId?: string;
};
export type TApproveApprovalRequestDTO = {
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx
index ff2f254206..d46105c5cf 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx
@@ -101,7 +101,10 @@ export const ApplicationDetailsByIDPage = () => {
/>
</TabPanel>
<TabPanel value="requests">
- <ApplicationRequestsTab profiles={profiles} />
+ <ApplicationRequestsTab
+ applicationId={application.id}
+ applicationName={application.name}
+ />
</TabPanel>
<TabPanel value="syncs">
<ApplicationSyncsTab
@@ -111,11 +114,7 @@ export const ApplicationDetailsByIDPage = () => {
/>
</TabPanel>
<TabPanel value="members">
- <ApplicationMembersTab
- members={members}
- applicationId={application.id}
- projectId={projectId ?? ""}
- />
+ <ApplicationMembersTab members={members} applicationId={application.id} />
</TabPanel>
<TabPanel value="settings">
<ApplicationSettingsTab application={application} profiles={profiles} />
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx
index dd5ac037d2..19a5c5ea24 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx
@@ -25,18 +25,18 @@ import {
SelectTrigger,
SelectValue
} from "@app/components/v3";
+import { useOrganization } from "@app/context";
import {
- useGetWorkspaceUsers,
- useListProjectIdentityMemberships,
- useListWorkspaceGroups
-} from "@app/hooks/api";
+ useGetIdentityMembershipOrgs,
+ useGetOrganizationGroups
+} from "@app/hooks/api/organization";
import { TPkiApplicationMember, useAddPkiApplicationMember } from "@app/hooks/api/pkiApplications";
+import { useGetOrgUsers } from "@app/hooks/api/users";
type ActorType = "user" | "identity" | "group";
type Props = {
applicationId: string;
- projectId: string;
isOpen: boolean;
onOpenChange: (open: boolean) => void;
existingMembers: TPkiApplicationMember[];
@@ -50,20 +50,23 @@ const PLACEHOLDER: Record<ActorType, string> = {
export const AddApplicationMemberModal = ({
applicationId,
- projectId,
isOpen,
onOpenChange,
existingMembers
}: Props) => {
+ const { currentOrg } = useOrganization();
+ const orgId = currentOrg?.id ?? "";
const [type, setType] = useState<ActorType>("user");
const [search, setSearch] = useState("");
const [selectedActorId, setSelectedActorId] = useState<string | null>(null);
const [role, setRole] = useState("operator");
const addMember = useAddPkiApplicationMember();
- const usersQuery = useGetWorkspaceUsers(projectId);
- const identitiesQuery = useListProjectIdentityMemberships({ projectId, limit: 100 });
- const groupsQuery = useListWorkspaceGroups(projectId);
+ // Cert Manager projects don't use project-level memberships, so eligible
+ // members are scoped to the organization rather than the project.
+ const usersQuery = useGetOrgUsers(orgId);
+ const identitiesQuery = useGetIdentityMembershipOrgs({ organizationId: orgId, limit: 100 });
+ const groupsQuery = useGetOrganizationGroups(orgId);
const taken = useMemo(() => {
const set = new Set<string>();
@@ -113,11 +116,11 @@ export const AddApplicationMemberModal = ({
const groups = groupsQuery.data ?? [];
return groups
- .filter((gm) => !taken.has(`group:${gm.group.id}`))
- .map((gm) => ({
- id: gm.group.id,
- primary: gm.group.name,
- secondary: gm.group.slug
+ .filter((g) => !taken.has(`group:${g.id}`))
+ .map((g) => ({
+ id: g.id,
+ primary: g.name,
+ secondary: g.slug
}))
.filter(
(i) =>
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx
index 17a25b9b00..019394ca5d 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx
@@ -45,7 +45,6 @@ import { AddApplicationMemberModal } from "./AddApplicationMemberModal";
type Props = {
members: TPkiApplicationMember[];
applicationId: string;
- projectId: string;
};
type ActorType = "user" | "identity" | "group";
@@ -72,7 +71,7 @@ const displaySecondary = (m: TPkiApplicationMember): string | null => {
return null;
};
-export const ApplicationMembersTab = ({ members, applicationId, projectId }: Props) => {
+export const ApplicationMembersTab = ({ members, applicationId }: Props) => {
const updateRole = useUpdatePkiApplicationMemberRole();
const removeMember = useRemovePkiApplicationMember();
const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
@@ -189,7 +188,6 @@ export const ApplicationMembersTab = ({ members, applicationId, projectId }: Pro
<AddApplicationMemberModal
applicationId={applicationId}
- projectId={projectId}
isOpen={isAddOpen}
onOpenChange={setIsAddOpen}
existingMembers={members}
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx
index 6036dc7bab..da0da36673 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx
@@ -1,7 +1,9 @@
import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useNavigate, useParams } from "@tanstack/react-router";
import { SearchIcon } from "lucide-react";
-import { Spinner, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import {
Badge,
Card,
@@ -24,55 +26,52 @@ import {
TableRow
} from "@app/components/v3";
import { useDebounce } from "@app/hooks";
+import { ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";
import {
- CertificateRequestStatus,
- TListCertificateRequestsParams,
- useListCertificateRequests
-} from "@app/hooks/api/certificates";
-import { TPkiApplicationProfile } from "@app/hooks/api/pkiApplications";
+ approvalRequestQuery,
+ ApprovalRequestStatus,
+ CertRequestRequestData,
+ TApprovalRequest
+} from "@app/hooks/api/approvalRequests";
type Props = {
- profiles: TPkiApplicationProfile[];
+ applicationId: string;
+ applicationName: string;
};
-type StatusTab = "pending" | "issued" | "rejected" | "all";
+type StatusFilter = "pending" | "approved" | "rejected" | "all";
-type BadgeVariant = "neutral" | "success" | "warning" | "danger" | "info";
-
-const TABS: { key: StatusTab; label: string; statuses: CertificateRequestStatus[] | null }[] = [
- {
- key: "pending",
- label: "Pending",
- statuses: [
- CertificateRequestStatus.PENDING_APPROVAL,
- CertificateRequestStatus.PENDING,
- CertificateRequestStatus.PENDING_VALIDATION
- ]
- },
- { key: "issued", label: "Issued", statuses: [CertificateRequestStatus.ISSUED] },
+const STATUS_TABS: {
+ key: StatusFilter;
+ label: string;
+ matches: (s: ApprovalRequestStatus) => boolean;
+}[] = [
+ { key: "pending", label: "Pending", matches: (s) => s === ApprovalRequestStatus.Pending },
+ { key: "approved", label: "Approved", matches: (s) => s === ApprovalRequestStatus.Approved },
{
key: "rejected",
label: "Rejected",
- statuses: [CertificateRequestStatus.REJECTED, CertificateRequestStatus.FAILED]
+ matches: (s) =>
+ s === ApprovalRequestStatus.Rejected ||
+ s === ApprovalRequestStatus.Cancelled ||
+ s === ApprovalRequestStatus.Expired
},
- { key: "all", label: "All", statuses: null }
+ { key: "all", label: "All", matches: () => true }
];
-const STATUS_BADGE: Record<CertificateRequestStatus, { label: string; variant: BadgeVariant }> = {
- [CertificateRequestStatus.PENDING_APPROVAL]: {
- label: "Approval required",
- variant: "warning"
- },
- [CertificateRequestStatus.PENDING]: { label: "Pending", variant: "neutral" },
- [CertificateRequestStatus.PENDING_VALIDATION]: { label: "Validating", variant: "info" },
- [CertificateRequestStatus.ISSUED]: { label: "Issued", variant: "success" },
- [CertificateRequestStatus.FAILED]: { label: "Failed", variant: "danger" },
- [CertificateRequestStatus.REJECTED]: { label: "Rejected", variant: "danger" }
+const STATUS_BADGE: Record<
+ ApprovalRequestStatus,
+ { label: string; variant: "warning" | "success" | "danger" | "neutral" | "info" }
+> = {
+ [ApprovalRequestStatus.Pending]: { label: "Pending review", variant: "warning" },
+ [ApprovalRequestStatus.Approved]: { label: "Approved", variant: "success" },
+ [ApprovalRequestStatus.Rejected]: { label: "Rejected", variant: "danger" },
+ [ApprovalRequestStatus.Cancelled]: { label: "Cancelled", variant: "neutral" },
+ [ApprovalRequestStatus.Expired]: { label: "Expired", variant: "neutral" }
};
const formatRelative = (iso: string): string => {
- const diffMs = Date.now() - new Date(iso).getTime();
- const minutes = Math.round(diffMs / 60000);
+ const minutes = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
const hours = Math.round(minutes / 60);
@@ -81,57 +80,70 @@ const formatRelative = (iso: string): string => {
return `${days} day${days === 1 ? "" : "s"} ago`;
};
-export const ApplicationRequestsTab = ({ profiles }: Props) => {
- const [activeTab, setActiveTab] = useState<StatusTab>("pending");
- const [pendingSearch, setPendingSearch] = useState("");
- const [debouncedSearch] = useDebounce(pendingSearch, 400);
-
- const profileIds = useMemo(() => profiles.map((p) => p.profileId), [profiles]);
+const isCertRequestData = (data: unknown): data is { requestData: CertRequestRequestData } => {
+ return Boolean(
+ data &&
+ typeof data === "object" &&
+ "requestData" in data &&
+ data.requestData &&
+ typeof data.requestData === "object" &&
+ "profileName" in (data.requestData as object)
+ );
+};
- const tab = TABS.find((t) => t.key === activeTab) ?? TABS[0];
+export const ApplicationRequestsTab = ({ applicationId, applicationName }: Props) => {
+ const params = useParams({ strict: false }) as { projectId?: string; orgId?: string };
+ const { projectId, orgId } = params;
+ const navigate = useNavigate();
+ const [activeStatus, setActiveStatus] = useState<StatusFilter>("pending");
+ const [searchInput, setSearchInput] = useState("");
+ const [debouncedSearch] = useDebounce(searchInput, 300);
- const queryParams: TListCertificateRequestsParams = useMemo(
- () => ({
- offset: 0,
- limit: 100,
- search: debouncedSearch || undefined,
- profileIds: profileIds.length > 0 ? profileIds : undefined
- }),
- [debouncedSearch, profileIds]
+ const { data: requests = [], isPending } = useQuery(
+ approvalRequestQuery.list({
+ policyType: ApprovalPolicyType.CertRequest,
+ projectId: projectId ?? "",
+ applicationId
+ })
);
- const { data, isPending } = useListCertificateRequests(queryParams);
-
const filtered = useMemo(() => {
- const all = data?.certificateRequests ?? [];
- if (!tab.statuses) return all;
- return all.filter((r) => tab.statuses!.includes(r.status as CertificateRequestStatus));
- }, [data, tab]);
+ const tab = STATUS_TABS.find((t) => t.key === activeStatus) ?? STATUS_TABS[0];
+ const norm = debouncedSearch.trim().toLowerCase();
+ return (requests as TApprovalRequest[])
+ .filter((r) => tab.matches(r.status as ApprovalRequestStatus))
+ .filter((r) => {
+ if (!norm) return true;
+ const cn = isCertRequestData(r.requestData)
+ ? (r.requestData.requestData.certificateRequest?.commonName ?? "")
+ : "";
+ const profile = isCertRequestData(r.requestData)
+ ? (r.requestData.requestData.profileName ?? "")
+ : "";
+ return cn.toLowerCase().includes(norm) || profile.toLowerCase().includes(norm);
+ });
+ }, [requests, activeStatus, debouncedSearch]);
const counts = useMemo(() => {
- const all = data?.certificateRequests ?? [];
- const result: Record<StatusTab, number> = {
+ const result: Record<StatusFilter, number> = {
pending: 0,
- issued: 0,
+ approved: 0,
rejected: 0,
- all: all.length
+ all: requests.length
};
- all.forEach((r) => {
- const s = r.status as CertificateRequestStatus;
- if (
- s === CertificateRequestStatus.PENDING_APPROVAL ||
- s === CertificateRequestStatus.PENDING ||
- s === CertificateRequestStatus.PENDING_VALIDATION
- ) {
- result.pending += 1;
- } else if (s === CertificateRequestStatus.ISSUED) {
- result.issued += 1;
- } else if (s === CertificateRequestStatus.REJECTED || s === CertificateRequestStatus.FAILED) {
+ (requests as TApprovalRequest[]).forEach((r) => {
+ const s = r.status as ApprovalRequestStatus;
+ if (s === ApprovalRequestStatus.Pending) result.pending += 1;
+ else if (s === ApprovalRequestStatus.Approved) result.approved += 1;
+ else if (
+ s === ApprovalRequestStatus.Rejected ||
+ s === ApprovalRequestStatus.Cancelled ||
+ s === ApprovalRequestStatus.Expired
+ )
result.rejected += 1;
- }
});
return result;
- }, [data]);
+ }, [requests]);
return (
<Card>
@@ -143,79 +155,93 @@ export const ApplicationRequestsTab = ({ profiles }: Props) => {
</CardDescription>
</CardHeader>
<CardContent>
- <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as StatusTab)}>
+ <Tabs value={activeStatus} onValueChange={(v) => setActiveStatus(v as StatusFilter)}>
<TabList>
- {TABS.map((t) => (
- <Tab
- key={t.key}
- value={t.key}
- variant="project"
- data-testid={`requests-tab-${t.key}`}
- >
+ {STATUS_TABS.map((t) => (
+ <Tab key={t.key} value={t.key} variant="project">
{t.label} ({counts[t.key]})
</Tab>
))}
</TabList>
-
- {TABS.map((t) => (
+ {STATUS_TABS.map((t) => (
<TabPanel key={t.key} value={t.key}>
- <div className="mt-4 mb-4">
+ <div className="my-4">
<InputGroup>
<InputGroupAddon>
<SearchIcon />
</InputGroupAddon>
<InputGroupInput
- value={pendingSearch}
- onChange={(e) => setPendingSearch(e.target.value)}
placeholder="Search by SAN or CN…"
- data-testid="requests-search"
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
/>
</InputGroup>
</div>
- {isPending && !data && (
- <div className="flex items-center justify-center p-8">
- <Spinner />
- </div>
+ {isPending && (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>Loading…</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
)}
- {(!isPending || data) && filtered.length === 0 && (
+ {!isPending && filtered.length === 0 && (
<Empty className="border">
<EmptyHeader>
<EmptyTitle>
- {activeTab === "pending" ? "No requests pending" : "No requests"}
+ {activeStatus === "pending" ? "No requests pending review" : "No requests"}
</EmptyTitle>
<EmptyDescription>
- Certificate issuance requests scoped to this Application&apos;s profiles will
- appear here.
+ Cert-request approval workflows scoped to this Application will appear here.
</EmptyDescription>
</EmptyHeader>
</Empty>
)}
- {(!isPending || data) && filtered.length > 0 && (
+ {!isPending && filtered.length > 0 && (
<Table>
<TableHeader>
<TableRow>
<TableHead>Common Name / SAN</TableHead>
<TableHead>Profile</TableHead>
+ <TableHead>Requester</TableHead>
<TableHead>Status</TableHead>
<TableHead>Requested</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filtered.map((r) => {
- const badge =
- STATUS_BADGE[r.status as CertificateRequestStatus] ??
- ({ label: r.status, variant: "neutral" } as const);
+ const certData = isCertRequestData(r.requestData)
+ ? r.requestData.requestData
+ : null;
+ const cn = certData?.certificateRequest?.commonName ?? "—";
+ const profile = certData?.profileName ?? "—";
+ const badge = STATUS_BADGE[r.status as ApprovalRequestStatus] ?? {
+ label: r.status,
+ variant: "neutral" as const
+ };
return (
- <TableRow key={r.id}>
- <TableCell isTruncatable>
- <div className="font-mono text-foreground">{r.commonName ?? "—"}</div>
- {r.altNames ? (
- <div className="font-mono text-xs text-accent">{r.altNames}</div>
- ) : null}
+ <TableRow
+ key={r.id}
+ className="cursor-pointer"
+ onClick={() =>
+ navigate({
+ to: `/organizations/${orgId ?? ""}/projects/cert-manager/${projectId ?? ""}/approvals/${r.id}` as never,
+ search: {
+ policyType: ApprovalPolicyType.CertRequest,
+ applicationName
+ } as never
+ } as never)
+ }
+ >
+ <TableCell isTruncatable className="font-mono">
+ {cn}
</TableCell>
- <TableCell className="font-mono text-xs">
- {r.profileName ?? "—"}
+ <TableCell className="font-mono text-xs">{profile}</TableCell>
+ <TableCell>
+ <div>{r.requesterName || "—"}</div>
+ {r.requesterEmail ? (
+ <div className="text-xs text-accent">{r.requesterEmail}</div>
+ ) : null}
</TableCell>
<TableCell>
<Badge variant={badge.variant}>{badge.label}</Badge>
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx
index eea7696dbe..5260903745 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx
@@ -95,7 +95,7 @@ const CodeSigningDetailsSection = ({
const PageContent = () => {
const { approvalRequestId } = useParams({ from: ROUTE_ID });
- const { policyType } = useSearch({ from: ROUTE_ID });
+ const { policyType, applicationName, from } = useSearch({ from: ROUTE_ID });
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
const { user: currentUser } = useUser();
@@ -127,6 +127,19 @@ const PageContent = () => {
text: "Successfully cancelled request",
type: "success"
});
+ if (applicationName) {
+ navigate({
+ to: `/organizations/${currentProject.orgId}/projects/cert-manager/${currentProject.id}/applications/${applicationName}` as never,
+ search: { selectedTab: "requests" } as never
+ } as never);
+ return;
+ }
+ if (from === "root-requests") {
+ navigate({
+ to: `/organizations/${currentProject.orgId}/projects/cert-manager/${currentProject.id}/requests` as never
+ } as never);
+ return;
+ }
navigate({
to: isCodeSigning
? "/organizations/$orgId/projects/cert-manager/$projectId/code-signing"
@@ -240,22 +253,60 @@ const PageContent = () => {
return <CertificateDetailsSection request={request} />;
};
- return (
- <div className="container mx-auto flex flex-col justify-between bg-bunker-800 font-inter text-white">
- <div className="mx-auto mb-6 w-full max-w-8xl">
+ const renderBackLink = () => {
+ const linkClass =
+ "mb-4 flex items-center gap-x-2 text-sm text-mineshaft-400 hover:text-mineshaft-200";
+
+ if (applicationName) {
+ return (
<Link
to={
- isCodeSigning
- ? "/organizations/$orgId/projects/cert-manager/$projectId/code-signing"
- : "/organizations/$orgId/projects/cert-manager/$projectId/approvals"
+ `/organizations/${currentOrg.id}/projects/cert-manager/${currentProject.id}/applications/${applicationName}` as never
}
- params={{ orgId: currentOrg.id, projectId: currentProject.id }}
- search={isCodeSigning ? { tab: "approvals" } : { section: "certificates" }}
- className="mb-4 flex items-center gap-x-2 text-sm text-mineshaft-400 hover:text-mineshaft-200"
+ search={{ selectedTab: "requests" } as never}
+ className={linkClass}
>
<FontAwesomeIcon icon={faChevronLeft} />
- {isCodeSigning ? "Signing Requests" : "Approvals List"}
+ {applicationName}
</Link>
+ );
+ }
+
+ if (from === "root-requests") {
+ return (
+ <Link
+ to={
+ `/organizations/${currentOrg.id}/projects/cert-manager/${currentProject.id}/requests` as never
+ }
+ className={linkClass}
+ >
+ <FontAwesomeIcon icon={faChevronLeft} />
+ Requests
+ </Link>
+ );
+ }
+
+ return (
+ <Link
+ to={
+ isCodeSigning
+ ? "/organizations/$orgId/projects/cert-manager/$projectId/code-signing"
+ : "/organizations/$orgId/projects/cert-manager/$projectId/approvals"
+ }
+ params={{ orgId: currentOrg.id, projectId: currentProject.id }}
+ search={isCodeSigning ? { tab: "approvals" } : { section: "certificates" }}
+ className={linkClass}
+ >
+ <FontAwesomeIcon icon={faChevronLeft} />
+ {isCodeSigning ? "Signing Requests" : "Approvals List"}
+ </Link>
+ );
+ };
+
+ return (
+ <div className="container mx-auto flex flex-col justify-between bg-bunker-800 font-inter text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ {renderBackLink()}
<div className="mb-6 flex items-start justify-between">
<div>{renderTitle()}</div>
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/route.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/route.tsx
index 92a6c365d2..29c1264246 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/route.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/route.tsx
@@ -7,7 +7,9 @@ import { ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";
import { ApprovalRequestDetailPage } from "./ApprovalRequestDetailPage";
const ApprovalRequestSearchSchema = z.object({
- policyType: z.nativeEnum(ApprovalPolicyType).optional()
+ policyType: z.nativeEnum(ApprovalPolicyType).optional(),
+ applicationName: z.string().optional(),
+ from: z.enum(["root-requests"]).optional()
});
export const Route = createFileRoute(
diff --git a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx
index c7a328f6c0..c3bec25849 100644
--- a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx
+++ b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx
@@ -283,7 +283,19 @@ export const RequestsPage = () => {
};
return (
- <TableRow key={r.id}>
+ <TableRow
+ key={r.id}
+ className="cursor-pointer"
+ onClick={() =>
+ navigate({
+ to: `/organizations/${orgId}/projects/cert-manager/${projectId}/approvals/${r.id}` as never,
+ search: {
+ policyType: ApprovalPolicyType.CertRequest,
+ from: "root-requests"
+ } as never
+ } as never)
+ }
+ >
<TableCell isTruncatable className="font-mono">
{cn}
</TableCell>
@@ -295,6 +307,7 @@ export const RequestsPage = () => {
`/organizations/${orgId}/projects/cert-manager/${projectId}/applications/${app.name}` as never
}
className="text-foreground hover:text-project"
+ onClick={(e) => e.stopPropagation()}
>
{app.name}
</Link>