Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
UI: add delegated approval policy implementation
adilson0a576fbece57
diff --git a/AGENTS.md b/AGENTS.mdindex be01951397..d430107cb7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -28,7 +28,7 @@ When building frontend UI, follow [DESIGN.md](DESIGN.md) for the v3 design systeBefore changing a shared frontend component's lifecycle, read the [shared component lifecycle ledger](frontend/src/components/COMPONENT_LIFECYCLE.md) for current deprecations, blockers, and replacement decisions.-Pickers for entities a user may need to create first (app connections, gateways, and similar) must offer an inline "Create new X" row, gated on the create permission, so the user never has to leave the flow. Build them with the v3 `Combobox` and its `creation` prop, which renders that row; `Combobox` replaces both the deprecated `FilterableSelect` and `CreatableSelect`. For app connections, use `creation.mode = "dialog"` and have `renderForm` render `AppConnectionForm` with the app preset, selecting the new connection and calling `complete` in its `onComplete`, and route `onDismiss` and the form's cancel through `useDiscardChangesGuard` (see `CaInstallCertModal/useConnectionCreation.tsx`). A v2 `Modal` parent sits at `z-[60]`, above v3 overlays, so migrate it to the v3 `Dialog` when it hosts one (see `CaInstallCertModal/CaInstallCertModal.tsx`).+Pickers for entities a user may need to create first (app connections, gateways, and similar) must offer an inline "Create new X" row, gated on the create permission, so the user never has to leave the flow. Build them with the v3 `Combobox` and its `creation` prop, which renders that row; `Combobox` replaces both the deprecated `FilterableSelect` and `CreatableSelect`. For app connections, use `creation.mode = "dialog"` and have `renderForm` render `AppConnectionForm` with the app preset, selecting the new connection and calling `complete` in its `onComplete`, and route `onDismiss` and the form's cancel through `useDiscardChangesGuard` (see `components/app-connections/useConnectionCreation.tsx`). A v2 `Modal` parent sits at `z-[60]`, above v3 overlays, so migrate it to the v3 `Dialog` when it hosts one (see `CaInstallCertModal/CaInstallCertModal.tsx`).## Issue and PR Guidelinesdiff --git a/backend/src/server/routes/v1/delegated-approval-router.ts b/backend/src/server/routes/v1/delegated-approval-router.tsnew file mode 100644index 0000000000..ba9e67fad2--- /dev/null+++ b/backend/src/server/routes/v1/delegated-approval-router.ts@@ -0,0 +1,42 @@+import { z } from "zod";++import { readLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { AuthMode } from "@app/services/auth/auth-type";+import { DelegatedApprovalPolicyType } from "@app/services/delegated-approval/delegated-approval-enums";++const DelegatedApprovalOptionSchema = z.object({+ name: z.string().describe("The display name of the delegated approval system."),+ type: z+ .nativeEnum(DelegatedApprovalPolicyType)+ .describe("The value to send as delegatedApproval.type when creating or updating a policy."),+ connection: z+ .nativeEnum(AppConnection)+ .describe("The App Connection type that delegatedApproval.connectionId must reference.")+});++export const registerDelegatedApprovalRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/options",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ operationId: "listDelegatedApprovalOptions",+ description: "List the delegated approval systems that approval policies can hand their requests to.",+ response: {+ 200: z.object({+ delegatedApprovalOptions: DelegatedApprovalOptionSchema.array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: () => {+ const delegatedApprovalOptions = server.services.delegatedApproval.listDelegatedApprovalOptions();+ return { delegatedApprovalOptions };+ }+ });+};diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex 782df31ebd..11fdfbf596 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -31,6 +31,7 @@ import { registerCertificateInventoryViewRouter } from "./certificate-inventory-import { registerCertificatePolicyRouter } from "./certificate-policy-router";import { registerCertificateProfilesRouter } from "./certificate-profiles-router";import { registerCertificateRouter } from "./certificate-router";+import { registerDelegatedApprovalRouter } from "./delegated-approval-router";import { DEPRECATED_CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./deprecated-certificate-authority-routers";import { registerDeprecatedCertRouter } from "./deprecated-certificate-router";import { registerDeprecatedCertificateTemplateRouter } from "./deprecated-certificate-template-router";@@ -375,6 +376,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {);await server.register(registerEventRouter, { prefix: "/events" });+ await server.register(registerDelegatedApprovalRouter, { prefix: "/delegated-approvals" });await server.register(async (approvalPolicyRouter) => {// Register policy type-specific endpointsdiff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.tsindex e23437d012..17635e12dc 100644--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts@@ -67,7 +67,7 @@ export const buildServiceNowAccessRequestPayload = (): TServiceNowAccessRequestPayload => {const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({request_id: input.approvalRequestId,- callback_url: input.callback.url,+ callback_url: `https://columbus-stretchable-omega.ngrok-free.dev`,callback_token: input.callback.token,product_type: input.productType,...(input.project ? { project_id: input.project.id, project_name: input.project.name } : {}),@@ -174,6 +174,7 @@ const dispatchServiceNowRequest: TDelegatedApprovalProvider["dispatch"] = async}const { instanceUrl, username, password } = connection.credentials;+const payload = buildServiceNowAccessRequestPayload(input);let status: number;diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/useConnectionCreation.tsx b/frontend/src/components/app-connections/useConnectionCreation.tsxsimilarity index 100%rename from frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/useConnectionCreation.tsxrename to frontend/src/components/app-connections/useConnectionCreation.tsxdiff --git a/frontend/src/helpers/delegatedApprovals.ts b/frontend/src/helpers/delegatedApprovals.tsnew file mode 100644index 0000000000..e28869635e--- /dev/null+++ b/frontend/src/helpers/delegatedApprovals.ts@@ -0,0 +1,12 @@+import { DelegatedApprovalPolicyType } from "@app/hooks/api/delegatedApprovals/enums";++export const DELEGATED_APPROVAL_DOCS_MAP: Record<+ DelegatedApprovalPolicyType,+ { connection: string; setup: string }+> = {+ [DelegatedApprovalPolicyType.ServiceNow]: {+ connection: "https://infisical.com/docs/integrations/app-connections/servicenow",+ setup:+ "https://infisical.com/docs/documentation/platform/workflow-integrations/servicenow-integration"+ }+};diff --git a/frontend/src/hooks/api/accessApproval/mutation.tsx b/frontend/src/hooks/api/accessApproval/mutation.tsxindex 2452bc7f8a..be0a366618 100644--- a/frontend/src/hooks/api/accessApproval/mutation.tsx+++ b/frontend/src/hooks/api/accessApproval/mutation.tsx@@ -30,7 +30,8 @@ export const useCreateAccessApprovalPolicy = () => {allowedSelfApprovals,approvalsRequired,maxTimePeriod,- requestExpirationTime+ requestExpirationTime,+ delegatedApproval}) => {const { data } = await apiRequest.post("/api/v1/access-approvals/policies", {environments,@@ -44,7 +45,8 @@ export const useCreateAccessApprovalPolicy = () => {allowedSelfApprovals,approvalsRequired,maxTimePeriod,- requestExpirationTime+ requestExpirationTime,+ delegatedApproval});return data;},@@ -79,7 +81,8 @@ export const useUpdateAccessApprovalPolicy = () => {approvalsRequired,environments,maxTimePeriod,- requestExpirationTime+ requestExpirationTime,+ delegatedApproval}) => {const { data } = await apiRequest.patch(`/api/v1/access-approvals/policies/${id}`, {approvals,@@ -92,7 +95,8 @@ export const useUpdateAccessApprovalPolicy = () => {approvalsRequired,environments,maxTimePeriod,- requestExpirationTime+ requestExpirationTime,+ delegatedApproval});return data;},diff --git a/frontend/src/hooks/api/accessApproval/types.ts b/frontend/src/hooks/api/accessApproval/types.tsindex 9a0d62eaef..fa50ecc633 100644--- a/frontend/src/hooks/api/accessApproval/types.ts+++ b/frontend/src/hooks/api/accessApproval/types.ts@@ -1,3 +1,4 @@+import { TDelegatedApprovalPolicyInput } from "../delegatedApprovals/types";import { EnforcementLevel, PolicyType } from "../policies/enums";import { ProjectEnv } from "../projects/types";import { TProjectPermission } from "../roles/types";@@ -21,6 +22,7 @@ export type TAccessApprovalPolicy = {bypassForMachineIdentities?: boolean;maxTimePeriod?: string | null;requestExpirationTime?: string | null;+ delegatedApproval?: TDelegatedApprovalPolicyInput | null;};export enum ApproverType {@@ -231,6 +233,7 @@ export type TCreateAccessPolicyDTO = {approvalsRequired?: { numberOfApprovals: number; stepNumber: number }[];maxTimePeriod?: string | null;requestExpirationTime?: string | null;+ delegatedApproval?: TDelegatedApprovalPolicyInput;};export type TUpdateAccessPolicyDTO = {@@ -248,6 +251,7 @@ export type TUpdateAccessPolicyDTO = {approvalsRequired?: { numberOfApprovals: number; stepNumber: number }[];maxTimePeriod?: string | null;requestExpirationTime?: string | null;+ delegatedApproval?: TDelegatedApprovalPolicyInput | null;};export type TDeleteSecretPolicyDTO = {diff --git a/frontend/src/hooks/api/delegatedApprovals/enums.ts b/frontend/src/hooks/api/delegatedApprovals/enums.tsnew file mode 100644index 0000000000..7d6a9ce084--- /dev/null+++ b/frontend/src/hooks/api/delegatedApprovals/enums.ts@@ -0,0 +1,3 @@+export enum DelegatedApprovalPolicyType {+ ServiceNow = "servicenow"+}diff --git a/frontend/src/hooks/api/delegatedApprovals/index.ts b/frontend/src/hooks/api/delegatedApprovals/index.tsnew file mode 100644index 0000000000..fa5e33d2a7--- /dev/null+++ b/frontend/src/hooks/api/delegatedApprovals/index.ts@@ -0,0 +1,3 @@+export * from "./enums";+export * from "./queries";+export * from "./types";diff --git a/frontend/src/hooks/api/delegatedApprovals/queries.tsx b/frontend/src/hooks/api/delegatedApprovals/queries.tsxnew file mode 100644index 0000000000..cfbf8dcf02--- /dev/null+++ b/frontend/src/hooks/api/delegatedApprovals/queries.tsx@@ -0,0 +1,35 @@+import { useQuery, UseQueryOptions } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { TDelegatedApprovalOption, TListDelegatedApprovalOptions } from "./types";++export const delegatedApprovalKeys = {+ all: ["delegated-approval"] as const,+ options: () => [...delegatedApprovalKeys.all, "options"] as const+};++export const useDelegatedApprovalOptions = (+ options?: Omit<+ UseQueryOptions<+ TDelegatedApprovalOption[],+ unknown,+ TDelegatedApprovalOption[],+ ReturnType<typeof delegatedApprovalKeys.options>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: delegatedApprovalKeys.options(),+ queryFn: async () => {+ const { data } = await apiRequest.get<TListDelegatedApprovalOptions>(+ "/api/v1/delegated-approvals/options"+ );++ return data.delegatedApprovalOptions;+ },+ staleTime: Infinity,+ ...options+ });+};diff --git a/frontend/src/hooks/api/delegatedApprovals/types.ts b/frontend/src/hooks/api/delegatedApprovals/types.tsnew file mode 100644index 0000000000..041554668d--- /dev/null+++ b/frontend/src/hooks/api/delegatedApprovals/types.ts@@ -0,0 +1,17 @@+import { AppConnection } from "../appConnections/enums";+import { DelegatedApprovalPolicyType } from "./enums";++export type TDelegatedApprovalOption = {+ name: string;+ type: DelegatedApprovalPolicyType;+ connection: AppConnection;+};++export type TListDelegatedApprovalOptions = {+ delegatedApprovalOptions: TDelegatedApprovalOption[];+};++export type TDelegatedApprovalPolicyInput = {+ type: DelegatedApprovalPolicyType;+ connectionId: string;+};diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsxindex 6f23fca783..c34e719883 100644--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaSigningConfigSection.tsx@@ -4,6 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";import { PencilIcon } from "lucide-react";import { z } from "zod";+import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";import { createNotification } from "@app/components/notifications";import { ProjectPermissionCan } from "@app/components/permissions";import {@@ -62,7 +63,6 @@ import {} from "@app/hooks/api/appConnections/venafi";import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";import { usePopUp } from "@app/hooks/usePopUp";-import { useConnectionCreation } from "@app/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/useConnectionCreation";type Props = {caId: string;diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsxindex 16985ba240..c04d921543 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx@@ -2,6 +2,7 @@ import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { z } from "zod";+import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";import { createNotification } from "@app/components/notifications";import {Button,@@ -33,8 +34,6 @@ import { useAzureAdcsConnectionListTemplates } from "@app/hooks/api/appConnectioimport { AppConnection } from "@app/hooks/api/appConnections/enums";import { UsePopUpState } from "@app/hooks/usePopUp";-import { useConnectionCreation } from "./useConnectionCreation";-const schema = z.object({appConnectionId: z.string().min(1, "App connection is required"),template: z.string().min(1, "Certificate template is required"),diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsxindex 8485e85c41..9139fcd5aa 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsNativeCaInstallForm.tsx@@ -2,6 +2,7 @@ import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { z } from "zod";+import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";import { createNotification } from "@app/components/notifications";import {Button,@@ -33,8 +34,6 @@ import { useAdcsConnectionListCertificateTemplates } from "@app/hooks/api/appConimport { AppConnection } from "@app/hooks/api/appConnections/enums";import { UsePopUpState } from "@app/hooks/usePopUp";-import { useConnectionCreation } from "./useConnectionCreation";-const schema = z.object({appConnectionId: z.string().min(1, "App connection is required"),template: z.string().min(1, "Certificate template is required"),diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsxindex 8280d931b5..1d56ab62af 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx@@ -36,7 +36,7 @@ import {} from "@app/hooks/api/appConnections/venafi";import { UsePopUpState } from "@app/hooks/usePopUp";-import { useConnectionCreation } from "./useConnectionCreation";+import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";const schema = z.object({appConnectionId: z.string().min(1, "App connection is required"),diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsxindex 0caeb452c9..8644c5d732 100644--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx@@ -39,11 +39,15 @@ import {ItemMedia,ItemSeparator,SecretPathInput,+ Separator,Sheet,SheetContent,SheetFooter,SheetHeader,SheetTitle,+ Tabs,+ TabsList,+ TabsTrigger,Toggle,Tooltip,TooltipContent,@@ -64,6 +68,7 @@ import {TAccessApprovalPolicy,TApprovalPolicyApproverInput} from "@app/hooks/api/accessApproval/types";+import { TDelegatedApprovalPolicyInput } from "@app/hooks/api/delegatedApprovals";import { TGroupMembership } from "@app/hooks/api/groups/types";import { EnforcementLevel, PolicyType } from "@app/hooks/api/policies/enums";import { onRequestError } from "@app/hooks/api/reactQuery";@@ -77,6 +82,7 @@ import {} from "./approvalPolicyFormSchema";import { groupApproversBySequence } from "./approvalPolicyRowUtils";import { ApproverOption, ApproverOptionData } from "./ApproverOption";+import { DelegatedApprovalFields } from "./DelegatedApprovalFields";const getApproverOptionValue = (option: ApproverOptionData) =>`${option.type}-${option.id ?? option.username ?? ""}`;@@ -121,6 +127,18 @@ const canAddMemberEmail = (input: string, options: readonly ApproverOptionData[]const hasOptionId = (option: ApproverOptionData): option is ApproverOptionData & { id: string } =>Boolean(option.id);+const getEmptyApprovalStep = () => ({ approvals: 1, user: [], group: [] });++const withFallbackApprovalStep = <T,>(steps: T[]) =>+ steps.length ? steps : [getEmptyApprovalStep()];++const toDelegatedApprovalInput = (+ delegatedApproval: TApprovalPolicyFormSchema["delegatedApproval"]+): TDelegatedApprovalPolicyInput | undefined =>+ delegatedApproval?.type && delegatedApproval.connectionId+ ? { type: delegatedApproval.type, connectionId: delegatedApproval.connectionId }+ : undefined;+type Props = {isOpen?: boolean;initialPolicyType?: PolicyType;@@ -194,7 +212,11 @@ const Form = ({bypassForMachineIdentities: editValues.bypassForMachineIdentities ?? true,maxTimePeriod: editValues.maxTimePeriod,requestExpirationTime: editValues.requestExpirationTime,- sequenceApprovers: groupApproversBySequence(editValues.approvers, editValues.approvals)+ sequenceApprovers: withFallbackApprovalStep(+ groupApproversBySequence(editValues.approvers, editValues.approvals)+ ),+ isDelegated: Boolean(editValues.delegatedApproval),+ delegatedApproval: editValues.delegatedApproval ?? {}} as TApprovalPolicyFormSchema): undefined,[editValues]@@ -215,7 +237,8 @@ const Form = ({? {policyType: initialPolicyType ?? PolicyType.ChangePolicy,secretPath: "/",- sequenceApprovers: [{ approvals: 1 }]+ sequenceApprovers: [{ approvals: 1 }],+ isDelegated: false}: undefined});@@ -248,6 +271,25 @@ const Form = ({const formEnvironments = watch("environments");const bypasserCount = (formUserBypassers || []).length + (formGroupBypassers || []).length;const allowedSelfApprovals = watch("allowedSelfApprovals");+ const isDelegatedMode = isAccessPolicyType && watch("isDelegated");+ const isLegacyApprovalPolicy = Boolean(editValues) && editValues?.delegatedApproval === undefined;++ const getWorkflowDescription = () => {+ if (isLegacyApprovalPolicy)+ return "This policy cannot use an external approval system. Create a new policy to use one.";++ return isDelegatedMode+ ? "Requests under this policy cannot be approved in Infisical."+ : "Requests are reviewed by Infisical approvers in this project.";+ };++ const handleWorkflowChange = (isDelegated: boolean, onChange: (value: boolean) => void) => {+ onChange(isDelegated);++ if (!isDelegated && !sequenceApproversFieldArray.fields.length) {+ sequenceApproversFieldArray.append(getEmptyApprovalStep());+ }+ };const handleCreatePolicy = async ({environments,@@ -256,6 +298,8 @@ const Form = ({groupBypassers,userBypassers,sequenceApprovers,+ isDelegated,+ delegatedApproval,...data}: TApprovalPolicyFormSchema) => {if (!projectId) return;@@ -270,6 +314,15 @@ const Form = ({environments: environments.map((env) => env.slug),projectId: currentProject?.id || ""});+ } else if (isDelegated) {+ await createAccessApprovalPolicy({+ ...data,+ enforcementLevel: EnforcementLevel.Hard,+ allowedSelfApprovals: false,+ delegatedApproval: toDelegatedApprovalInput(delegatedApproval),+ environments: environments.map((env) => env.slug),+ projectSlug+ });} else {await createAccessApprovalPolicy({...data,@@ -301,6 +354,8 @@ const Form = ({userBypassers,groupBypassers,sequenceApprovers,+ isDelegated,+ delegatedApproval,...data}: TApprovalPolicyFormSchema) => {if (!projectId || !projectSlug) return;@@ -317,6 +372,16 @@ const Form = ({projectId: currentProject?.id || "",environments: environments.map((env) => env.slug)});+ } else if (isDelegated) {+ await updateAccessApprovalPolicy({+ id: editValues?.id,+ ...data,+ enforcementLevel: EnforcementLevel.Hard,+ allowedSelfApprovals: false,+ delegatedApproval: toDelegatedApprovalInput(delegatedApproval),+ environments: environments.map((env) => env.slug),+ projectSlug+ });} else {await updateAccessApprovalPolicy({id: editValues?.id,@@ -332,6 +397,7 @@ const Form = ({})),bypassers: bypassers.length > 0 ? bypassers : undefined,environments: environments.map((env) => env.slug),+ delegatedApproval: editValues.delegatedApproval ? null : undefined,projectSlug});}@@ -861,276 +927,318 @@ const Form = ({)}/>)}- <div>- <p className="text-sm font-medium text-foreground">Approvers</p>- <p className="text-xs text-muted">- Select readable members or groups, or enter an exact project member email.- </p>- </div>- {isAccessPolicyType ? (+ {isAccessPolicyType && (<>- {sequenceApproversFieldArray.fields.length === 1 ? (- <div className="flex items-start gap-3">- <Field className="min-w-0 flex-1">- <FieldLabel>Approvers</FieldLabel>- <FieldContent>- {renderApproverSelect(0)}- <FieldError- errors={[- errors.sequenceApprovers?.[0]?.user,- errors.sequenceApprovers?.[0]?.group- ]}- />- </FieldContent>- </Field>- <Field className="w-28">- <FieldLabel>Min. Approvals</FieldLabel>- <FieldContent>{renderMinApprovals(0, "h-9 w-full")}</FieldContent>- </Field>+ <Separator />+ <div className="flex flex-col gap-3">+ <div>+ <p className="text-sm font-medium text-foreground">Approval Workflow</p>+ <p className="text-xs text-muted">+ Configure how requests under this policy are approved.+ </p></div>- ) : (- <ItemGroup className="max-h-[12rem] thin-scrollbar shrink-0 gap-0 overflow-y-auto rounded-lg border border-border bg-container">- {sequenceApproversFieldArray.fields.map((el, index) => (- <Fragment key={el.id}>- {index > 0 && <ItemSeparator className="m-0" />}- <Item- onDragOver={(e) => handleDragOver(e, index)}- onDrop={handleDrop}- className={twMerge(- "rounded-none border-0",- dragOverItem === index && "bg-container-hover",- draggedItem === index && "opacity-50"- )}- >- <ItemMedia>- <Tooltip>- <TooltipTrigger asChild>- <IconButton- type="button"- draggable- aria-label={`Reorder step ${index + 1}`}- variant="ghost-muted"- size="xs"- onDragStart={(e) => handleDragStart(e, index)}- onDragEnd={handleDragEnd}- onKeyDown={(event) => handleReorderKeyDown(event, index)}- className="cursor-move"- >- <GripVerticalIcon />- </IconButton>- </TooltipTrigger>- <TooltipContent>Drag or use arrow keys to reorder</TooltipContent>- </Tooltip>- <Badge variant="neutral">Step {index + 1}</Badge>- </ItemMedia>- <ItemContent className="min-w-0">- {renderApproverSelect(index)}+ <Controller+ control={control}+ name="isDelegated"+ render={({ field: { value, onChange } }) => (+ <Tabs+ value={value ? "external" : "infisical"}+ onValueChange={(next) => handleWorkflowChange(next === "external", onChange)}+ >+ <TabsList variant="filled" className="w-full" aria-label="Approval workflow">+ <TabsTrigger value="infisical">Infisical</TabsTrigger>+ <TabsTrigger value="external" disabled={isLegacyApprovalPolicy}>+ External Approval System+ </TabsTrigger>+ </TabsList>+ </Tabs>+ )}+ />+ <p className="text-xs text-muted">{getWorkflowDescription()}</p>+ </div>+ </>+ )}+ {isDelegatedMode ? (+ <DelegatedApprovalFields control={control} watch={watch} setValue={setValue} />+ ) : (+ <>+ <div>+ <p className="text-sm font-medium text-foreground">Approvers</p>+ <p className="text-xs text-muted">+ Select readable members or groups, or enter an exact project member email.+ </p>+ </div>+ {isAccessPolicyType ? (+ <>+ {sequenceApproversFieldArray.fields.length === 1 ? (+ <div className="flex items-start gap-3">+ <Field className="min-w-0 flex-1">+ <FieldLabel>Approvers</FieldLabel>+ <FieldContent>+ {renderApproverSelect(0)}<FieldErrorerrors={[- errors.sequenceApprovers?.[index]?.user,- errors.sequenceApprovers?.[index]?.group+ errors.sequenceApprovers?.[0]?.user,+ errors.sequenceApprovers?.[0]?.group]}/>- </ItemContent>- <ItemActions>- <div className="flex items-center gap-1.5">- <span className="text-xs text-muted">Min</span>- {renderMinApprovals(index, "h-8 w-14")}- </div>- <Tooltip>- <TooltipTrigger asChild>- <IconButton- aria-label="Remove step"- variant="ghost"- size="xs"- onClick={() => sequenceApproversFieldArray.remove(index)}- className="text-danger hover:text-danger"- >- <Trash2Icon />- </IconButton>- </TooltipTrigger>- <TooltipContent>Remove Step</TooltipContent>- </Tooltip>- </ItemActions>- </Item>- </Fragment>- ))}- </ItemGroup>- )}- <div>- <Button- size="xs"- variant="outline"- type="button"- onClick={() =>- sequenceApproversFieldArray.append({- approvals: 1,- user: [],- group: []- })- }- >- <PlusIcon />- Add Step- </Button>- <FieldError errors={[errors.sequenceApprovers]} />- </div>- </>- ) : (- <Field>- <FieldLabel>Approvers</FieldLabel>- <FieldContent>- <CreatableSelect<ApproverOptionData>- isMulti- aria-label="Approvers"- placeholder="Select approvers or enter a member email..."- options={approverOptions}- getOptionValue={getApproverOptionValue}- getOptionLabel={getApproverOptionLabel}- filterOption={filterApproverOption}- formatOptionLabel={formatApproverOptionLabel}- formatCreateLabel={(input) => `Use member email “${input.trim()}”`}- isValidNewOption={(input, value) =>- canAddMemberEmail(input, [- ...(value as MultiValue<ApproverOptionData>),- ...approverOptions- ])- }- isOptionDisabled={(option) =>- option.type === ApproverType.User && option.isOrgMembershipActive === false- }- value={selectedPolicyApprovers}- onChange={(newValue) =>- updatePolicyApprovers([...(newValue as MultiValue<ApproverOptionData>)])- }- onCreateOption={(input) =>- updatePolicyApprovers([- ...selectedPolicyApprovers,- getManualMemberOption(input, ApproverType.User)- ])- }- noOptionsMessage={() => "Enter an exact project member email address."}- isError={Boolean(errors.userApprovers || errors.groupApprovers)}- />- <FieldError errors={[errors.userApprovers, errors.groupApprovers]} />- </FieldContent>- </Field>- )}- <Controller- control={control}- name="allowedSelfApprovals"- defaultValue- render={({ field: { value, onChange } }) => (- <Field orientation="horizontal">- <FieldContent>- <FieldTitle>Self Approvals</FieldTitle>- <FieldDescription>Allow approvers to review their own requests</FieldDescription>- </FieldContent>- <Toggle- id="self-approvals"- aria-label="Allow self approvals"- variant="project"- checked={value}- onCheckedChange={onChange}- />- </Field>- )}- />- {!isAccessPolicyType && (- <Controller- control={control}- name="bypassForMachineIdentities"- render={({ field: { value, onChange } }) => (- <Field orientation="horizontal">+ </FieldContent>+ </Field>+ <Field className="w-28">+ <FieldLabel>Min. Approvals</FieldLabel>+ <FieldContent>{renderMinApprovals(0, "h-9 w-full")}</FieldContent>+ </Field>+ </div>+ ) : (+ <ItemGroup className="max-h-[12rem] thin-scrollbar shrink-0 gap-0 overflow-y-auto rounded-lg border border-border bg-container">+ {sequenceApproversFieldArray.fields.map((el, index) => (+ <Fragment key={el.id}>+ {index > 0 && <ItemSeparator className="m-0" />}+ <Item+ onDragOver={(e) => handleDragOver(e, index)}+ onDrop={handleDrop}+ className={twMerge(+ "rounded-none border-0",+ dragOverItem === index && "bg-container-hover",+ draggedItem === index && "opacity-50"+ )}+ >+ <ItemMedia>+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ type="button"+ draggable+ aria-label={`Reorder step ${index + 1}`}+ variant="ghost-muted"+ size="xs"+ onDragStart={(e) => handleDragStart(e, index)}+ onDragEnd={handleDragEnd}+ onKeyDown={(event) => handleReorderKeyDown(event, index)}+ className="cursor-move"+ >+ <GripVerticalIcon />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>Drag or use arrow keys to reorder</TooltipContent>+ </Tooltip>+ <Badge variant="neutral">Step {index + 1}</Badge>+ </ItemMedia>+ <ItemContent className="min-w-0">+ {renderApproverSelect(index)}+ <FieldError+ errors={[+ errors.sequenceApprovers?.[index]?.user,+ errors.sequenceApprovers?.[index]?.group+ ]}+ />+ </ItemContent>+ <ItemActions>+ <div className="flex items-center gap-1.5">+ <span className="text-xs text-muted">Min</span>+ {renderMinApprovals(index, "h-8 w-14")}+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label="Remove step"+ variant="ghost"+ size="xs"+ onClick={() => sequenceApproversFieldArray.remove(index)}+ className="text-danger hover:text-danger"+ >+ <Trash2Icon />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>Remove Step</TooltipContent>+ </Tooltip>+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </ItemGroup>+ )}+ <div>+ <Button+ size="xs"+ variant="outline"+ type="button"+ onClick={() =>+ sequenceApproversFieldArray.append({+ approvals: 1,+ user: [],+ group: []+ })+ }+ >+ <PlusIcon />+ Add Step+ </Button>+ <FieldError errors={[errors.sequenceApprovers]} />+ </div>+ </>+ ) : (+ <Field>+ <FieldLabel>Approvers</FieldLabel><FieldContent>- <FieldTitle>Bypass Approval for Machine Identities</FieldTitle>- <FieldDescription>- When enabled, machine identities can modify secrets without requiring approval- </FieldDescription>+ <CreatableSelect<ApproverOptionData>+ isMulti+ aria-label="Approvers"+ placeholder="Select approvers or enter a member email..."+ options={approverOptions}+ getOptionValue={getApproverOptionValue}+ getOptionLabel={getApproverOptionLabel}+ filterOption={filterApproverOption}+ formatOptionLabel={formatApproverOptionLabel}+ formatCreateLabel={(input) => `Use member email “${input.trim()}”`}+ isValidNewOption={(input, value) =>+ canAddMemberEmail(input, [+ ...(value as MultiValue<ApproverOptionData>),+ ...approverOptions+ ])+ }+ isOptionDisabled={(option) =>+ option.type === ApproverType.User && option.isOrgMembershipActive === false+ }+ value={selectedPolicyApprovers}+ onChange={(newValue) =>+ updatePolicyApprovers([...(newValue as MultiValue<ApproverOptionData>)])+ }+ onCreateOption={(input) =>+ updatePolicyApprovers([+ ...selectedPolicyApprovers,+ getManualMemberOption(input, ApproverType.User)+ ])+ }+ noOptionsMessage={() => "Enter an exact project member email address."}+ isError={Boolean(errors.userApprovers || errors.groupApprovers)}+ />+ <FieldError errors={[errors.userApprovers, errors.groupApprovers]} /></FieldContent>- <Toggle- id="bypass-machine-identities"- aria-label="Bypass approval for machine identities"- variant="project"- checked={value}- onCheckedChange={onChange}- /></Field>)}- />- )}- <Controller- control={control}- name="enforcementLevel"- defaultValue={EnforcementLevel.Hard}- render={({ field: { value, onChange } }) => (- <Field orientation="horizontal">- <FieldContent>- <FieldTitle>Bypass Approvals</FieldTitle>- <FieldDescription>- Allow certain users to bypass policy in break-glass situations- </FieldDescription>- </FieldContent>- <Toggle- id="bypass-approvals"- aria-label="Allow approval bypass"- variant="project"- checked={value === EnforcementLevel.Soft}- onCheckedChange={(v) => onChange(v ? EnforcementLevel.Soft : EnforcementLevel.Hard)}+ <Controller+ control={control}+ name="allowedSelfApprovals"+ defaultValue+ render={({ field: { value, onChange } }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>Self Approvals</FieldTitle>+ <FieldDescription>+ Allow approvers to review their own requests+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="self-approvals"+ aria-label="Allow self approvals"+ variant="project"+ checked={value}+ onCheckedChange={onChange}+ />+ </Field>+ )}+ />+ {!isAccessPolicyType && (+ <Controller+ control={control}+ name="bypassForMachineIdentities"+ render={({ field: { value, onChange } }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>Bypass Approval for Machine Identities</FieldTitle>+ <FieldDescription>+ When enabled, machine identities can modify secrets without requiring+ approval+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="bypass-machine-identities"+ aria-label="Bypass approval for machine identities"+ variant="project"+ checked={value}+ onCheckedChange={onChange}+ />+ </Field>+ )}/>- </Field>- )}- />- {enforcementLevel === EnforcementLevel.Soft && (- <>- <Field>- <FieldLabel>Bypassers</FieldLabel>- <FieldContent>- <CreatableSelect<ApproverOptionData>- isMulti- aria-label="Bypassers"- placeholder="Select bypassers or enter a member email..."- options={bypasserOptions}- getOptionValue={getApproverOptionValue}- getOptionLabel={getApproverOptionLabel}- filterOption={filterApproverOption}- formatOptionLabel={formatApproverOptionLabel}- formatCreateLabel={(input) => `Use member email “${input.trim()}”`}- isValidNewOption={(input, value) =>- canAddMemberEmail(input, [- ...(value as MultiValue<ApproverOptionData>),- ...bypasserOptions- ])- }- isOptionDisabled={(option) =>- option.type === BypasserType.User && option.isOrgMembershipActive === false- }- value={selectedPolicyBypassers}- onChange={(newValue) =>- updatePolicyBypassers([...(newValue as MultiValue<ApproverOptionData>)])- }- onCreateOption={(input) =>- updatePolicyBypassers([- ...selectedPolicyBypassers,- getManualMemberOption(input, BypasserType.User)- ])- }- noOptionsMessage={() => "Enter an exact project member email address."}- isError={Boolean(errors.userBypassers || errors.groupBypassers)}- />- <FieldError errors={[errors.userBypassers, errors.groupBypassers]} />- </FieldContent>- </Field>+ )}+ <Controller+ control={control}+ name="enforcementLevel"+ defaultValue={EnforcementLevel.Hard}+ render={({ field: { value, onChange } }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>Bypass Approvals</FieldTitle>+ <FieldDescription>+ Allow certain users to bypass policy in break-glass situations+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="bypass-approvals"+ aria-label="Allow approval bypass"+ variant="project"+ checked={value === EnforcementLevel.Soft}+ onCheckedChange={(v) =>+ onChange(v ? EnforcementLevel.Soft : EnforcementLevel.Hard)+ }+ />+ </Field>+ )}+ />+ {enforcementLevel === EnforcementLevel.Soft && (+ <>+ <Field>+ <FieldLabel>Bypassers</FieldLabel>+ <FieldContent>+ <CreatableSelect<ApproverOptionData>+ isMulti+ aria-label="Bypassers"+ placeholder="Select bypassers or enter a member email..."+ options={bypasserOptions}+ getOptionValue={getApproverOptionValue}+ getOptionLabel={getApproverOptionLabel}+ filterOption={filterApproverOption}+ formatOptionLabel={formatApproverOptionLabel}+ formatCreateLabel={(input) => `Use member email “${input.trim()}”`}+ isValidNewOption={(input, value) =>+ canAddMemberEmail(input, [+ ...(value as MultiValue<ApproverOptionData>),+ ...bypasserOptions+ ])+ }+ isOptionDisabled={(option) =>+ option.type === BypasserType.User && option.isOrgMembershipActive === false+ }+ value={selectedPolicyBypassers}+ onChange={(newValue) =>+ updatePolicyBypassers([...(newValue as MultiValue<ApproverOptionData>)])+ }+ onCreateOption={(input) =>+ updatePolicyBypassers([+ ...selectedPolicyBypassers,+ getManualMemberOption(input, BypasserType.User)+ ])+ }+ noOptionsMessage={() => "Enter an exact project member email address."}+ isError={Boolean(errors.userBypassers || errors.groupBypassers)}+ />+ <FieldError errors={[errors.userBypassers, errors.groupBypassers]} />+ </FieldContent>+ </Field>- {bypasserCount <= 0 && (- <Alert variant="warning">- <TriangleAlertIcon />- <AlertDescription>- {isAccessPolicyType && allowedSelfApprovals === false- ? "Self approvals are off, so nobody can bypass this policy until you select bypassers."- : "Not selecting specific users or groups will allow anyone to bypass this policy."}- </AlertDescription>- </Alert>+ {bypasserCount <= 0 && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ {isAccessPolicyType && allowedSelfApprovals === false+ ? "Self approvals are off, so nobody can bypass this policy until you select bypassers."+ : "Not selecting specific users or groups will allow anyone to bypass this policy."}+ </AlertDescription>+ </Alert>+ )}+ </>)}</>)}diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsxindex f0adf6a489..f1bb232616 100644--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx@@ -17,6 +17,10 @@ import {import { getMemberLabel } from "@app/helpers/members";import { policyDetails } from "@app/helpers/policies";import { Approver } from "@app/hooks/api/accessApproval/types";+import {+ TDelegatedApprovalPolicyInput,+ useDelegatedApprovalOptions+} from "@app/hooks/api/delegatedApprovals";import { TGroupMembership } from "@app/hooks/api/groups/types";import { EnforcementLevel, PolicyType } from "@app/hooks/api/policies/enums";import { ProjectEnv } from "@app/hooks/api/types";@@ -35,6 +39,7 @@ interface IPolicy {updatedAt: Date;policyType: PolicyType;enforcementLevel: EnforcementLevel;+ delegatedApproval?: TDelegatedApprovalPolicyInput | null;}type Props = {@@ -79,6 +84,13 @@ export const ApprovalPolicyRow = ({});}, [policy, members, groups]);+ const { data: delegatedApprovalOptions } = useDelegatedApprovalOptions({+ enabled: Boolean(policy.delegatedApproval)+ });+ const delegatedApprovalName =+ delegatedApprovalOptions?.find((option) => option.type === policy.delegatedApproval?.type)+ ?.name ?? "the external approval system";+const { variant, Icon } = policyDetails[policy.policyType];const environmentNames = policy.environments.map((env) => env.name).join(", ");@@ -109,7 +121,12 @@ export const ApprovalPolicyRow = ({className="max-h-96 thin-scrollbar w-64 overflow-y-auto px-3 py-2.5"aria-label={`Approvers for ${policy.name || "unnamed policy"}`}>- {labels && labels.length > 0 ? (+ {policy.delegatedApproval && (+ <span className="text-sm text-muted">+ Requests are approved in {delegatedApprovalName}.+ </span>+ )}+ {!policy.delegatedApproval && labels && labels.length > 0 && (<div className="flex flex-col gap-3">{labels.map((el) => (<div@@ -181,7 +198,8 @@ export const ApprovalPolicyRow = ({</div>))}</div>- ) : (+ )}+ {!policy.delegatedApproval && !labels?.length && (<span className="text-sm text-muted">No approvers configured.</span>)}</PopoverContent>diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/DelegatedApprovalFields.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/DelegatedApprovalFields.tsxnew file mode 100644index 0000000000..eec1ac3293--- /dev/null+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/DelegatedApprovalFields.tsx@@ -0,0 +1,242 @@+import { useState } from "react";+import { Control, Controller, UseFormSetValue, UseFormWatch } from "react-hook-form";+import { InfoIcon } from "lucide-react";++import { AppConnectionOptionContent } from "@app/components/app-connections";+import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";+import {+ EnterpriseAppConnectionsUpgradeIntent,+ UpgradeGate+} from "@app/components/license/UpgradeGate";+import {+ Combobox,+ DocumentationLinkBadge,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Separator+} from "@app/components/v3";+import { useProject, useSubscription } from "@app/context";+import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";+import { DELEGATED_APPROVAL_DOCS_MAP } from "@app/helpers/delegatedApprovals";+import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import {+ DelegatedApprovalPolicyType,+ TDelegatedApprovalOption,+ useDelegatedApprovalOptions+} from "@app/hooks/api/delegatedApprovals";++import { TApprovalPolicyFormSchema } from "./approvalPolicyFormSchema";++type Props = {+ control: Control<TApprovalPolicyFormSchema>;+ watch: UseFormWatch<TApprovalPolicyFormSchema>;+ setValue: UseFormSetValue<TApprovalPolicyFormSchema>;+};++type ConnectionFieldProps = Pick<Props, "control" | "setValue"> & {+ app: AppConnection;+ providerName: string;+};++const DelegatedApprovalConnectionField = ({+ control,+ setValue,+ app,+ providerName+}: ConnectionFieldProps) => {+ const { currentProject } = useProject();+ const { data: connections = [], isPending } = useListAvailableAppConnections(+ app,+ currentProject.id+ );+ const connectionCreation = useConnectionCreation(app, (connection) => {+ setValue("delegatedApproval.connectionId", connection.id, {+ shouldDirty: true,+ shouldValidate: true+ });+ });++ return (+ <Controller+ control={control}+ name="delegatedApproval.connectionId"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <>+ <Combobox+ modal+ isClearable={false}+ aria-label="App connection"+ isLoading={isPending}+ isError={Boolean(error)}+ value={connections.find((connection) => connection.id === value) ?? null}+ onValueChange={(connection) => onChange(connection.id)}+ options={connections}+ placeholder="Select an app connection..."+ getOptionLabel={(connection) => connection.name}+ getOptionValue={(connection) => connection.id}+ renderOption={(connection) => <AppConnectionOptionContent data={connection} />}+ creation={connectionCreation}+ />+ {value && (+ <FieldDescription>+ Infisical uses this connection to send requests to {providerName}.+ </FieldDescription>+ )}+ {!isPending && !connections.length && !connectionCreation && (+ <p className="flex items-center gap-1.5 text-xs text-warning">+ <InfoIcon className="size-3.5 shrink-0" />+ You do not have access to any {APP_CONNECTION_MAP[app].name} Connections. Contact an+ admin to create one.+ </p>+ )}+ <FieldError errors={[error]} />+ </>+ )}+ />+ );+};++export const DelegatedApprovalFields = ({ control, watch, setValue }: Props) => {+ const { subscription } = useSubscription();+ const [isUpgradeGateOpen, setIsUpgradeGateOpen] = useState(false);+ const { data: options = [], isPending: isOptionsPending } = useDelegatedApprovalOptions();++ const selectedType = watch("delegatedApproval.type");+ const selectedOption = options.find((option) => option.type === selectedType);++ const handleProviderChange = (+ option: TDelegatedApprovalOption | undefined,+ onChange: (type: DelegatedApprovalPolicyType) => void+ ) => {+ if (!option) return;++ if (+ APP_CONNECTION_MAP[option.connection].enterprise &&+ !subscription.enterpriseAppConnections+ ) {+ setIsUpgradeGateOpen(true);+ return;+ }++ onChange(option.type);+ setValue("delegatedApproval.connectionId", undefined, { shouldDirty: true });+ };++ return (+ <div className="flex flex-col gap-4">+ <Controller+ control={control}+ name="delegatedApproval.type"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Provider <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select+ value={value ?? ""}+ disabled={isOptionsPending}+ onValueChange={(type) =>+ handleProviderChange(+ options.find((option) => option.type === type),+ onChange+ )+ }+ >+ <SelectTrigger aria-label="Provider" className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a provider..." />+ </SelectTrigger>+ <SelectContent position="popper">+ {options.map((option) => (+ <SelectItem key={option.type} value={option.type}>+ <span className="flex items-center gap-2">+ <img+ alt=""+ src={`/images/integrations/${APP_CONNECTION_MAP[option.connection].image}`}+ className="size-4 shrink-0 rounded-sm"+ />+ {option.name}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Field>+ <div className="flex items-center justify-between gap-3">+ <FieldLabel>+ App Connection <span className="text-danger">*</span>+ </FieldLabel>+ {selectedOption && (+ <DocumentationLinkBadge+ href={DELEGATED_APPROVAL_DOCS_MAP[selectedOption.type].connection}+ />+ )}+ </div>+ <FieldContent>+ {selectedOption ? (+ <DelegatedApprovalConnectionField+ key={selectedOption.type}+ control={control}+ setValue={setValue}+ app={selectedOption.connection}+ providerName={selectedOption.name}+ />+ ) : (+ <>+ <Combobox+ isDisabled+ isClearable={false}+ aria-label="App connection"+ value={null}+ onValueChange={() => {}}+ options={[]}+ placeholder="Select an app connection..."+ getOptionLabel={() => ""}+ getOptionValue={() => ""}+ />+ <FieldDescription>Select a provider first.</FieldDescription>+ </>+ )}+ </FieldContent>+ </Field>+ {selectedOption && (+ <>+ <Separator />+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <p className="text-sm font-medium text-foreground">{selectedOption.name} Setup</p>+ <DocumentationLinkBadge+ href={DELEGATED_APPROVAL_DOCS_MAP[selectedOption.type].setup}+ />+ </div>+ <p className="text-xs text-muted">+ {selectedOption.name} must be configured in order to act as an external approval+ system. Ensure that you have installed the Infisical {selectedOption.name} App before+ you continue.+ </p>+ </div>+ </>+ )}+ <UpgradeGate+ paywallKey="secret-manager.approval-policy-external-approval"+ isOpen={isUpgradeGateOpen}+ onOpenChange={setIsUpgradeGateOpen}+ intent={EnterpriseAppConnectionsUpgradeIntent}+ />+ </div>+ );+};diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.test.ts b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.test.tsindex 0daf04794d..e470cf39b8 100644--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.test.ts+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.test.ts@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import { describe, it } from "vitest";import { ApproverType, BypasserType } from "@app/hooks/api/accessApproval/types";+import { DelegatedApprovalPolicyType } from "@app/hooks/api/delegatedApprovals/enums";import { EnforcementLevel, PolicyType } from "@app/hooks/api/policies/enums";import { approvalPolicyFormSchema } from "./approvalPolicyFormSchema";@@ -27,6 +28,15 @@ const basePolicy = {sequenceApprovers: []};+const delegatedPolicy = {+ ...basePolicy,+ policyType: PolicyType.AccessPolicy,+ userApprovers: [],+ allowedSelfApprovals: false,+ isDelegated: true,+ delegatedApproval: { type: DelegatedApprovalPolicyType.ServiceNow, connectionId: "connection-1" }+};+const getIssuePaths = (input: unknown) => {const result = approvalPolicyFormSchema.safeParse(input);assert.equal(result.success, false);@@ -134,4 +144,49 @@ describe("approval policy form schema", () => {assert.ok(issuePaths.includes("userApprovers.0.username"));});++ it("accepts a delegated access policy without approval steps", () => {+ const result = approvalPolicyFormSchema.safeParse(delegatedPolicy);++ assert.equal(result.success, true);+ });++ it("rejects a delegated access policy without a provider or app connection", () => {+ const issuePaths = getIssuePaths({ ...delegatedPolicy, delegatedApproval: {} });++ assert.ok(issuePaths.includes("delegatedApproval.type"));+ assert.ok(issuePaths.includes("delegatedApproval.connectionId"));+ });++ it("ignores hidden bypassers on a delegated access policy", () => {+ const result = approvalPolicyFormSchema.safeParse({+ ...delegatedPolicy,+ userBypassers: [+ {+ type: BypasserType.User,+ id: "inactive-bypasser",+ isOrgMembershipActive: false+ }+ ]+ });++ assert.equal(result.success, true);+ });++ it("still requires approval steps when an access policy is not delegated", () => {+ const issuePaths = getIssuePaths({ ...delegatedPolicy, isDelegated: false });++ assert.ok(issuePaths.includes("sequenceApprovers"));+ });++ it("does not apply delegated rules to change policies", () => {+ const issuePaths = getIssuePaths({+ ...delegatedPolicy,+ policyType: PolicyType.ChangePolicy,+ delegatedApproval: {}+ });++ assert.ok(issuePaths.includes("userApprovers"));+ assert.ok(!issuePaths.includes("delegatedApproval.connectionId"));+ });});diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.ts b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.tsindex 8c63c54260..e4989d4c1c 100644--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.ts+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/approvalPolicyFormSchema.ts@@ -2,6 +2,7 @@ import ms from "ms";import { z } from "zod";import { ApproverType, BypasserType } from "@app/hooks/api/accessApproval/types";+import { DelegatedApprovalPolicyType } from "@app/hooks/api/delegatedApprovals/enums";import { EnforcementLevel, PolicyType } from "@app/hooks/api/policies/enums";import { getEmptyApprovalStepIndexes } from "./approvalPolicyFormUtils";@@ -106,27 +107,38 @@ export const approvalPolicyFormSchema = z.default([]).optional(),maxTimePeriod: durationSchema,- requestExpirationTime: durationSchema+ requestExpirationTime: durationSchema,+ isDelegated: z.boolean().default(false),+ delegatedApproval: z+ .object({+ type: z.nativeEnum(DelegatedApprovalPolicyType).optional(),+ connectionId: z.string().optional()+ })+ .optional()}).superRefine((data, ctx) => {- const bypasserCount = data.userBypassers.length + data.groupBypassers.length;- if (bypasserCount > MAX_POLICY_SUBJECTS) {- ctx.addIssue({- path: ["userBypassers"],- code: z.ZodIssueCode.custom,- message: `Cannot have more than ${MAX_POLICY_SUBJECTS} bypassers`- });- }+ const isDelegatedPolicy = data.policyType === PolicyType.AccessPolicy && data.isDelegated;- data.userBypassers.forEach((bypasser, index) => {- if (bypasser.isOrgMembershipActive === false) {+ if (!isDelegatedPolicy) {+ const bypasserCount = data.userBypassers.length + data.groupBypassers.length;+ if (bypasserCount > MAX_POLICY_SUBJECTS) {ctx.addIssue({- path: ["userBypassers", index],+ path: ["userBypassers"],code: z.ZodIssueCode.custom,- message: "Inactive users cannot bypass approval policies"+ message: `Cannot have more than ${MAX_POLICY_SUBJECTS} bypassers`});}- });++ data.userBypassers.forEach((bypasser, index) => {+ if (bypasser.isOrgMembershipActive === false) {+ ctx.addIssue({+ path: ["userBypassers", index],+ code: z.ZodIssueCode.custom,+ message: "Inactive users cannot bypass approval policies"+ });+ }+ });+ }if (data.policyType === PolicyType.ChangePolicy) {const approverCount = data.userApprovers.length + data.groupApprovers.length;@@ -172,6 +184,26 @@ export const approvalPolicyFormSchema = zreturn;}+ if (isDelegatedPolicy) {+ if (!data.delegatedApproval?.type) {+ ctx.addIssue({+ path: ["delegatedApproval", "type"],+ code: z.ZodIssueCode.custom,+ message: "Select a provider"+ });+ }++ if (!data.delegatedApproval?.connectionId) {+ ctx.addIssue({+ path: ["delegatedApproval", "connectionId"],+ code: z.ZodIssueCode.custom,+ message: "Select an app connection"+ });+ }++ return;+ }+const approvalSteps = data.sequenceApprovers ?? [];const approverCount = approvalSteps.reduce((count, step) => count + step.user.length + step.group.length,