Skip to content

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

refactor: enhance permission condition handling for secret actions with dynamic conditions

Victor Santos9ea2411a6365
diff --git a/backend/src/ee/services/permission/permission-fns.ts b/backend/src/ee/services/permission/permission-fns.ts
index 0da5ad3b25..8df01a2a79 100644
--- a/backend/src/ee/services/permission/permission-fns.ts
+++ b/backend/src/ee/services/permission/permission-fns.ts
@@ -13,6 +13,7 @@ import {
ProjectPermissionSet,
ProjectPermissionSub,
ProjectPermissionV2Schema,
+ SecretActionAllowedConditions,
SecretSubjectFields
} from "./project-permission";
@@ -100,6 +101,23 @@ export function checkForInvalidPermissionCombination(permissions: z.infer<typeof
}. You cannot select Read Value or Describe Secret if you have selected Read. The Read permission is a legacy action which has been replaced by Describe Secret and Read Value.`
});
}
+
+ // Validate conditions against allowed conditions per action
+ if (permission.conditions) {
+ const conditionKeys = Object.keys(permission.conditions);
+ for (const action of permission.action) {
+ const allowedConditions = SecretActionAllowedConditions[action as ProjectPermissionSecretActions];
+ if (allowedConditions) {
+ for (const condKey of conditionKeys) {
+ if (!allowedConditions.includes(condKey)) {
+ throw new BadRequestError({
+ message: `Condition "${condKey}" is not allowed for action "${action}"`
+ });
+ }
+ }
+ }
+ }
+ }
}
}
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 5103f01145..7ab98e30cb 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -47,9 +47,20 @@ export enum ProjectPermissionSecretActions {
ReadValue = "readValue",
Create = "create",
Edit = "edit",
- Delete = "delete"
+ Delete = "delete",
+ // Test actions for dynamic conditions feature - to be removed after testing
+ ImportSecret = "importSecret",
+ DuplicateSecret = "duplicateSecret"
}
+// Mapping of secret actions to their allowed condition keys
+// Actions without restrictions (undefined or not in map) allow all conditions
+export const SecretActionAllowedConditions: Partial<Record<ProjectPermissionSecretActions, string[]>> = {
+ // Test actions with restricted conditions - to be removed after testing
+ [ProjectPermissionSecretActions.ImportSecret]: ["environment"],
+ [ProjectPermissionSecretActions.DuplicateSecret]: ["environment", "secretPath", "secretName"]
+};
+
export enum ProjectPermissionCmekActions {
Read = "read",
Create = "create",
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index d4c50f7704..84b88ee4ed 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -24,7 +24,10 @@ export enum ProjectPermissionSecretActions {
Create = "create",
Edit = "edit",
Delete = "delete",
- Subscribe = "subscribe"
+ Subscribe = "subscribe",
+ // Test actions for dynamic conditions feature - to be removed after testing
+ ImportSecret = "importSecret",
+ DuplicateSecret = "duplicateSecret"
}
export enum ProjectPermissionDynamicSecretActions {
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ConditionsFields.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ConditionsFields.tsx
index 999f83dbfc..9d48bd0e83 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ConditionsFields.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ConditionsFields.tsx
@@ -1,6 +1,7 @@
-import { Fragment } from "react";
+import { Fragment, useMemo } from "react";
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
import { InfoIcon, PlusIcon, TrashIcon, TriangleAlertIcon } from "lucide-react";
+import { twMerge } from "tailwind-merge";
import {
Badge,
@@ -30,21 +31,69 @@ import {
import {
getConditionOperatorHelperInfo,
+ getDefaultOperatorForCondition,
renderOperatorSelectItems
} from "./PermissionConditionHelpers";
import { TFormSchema } from "./ProjectRoleModifySection.utils";
-export const ConditionsFields = ({
- isDisabled,
- subject,
- position,
- selectOptions
-}: {
+type ActionConditionsMap = Partial<Record<string, string[]>>;
+
+type ConditionsFieldsProps = {
isDisabled: boolean | undefined;
subject: ConditionalProjectPermissionSubject;
position: number;
selectOptions: [{ value: string; label: string }, ...{ value: string; label: string }[]];
-}) => {
+ selectedActions?: string[];
+ actionConditionsMap?: ActionConditionsMap;
+};
+
+const computeAllowedConditions = (
+ selectedActions: string[] | undefined,
+ actionConditionsMap: ActionConditionsMap | undefined,
+ allConditions: string[]
+): string[] => {
+ if (!selectedActions || selectedActions.length === 0 || !actionConditionsMap) {
+ return allConditions;
+ }
+
+ const actionsWithRestrictions = selectedActions.filter(
+ (action) => actionConditionsMap[action] !== undefined
+ );
+
+ if (actionsWithRestrictions.length === 0) {
+ return allConditions;
+ }
+
+ // Return intersection of all allowed conditions for actions with restrictions
+ return actionsWithRestrictions.reduce<string[]>((acc, action) => {
+ const allowed = actionConditionsMap[action];
+ if (!allowed) return acc;
+ if (acc.length === 0) return allowed;
+ return acc.filter((cond) => allowed.includes(cond));
+ }, []);
+};
+
+const getDisallowingActions = (
+ conditionValue: string,
+ selectedActions: string[] | undefined,
+ actionConditionsMap: ActionConditionsMap | undefined
+): string[] => {
+ if (!selectedActions || !actionConditionsMap) return [];
+
+ return selectedActions.filter((action) => {
+ const allowed = actionConditionsMap[action];
+ return allowed !== undefined && !allowed.includes(conditionValue);
+ });
+};
+
+export const ConditionsFields = ({
+ isDisabled,
+ subject,
+ position,
+ selectOptions,
+ selectedActions,
+ actionConditionsMap
+}: ConditionsFieldsProps) => {
const {
control,
watch,
@@ -56,6 +105,37 @@ export const ConditionsFields = ({
name: `permissions.${subject}.${position}.conditions` as const
});
+ const allConditionValues = useMemo(() => selectOptions.map((opt) => opt.value), [selectOptions]);
+
+ const allowedConditions = useMemo(
+ () => computeAllowedConditions(selectedActions, actionConditionsMap, allConditionValues),
+ [selectedActions, actionConditionsMap, allConditionValues]
+ );
+
+ const usedConditionTypes = useMemo(() => {
+ return items.fields.map((_, i) => {
+ const lhs = watch(`permissions.${subject}.${position}.conditions.${i}.lhs` as const);
+ return lhs;
+ });
+ }, [items.fields, watch, subject, position]);
+
+ const availableConditionsToAdd = useMemo(() => {
+ return selectOptions.filter(
+ ({ value }) => allowedConditions.includes(value) && !usedConditionTypes.includes(value)
+ );
+ }, [selectOptions, allowedConditions, usedConditionTypes]);
+
+ const canAddCondition = availableConditionsToAdd.length > 0;
+
+ const getNewConditionDefaults = () => {
+ const conditionType = availableConditionsToAdd[0]?.value || selectOptions[0].value;
+ return {
+ lhs: conditionType,
+ operator: getDefaultOperatorForCondition(conditionType),
+ rhs: ""
+ };
+ };
+
if (isDisabled && items.fields.length === 0) {
return null;
}
@@ -84,23 +164,26 @@ export const ConditionsFields = ({
</TooltipContent>
</Tooltip>
</div>
- <Button
- type="button"
- variant="outline"
- size="xs"
- className="mt-2"
- isDisabled={isDisabled}
- onClick={() =>
- items.append({
- lhs: selectOptions[0].value,
- operator: PermissionConditionOperators.$EQ,
- rhs: ""
- })
- }
- >
- <PlusIcon className="size-4" />
- Add Condition
- </Button>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="mt-2"
+ isDisabled={isDisabled || !canAddCondition}
+ onClick={() => items.append(getNewConditionDefaults())}
+ >
+ <PlusIcon className="size-4" />
+ Add Condition
+ </Button>
+ </span>
+ </TooltipTrigger>
+ {!canAddCondition && !isDisabled && (
+ <TooltipContent side="top">All available conditions have been added</TooltipContent>
+ )}
+ </Tooltip>
</div>
<div className="mt-2 flex flex-col space-y-2">
{items.fields.length === 0 ? (
@@ -120,6 +203,11 @@ export const ConditionsFields = ({
rhs: string;
operator: string;
}) || {};
+
+ const availableOptionsForRow = selectOptions.filter(
+ ({ value }) => !usedConditionTypes.includes(value) || value === condition.lhs
+ );
+
return (
<Fragment key={el.id}>
<div className="flex items-center gap-2 bg-card first:rounded-t-md last:rounded-b-md">
@@ -158,11 +246,42 @@ export const ConditionsFields = ({
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
- {selectOptions.map(({ value, label }) => (
- <SelectItem key={value} value={value}>
- {label}
- </SelectItem>
- ))}
+ {availableOptionsForRow.map(({ value, label }) => {
+ const isAllowed = allowedConditions.includes(value);
+ const disallowingActions = getDisallowingActions(
+ value,
+ selectedActions,
+ actionConditionsMap
+ );
+
+ if (!isAllowed) {
+ return (
+ <Tooltip key={value}>
+ <TooltipTrigger asChild>
+ <div>
+ <SelectItem
+ value={value}
+ disabled
+ className={twMerge("cursor-not-allowed opacity-50")}
+ >
+ {label}
+ </SelectItem>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-xs">
+ This condition is not available for the actions:{" "}
+ {disallowingActions.join(", ")}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <SelectItem key={value} value={value}>
+ {label}
+ </SelectItem>
+ );
+ })}
</SelectContent>
</Select>
</FieldContent>
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx
index 295e7c0764..5bdc6a8dd7 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx
@@ -17,6 +17,15 @@ export const getConditionOperatorHelperInfo = (type: PermissionConditionOperator
}
};
+export const getDefaultOperatorForCondition = (type: string): PermissionConditionOperators => {
+ switch (type) {
+ case "secretTags":
+ return PermissionConditionOperators.$IN;
+ default:
+ return PermissionConditionOperators.$EQ;
+ }
+};
+
// scott: we may need to pass the subject in the future to further refine returned items
export const renderOperatorSelectItems = (type: string) => {
switch (type) {
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 543f2d453d..8ca62e6276 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -80,7 +80,10 @@ const SecretPolicyActionSchema = z.object({
[ProjectPermissionSecretActions.Edit]: z.boolean().optional(),
[ProjectPermissionSecretActions.Delete]: z.boolean().optional(),
[ProjectPermissionSecretActions.Create]: z.boolean().optional(),
- [ProjectPermissionSecretActions.Subscribe]: z.boolean().optional()
+ [ProjectPermissionSecretActions.Subscribe]: z.boolean().optional(),
+ // Test actions for dynamic conditions feature - to be removed after testing
+ [ProjectPermissionSecretActions.ImportSecret]: z.boolean().optional(),
+ [ProjectPermissionSecretActions.DuplicateSecret]: z.boolean().optional()
});
const ApprovalPolicyActionSchema = z.object({
@@ -366,6 +369,49 @@ const ConditionSchema = z
}
);
+// Mapping of secret actions to their allowed condition keys
+// undefined means all conditions are allowed (backwards compatible)
+export const SECRET_ACTION_ALLOWED_CONDITIONS: Partial<
+ Record<ProjectPermissionSecretActions, string[]>
+> = {
+ // Test actions with restricted conditions - to be removed after testing
+ [ProjectPermissionSecretActions.ImportSecret]: ["environment"],
+ [ProjectPermissionSecretActions.DuplicateSecret]: ["environment", "secretPath", "secretName"]
+};
+
+const SecretPolicyActionWithConditionsSchema = SecretPolicyActionSchema.extend({
+ inverted: z.boolean().optional(),
+ conditions: ConditionSchema
+}).refine(
+ (data) => {
+ if (!data.conditions || data.conditions.length === 0) return true;
+
+ const selectedActions = Object.entries(data)
+ .filter(
+ ([key, value]) =>
+ value === true &&
+ Object.values(ProjectPermissionSecretActions).includes(
+ key as ProjectPermissionSecretActions
+ )
+ )
+ .map(([key]) => key as ProjectPermissionSecretActions);
+
+ if (selectedActions.length === 0) return true;
+
+ const conditionKeys = data.conditions.map((c) => c.lhs);
+
+ return selectedActions.every((action) => {
+ const allowedConditions = SECRET_ACTION_ALLOWED_CONDITIONS[action];
+ if (!allowedConditions) return true;
+ return conditionKeys.every((condKey) => allowedConditions.includes(condKey));
+ });
+ },
+ {
+ message: "Some conditions are not available for the selected actions",
+ path: ["conditions"]
+ }
+);
+
export const projectRoleFormSchema = z.object({
name: z.string().trim(),
description: z.string().trim().nullish(),
@@ -376,12 +422,7 @@ export const projectRoleFormSchema = z.object({
.refine((val) => val !== "custom", { message: "Cannot use custom as its a keyword" }),
permissions: z
.object({
- [ProjectPermissionSub.Secrets]: SecretPolicyActionSchema.extend({
- inverted: z.boolean().optional(),
- conditions: ConditionSchema
- })
- .array()
- .default([]),
+ [ProjectPermissionSub.Secrets]: SecretPolicyActionWithConditionsSchema.array().default([]),
[ProjectPermissionSub.SecretFolders]: GeneralPolicyActionSchema.extend({
inverted: z.boolean().optional(),
conditions: ConditionSchema
@@ -1618,6 +1659,7 @@ export type TProjectPermissionObject = {
NonNullable<NonNullable<TFormSchema["permissions"]>[K]>[number],
"conditions" | "inverted"
>;
+ allowedConditions?: string[];
}[];
};
};
@@ -1658,6 +1700,19 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
label: "Create",
description: "Create new secrets in the project",
value: ProjectPermissionSecretActions.Create
+ },
+ // Test actions for dynamic conditions feature - to be removed after testing
+ {
+ label: "Import Secret (Test)",
+ description: "Test action that only allows environment condition",
+ value: ProjectPermissionSecretActions.ImportSecret,
+ allowedConditions: ["environment"]
+ },
+ {
+ label: "Duplicate Secret (Test)",
+ description: "Test action that allows environment, secretPath, and secretName conditions",
+ value: ProjectPermissionSecretActions.DuplicateSecret,
+ allowedConditions: ["environment", "secretPath", "secretName"]
}
]
},
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/SecretPermissionConditions.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/SecretPermissionConditions.tsx
index 9978b3e458..9c2f9133f2 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/SecretPermissionConditions.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/SecretPermissionConditions.tsx
@@ -1,6 +1,13 @@
-import { ProjectPermissionSub } from "@app/context/ProjectPermissionContext/types";
+import { useMemo } from "react";
+import { useFormContext } from "react-hook-form";
+
+import {
+ ProjectPermissionSecretActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
import { ConditionsFields } from "./ConditionsFields";
+import { SECRET_ACTION_ALLOWED_CONDITIONS, TFormSchema } from "./ProjectRoleModifySection.utils";
type Props = {
position?: number;
@@ -8,6 +15,23 @@ type Props = {
};
export const SecretPermissionConditions = ({ position = 0, isDisabled }: Props) => {
+ const { watch } = useFormContext<TFormSchema>();
+ const permissionRule = watch(`permissions.${ProjectPermissionSub.Secrets}.${position}`);
+
+ const selectedActions = useMemo(() => {
+ if (!permissionRule) return [];
+
+ return Object.entries(permissionRule)
+ .filter(
+ ([key, value]) =>
+ value === true &&
+ Object.values(ProjectPermissionSecretActions).includes(
+ key as ProjectPermissionSecretActions
+ )
+ )
+ .map(([key]) => key);
+ }, [permissionRule]);
+
return (
<ConditionsFields
isDisabled={isDisabled}
@@ -19,6 +43,8 @@ export const SecretPermissionConditions = ({ position = 0, isDisabled }: Props)
{ value: "secretName", label: "Secret Name" },
{ value: "secretTags", label: "Secret Tags" }
]}
+ selectedActions={selectedActions}
+ actionConditionsMap={SECRET_ACTION_ALLOWED_CONDITIONS}
/>
);
};