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
import { useEffect, useMemo } from "react";
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
import { PlusIcon, TrashIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import { z } from "zod";
import { FieldLabelWithTooltip } from "@app/components/secret-rotations-v2/forms/shared";
import {
Button,
Combobox,
Field,
FieldError,
IconButton,
Input,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Tabs,
TabsContent,
TabsList,
TabsTrigger
} from "@app/components/v3";
import {
useCloudflareConnectionListPermissionGroups,
useCloudflareConnectionListZones
} from "@app/hooks/api/appConnections/cloudflare";
import {
CLOUDFLARE_POLICY_EFFECT_MAP,
CLOUDFLARE_POLICY_SCOPE_MAP,
CLOUDFLARE_POLICY_SCOPE_RESOURCE_MAP,
CloudflareApiTokenPolicyEffect,
CloudflareApiTokenPolicyScope,
CloudflareApiTokenRotationSchema,
explodePolicies,
isStoredPolicy
} from "../schemas/cloudflare-api-token-rotation-schema";
import { CLOUDFLARE_TOKEN_NAME_MAX_LENGTH } from "../schemas/shared";
import { CloudflareIpListField } from "./shared";
// The schema merges policy rows into the stored shape on submit, so `TSecretRotationV2Form` (the
// schema's *output* type) describes merged policies. The fields here edit rows, which is the input side.
type TCloudflareApiTokenForm = z.input<typeof CloudflareApiTokenRotationSchema>;
const DEFAULT_POLICY = {
effect: CloudflareApiTokenPolicyEffect.Allow,
scope: CloudflareApiTokenPolicyScope.Account,
zoneIds: [],
permissionGroupId: ""
};
enum ParameterTab {
General = "general",
Restrictions = "restrictions"
}
export const CloudflareApiTokenRotationParametersFields = () => {
const { control, watch, setValue, getValues } = useFormContext<TCloudflareApiTokenForm>();
const connectionId = watch("connection.id");
const policies = watch("parameters.policies");
// account-scoped: a zone outside the connection's account can't appear in an account token's policy
const { data: zones, isPending: isZonesPending } = useCloudflareConnectionListZones(
connectionId,
{ enabled: Boolean(connectionId) },
true
);
const { data: permissionGroups, isPending: isPermissionGroupsPending } =
useCloudflareConnectionListPermissionGroups(connectionId, {
enabled: Boolean(connectionId)
});
const policyFields = useFieldArray({
control,
name: "parameters.policies"
});
// Seed a first row on create, and on edit expand the stored merged policies into one row per
// permission group so the field array has something row-shaped to render.
useEffect(() => {
const currentPolicies = getValues("parameters.policies");
if (!currentPolicies?.length) {
setValue("parameters.policies", [DEFAULT_POLICY]);
return;
}
// the form type says rows, but `defaultValues` really does hand us the stored shape on edit
const storedPolicies = (currentPolicies as unknown[]).filter(isStoredPolicy);
if (storedPolicies.length) {
setValue("parameters.policies", explodePolicies(storedPolicies));
}
}, []);
// A permission group can only be attached to the resource types listed in its `scopes`. Groups that
// report no scopes are kept in every list so an upstream response change can't empty the dropdown.
const permissionGroupsByScope = useMemo(() => {
const filterByScope = (scope: CloudflareApiTokenPolicyScope) =>
(permissionGroups ?? []).filter(
(group) =>
!group.scopes.length || group.scopes.includes(CLOUDFLARE_POLICY_SCOPE_RESOURCE_MAP[scope])
);
return {
[CloudflareApiTokenPolicyScope.Account]: filterByScope(CloudflareApiTokenPolicyScope.Account),
[CloudflareApiTokenPolicyScope.AllZones]: filterByScope(
CloudflareApiTokenPolicyScope.AllZones
),
[CloudflareApiTokenPolicyScope.Zones]: filterByScope(CloudflareApiTokenPolicyScope.Zones)
};
}, [permissionGroups]);
return (
<Tabs defaultValue={ParameterTab.General}>
<TabsList variant="project" className="w-full justify-start">
<TabsTrigger value={ParameterTab.General}>General</TabsTrigger>
<TabsTrigger value={ParameterTab.Restrictions}>Restrictions</TabsTrigger>
</TabsList>
<TabsContent value={ParameterTab.General} className="space-y-4">
<Controller
control={control}
name="parameters.name"
render={({ field, fieldState: { error } }) => (
<Field data-invalid={Boolean(error)}>
<FieldLabelWithTooltip tooltip="The name for the generated Cloudflare API token. A timestamp is appended so each rotated token is distinct.">
Token Name
</FieldLabelWithTooltip>
<Input
{...field}
placeholder="infisical-rotated-token"
maxLength={CLOUDFLARE_TOKEN_NAME_MAX_LENGTH}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
</Field>
)}
/>
<div className="space-y-3">
<FieldLabelWithTooltip tooltip="Each row grants one permission group over the entire account, all zones in the account, or a specific set of zones. Rows targeting the same resources are combined into a single Cloudflare policy.">
Access Policies
</FieldLabelWithTooltip>
<div className="flex w-full flex-col gap-3">
{policyFields.fields.map(({ id: policyFieldId }, i) => {
const policyScope = policies?.[i]?.scope ?? CloudflareApiTokenPolicyScope.Account;
const permissionGroupOptions = permissionGroupsByScope[policyScope];
const showZones = policyScope === CloudflareApiTokenPolicyScope.Zones;
return (
// A card per policy rather than one flat row: four selects side by side don't fit the
// modal width, and cramming them wraps the placeholders and misaligns the labels.
<div key={policyFieldId} className="rounded-md border border-border bg-card p-3">
<div className="mb-1 flex items-center justify-between">
<span className="text-xs text-muted">Policy {i + 1}</span>
<IconButton
type="button"
aria-label="Delete policy"
variant="ghost"
onClick={() => {
const currentPolicies = getValues("parameters.policies");
if (currentPolicies && currentPolicies.length > 1) {
policyFields.remove(i);
} else {
setValue("parameters.policies", [DEFAULT_POLICY]);
}
}}
>
<TrashIcon />
</IconButton>
</div>
<div className="grid grid-cols-2 gap-x-3">
<Controller
control={control}
name={`parameters.policies.${i}.effect`}
render={({ field, fieldState: { error } }) => (
<Field data-invalid={Boolean(error)}>
<FieldLabelWithTooltip>Effect</FieldLabelWithTooltip>
<Select
value={field.value}
onValueChange={(nextValue) => {
// Radix Select can emit a spurious empty onValueChange while options mount.
if (!nextValue || nextValue === field.value) return;
field.onChange(nextValue);
}}
>
<SelectTrigger className="w-full" isError={Boolean(error)}>
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
{Object.entries(CLOUDFLARE_POLICY_EFFECT_MAP).map(
([effect, label]) => (
<SelectItem key={effect} value={effect}>
{label}
</SelectItem>
)
)}
</SelectContent>
</Select>
<FieldError>{error?.message}</FieldError>
</Field>
)}
/>
<Controller
control={control}
name={`parameters.policies.${i}.scope`}
render={({ field, fieldState: { error } }) => (
<Field data-invalid={Boolean(error)}>
<FieldLabelWithTooltip>Scope</FieldLabelWithTooltip>
<Select
value={field.value}
onValueChange={(scope) => {
// Radix Select can emit a spurious empty onValueChange while options mount.
if (!scope || scope === field.value) return;
field.onChange(scope);
// the zones and permission group from the previous scope no longer apply
setValue(`parameters.policies.${i}.zoneIds`, []);
setValue(`parameters.policies.${i}.permissionGroupId`, "");
}}
>
<SelectTrigger className="w-full" isError={Boolean(error)}>
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
{Object.entries(CLOUDFLARE_POLICY_SCOPE_MAP).map(([scope, label]) => (
<SelectItem key={scope} value={scope}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError>{error?.message}</FieldError>
</Field>
)}
/>
{showZones && (
<Controller
control={control}
name={`parameters.policies.${i}.zoneIds`}
render={({ field: { value, onChange, onBlur }, fieldState: { error } }) => (
<Field className="mt-3" data-invalid={Boolean(error)}>
<FieldLabelWithTooltip>Zones</FieldLabelWithTooltip>
<Combobox
multiple
isLoading={isZonesPending && Boolean(connectionId)}
isDisabled={!connectionId}
options={zones}
placeholder="Select zones..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
getOptionKeywords={(option) => [option.id]}
value={zones?.filter((zone) => (value ?? []).includes(zone.id)) ?? []}
onBlur={onBlur}
onValueChange={(option) => onChange(option.map((zone) => zone.id))}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
</Field>
)}
/>
)}
<Controller
control={control}
name={`parameters.policies.${i}.permissionGroupId`}
render={({ field: { value, onChange, onBlur }, fieldState: { error } }) => (
<Field
className={twMerge("mt-3", showZones ? "" : "col-span-2")}
data-invalid={Boolean(error)}
>
<FieldLabelWithTooltip>Permission group</FieldLabelWithTooltip>
<Combobox
isLoading={isPermissionGroupsPending && Boolean(connectionId)}
isDisabled={!connectionId}
options={permissionGroupOptions}
placeholder="Select a permission group..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
getOptionKeywords={(option) => [option.id]}
value={
permissionGroupOptions.find((group) => group.id === value) ?? null
}
onBlur={onBlur}
onValueChange={(option) => onChange(option.id)}
isClearable={false}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
</Field>
)}
/>
</div>
</div>
);
})}
<div>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => policyFields.append(DEFAULT_POLICY)}
>
<PlusIcon />
Add policy
</Button>
</div>
</div>
</div>
</TabsContent>
<TabsContent value={ParameterTab.Restrictions} className="space-y-4">
<CloudflareIpListField
control={control}
name="parameters.allowedIps"
label="Allowed IPs"
tooltipText="The generated token can only be used from these IP addresses or CIDR blocks. One entry per line. Leave empty to allow any IP."
/>
<CloudflareIpListField
control={control}
name="parameters.disallowedIps"
label="Disallowed IPs"
tooltipText="The generated token cannot be used from these IP addresses or CIDR blocks. One entry per line."
/>
</TabsContent>
</Tabs>
);
};