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
feat(rbac): added glob support in permission and revealed settings
Akhil Mohana4ef829046dd
diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 3a65f61d63..f5c55cf56f 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -19,6 +19,7 @@"@sentry/tracing": "^7.48.0","@types/crypto-js": "^4.1.1","@types/libsodium-wrappers": "^0.7.10",+ "@ucast/mongo2js": "^1.3.4","argon2": "^0.30.3","aws-sdk": "^2.1364.0","axios": "^1.3.5",diff --git a/backend/package.json b/backend/package.jsonindex 21f7af45aa..08db10eccb 100644--- a/backend/package.json+++ b/backend/package.json@@ -10,6 +10,7 @@"@sentry/tracing": "^7.48.0","@types/crypto-js": "^4.1.1","@types/libsodium-wrappers": "^0.7.10",+ "@ucast/mongo2js": "^1.3.4","argon2": "^0.30.3","aws-sdk": "^2.1364.0","axios": "^1.3.5",diff --git a/backend/src/ee/controllers/v1/secretController.ts b/backend/src/ee/controllers/v1/secretController.tsindex 1203f406d6..58b7e62649 100644--- a/backend/src/ee/controllers/v1/secretController.ts+++ b/backend/src/ee/controllers/v1/secretController.ts@@ -1,7 +1,7 @@import { ForbiddenError, subject } from "@casl/ability";import { Request, Response } from "express";import { validateRequest } from "../../../helpers/validation";-import { Secret } from "../../../models";+import { Folder, Secret } from "../../../models";import {ProjectPermissionActions,ProjectPermissionSub,@@ -11,6 +11,7 @@ import { BadRequestError } from "../../../utils/errors";import * as reqValidator from "../../../validation";import { SecretVersion } from "../../models";import { EESecretService } from "../../services";+import { getFolderWithPathFromId } from "../../../services/FolderService";/*** Return secret versions for secret with id [secretId]@@ -164,10 +165,6 @@ export const rollbackSecretVersion = async (req: Request, res: Response) => {ProjectPermissionActions.Create,ProjectPermissionSub.SecretRollback);- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionActions.Edit,- subject(ProjectPermissionSub.Secrets, { environment: toBeUpdatedSec.environment })- );// validate secret versionconst oldSecretVersion = await SecretVersion.findOne({@@ -194,6 +191,15 @@ export const rollbackSecretVersion = async (req: Request, res: Response) => {keyEncoding} = oldSecretVersion;+ let secretPath = "/";+ const folders = await Folder.findOne({ workspace, environment });+ if (folders)+ secretPath = getFolderWithPathFromId(folders.nodes, folder || "root")?.folderPath || "/";+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionActions.Edit,+ subject(ProjectPermissionSub.Secrets, { environment: toBeUpdatedSec.environment, secretPath })+ );+// update secretconst secret = await Secret.findByIdAndUpdate(secretId,diff --git a/backend/src/services/ProjectRoleService.ts b/backend/src/services/ProjectRoleService.tsindex 5a2d24e007..10dbd2302d 100644--- a/backend/src/services/ProjectRoleService.ts+++ b/backend/src/services/ProjectRoleService.ts@@ -3,11 +3,31 @@ import {ForcedSubject,MongoAbility,RawRuleOf,+ buildMongoQueryMatcher,createMongoAbility} from "@casl/ability";import { Membership } from "../models";import { IRole } from "../models/role";import { BadRequestError, UnauthorizedRequestError } from "../utils/errors";+import { FieldCondition, FieldInstruction, JsInterpreter } from "@ucast/mongo2js";+import picomatch from "picomatch";++const $glob: FieldInstruction<string> = {+ type: "field",+ validate(instruction, value) {+ if (typeof value !== "string") {+ throw new Error(`"${instruction.name}" expects value to be a string`);+ }+ }+};++const glob: JsInterpreter<FieldCondition<string>> = (node, object, context) => {+ const secretPath = context.get(object, node.field);+ const permissionSecretGlobPath = node.value;+ return picomatch.isMatch(secretPath, permissionSecretGlobPath, { strictSlashes: false });+};++export const conditionsMatcher = buildMongoQueryMatcher({ $glob }, { glob });export enum ProjectPermissionActions {Read = "read",@@ -36,7 +56,7 @@ export enum ProjectPermissionSub {type SubjectFields = {environment: string;- secretPath?: string;+ secretPath: string;};export type ProjectPermissionSet =@@ -144,7 +164,7 @@ const buildAdminPermission = () => {can(ProjectPermissionActions.Edit, ProjectPermissionSub.Workspace);can(ProjectPermissionActions.Delete, ProjectPermissionSub.Workspace);- return build();+ return build({ conditionsMatcher });};export const adminProjectPermissions = buildAdminPermission();@@ -180,7 +200,7 @@ const buildMemberPermission = () => {can(ProjectPermissionActions.Read, ProjectPermissionSub.AuditLogs);can(ProjectPermissionActions.Read, ProjectPermissionSub.IpAllowList);- return build();+ return build({ conditionsMatcher });};export const memberProjectPermissions = buildMemberPermission();@@ -203,7 +223,7 @@ const buildViewerPermission = () => {can(ProjectPermissionActions.Read, ProjectPermissionSub.AuditLogs);can(ProjectPermissionActions.Read, ProjectPermissionSub.IpAllowList);- return build();+ return build({ conditionsMatcher });};export const viewerProjectPermission = buildViewerPermission();@@ -228,7 +248,9 @@ export const getUserProjectPermissions = async (userId: string, workspaceId: strif (membership.role === "viewer") return { permission: viewerProjectPermission, membership };if (membership.role === "custom") {- const permission = createMongoAbility<ProjectPermissionSet>(membership.customRole.permissions);+ const permission = createMongoAbility<ProjectPermissionSet>(membership.customRole.permissions, {+ conditionsMatcher+ });return { permission, membership };}diff --git a/backend/src/services/RoleService.ts b/backend/src/services/RoleService.tsindex 6481282464..bc5ef74535 100644--- a/backend/src/services/RoleService.ts+++ b/backend/src/services/RoleService.ts@@ -3,6 +3,7 @@ import { MembershipOrg } from "../models";import { IRole } from "../models/role";import { BadRequestError, UnauthorizedRequestError } from "../utils/errors";import { ACCEPTED } from "../variables";+import { conditionsMatcher } from "./ProjectRoleService";export enum OrgPermissionActions {Read = "read",@@ -74,7 +75,7 @@ const buildAdminPermission = () => {can(OrgPermissionActions.Edit, OrgPermissionSubjects.Billing);can(OrgPermissionActions.Delete, OrgPermissionSubjects.Billing);- return build();+ return build({ conditionsMatcher });};export const adminPermissions = buildAdminPermission();@@ -92,7 +93,7 @@ const buildMemberPermission = () => {can(OrgPermissionActions.Read, OrgPermissionSubjects.IncidentAccount);can(OrgPermissionActions.Read, OrgPermissionSubjects.SecretScanning);- return build();+ return build({ conditionsMatcher });};export const memberPermissions = buildMemberPermission();@@ -119,7 +120,9 @@ export const getUserOrgPermissions = async (userId: string, orgId: string) => {if (membership.role === "member") return { permission: memberPermissions, membership };if (membership.role === "custom") {- const permission = createMongoAbility<OrgPermissionSet>(membership.customRole.permissions);+ const permission = createMongoAbility<OrgPermissionSet>(membership.customRole.permissions, {+ conditionsMatcher+ });return { permission, membership };}diff --git a/backend/src/validation/role.ts b/backend/src/validation/role.tsindex efc659a230..e3ecafe599 100644--- a/backend/src/validation/role.ts+++ b/backend/src/validation/role.ts@@ -11,7 +11,9 @@ export const CreateRoleSchema = z.object({.object({subject: z.string().trim(),action: z.string().trim(),- conditions: z.record(z.union([z.string().trim(), z.number()])).optional()+ conditions: z+ .record(z.union([z.string().trim(), z.number(), z.object({ $glob: z.string() })]))+ .optional()}).array()})@@ -31,7 +33,9 @@ export const UpdateRoleSchema = z.object({.object({subject: z.string().trim(),action: z.string().trim(),- conditions: z.record(z.union([z.string().trim(), z.number()])).optional()+ conditions: z+ .record(z.union([z.string().trim(), z.number(), z.object({ $glob: z.string() })]))+ .optional()}).array().optional()diff --git a/backend/src/validation/secrets.ts b/backend/src/validation/secrets.tsindex afa77cbf07..700a3ea5d5 100644--- a/backend/src/validation/secrets.ts+++ b/backend/src/validation/secrets.ts@@ -189,7 +189,7 @@ export const BatchSecretsV2 = z.object({workspaceId: z.string().trim(),folderId: z.string().trim().default("root"),environment: z.string().trim(),- secretPath: z.string().trim().optional(),+ secretPath: z.string().trim().default("/"),requests: z.discriminatedUnion("method", [z.object({@@ -328,7 +328,7 @@ export const CreateSecretV3 = z.object({secretCommentCiphertext: z.string().trim().optional(),secretCommentIV: z.string().trim().optional(),secretCommentTag: z.string().trim().optional(),- metadata: z.record(z.string()).optional(),+ metadata: z.record(z.string()).optional()}),params: z.object({secretName: z.string().trim()diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 262051bcfa..e6847b42cf 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -41,6 +41,7 @@"@stripe/stripe-js": "^1.46.0","@tanstack/react-query": "^4.23.0","@types/argon2-browser": "^1.18.1",+ "@ucast/mongo2js": "^1.3.4","add": "^2.0.6","argon2-browser": "^1.18.0","axios": "^0.27.2",@@ -65,6 +66,7 @@"markdown-it": "^13.0.1","next": "^12.3.4","nprogress": "^0.2.0",+ "picomatch": "^2.3.1","posthog-js": "^1.58.0","query-string": "^7.1.3","react": "^17.0.2",@@ -106,6 +108,7 @@"@tailwindcss/typography": "^0.5.4","@types/jsrp": "^0.2.4","@types/node": "^18.11.9",+ "@types/picomatch": "^2.3.0","@types/react": "^18.0.26","@types/sanitize-html": "^2.9.0","@typescript-eslint/eslint-plugin": "^5.48.1",@@ -8391,6 +8394,12 @@"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz","integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA=="},+ "node_modules/@types/picomatch": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-2.3.0.tgz",+ "integrity": "sha512-O397rnSS9iQI4OirieAtsDqvCj4+3eY1J+EPdNTKuHuRWIfUoGyzX294o8C4KJYaLqgSrd2o60c5EqCU8Zv02g==",+ "dev": true+ },"node_modules/@types/pretty-hrtime": {"version": "1.0.1","resolved": "https://registry.npmjs.org/@types/pretty-hrtime/-/pretty-hrtime-1.0.1.tgz",@@ -29414,6 +29423,12 @@"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz","integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA=="},+ "@types/picomatch": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-2.3.0.tgz",+ "integrity": "sha512-O397rnSS9iQI4OirieAtsDqvCj4+3eY1J+EPdNTKuHuRWIfUoGyzX294o8C4KJYaLqgSrd2o60c5EqCU8Zv02g==",+ "dev": true+ },"@types/pretty-hrtime": {"version": "1.0.1","resolved": "https://registry.npmjs.org/@types/pretty-hrtime/-/pretty-hrtime-1.0.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 1e73e4c7e0..d954da2a83 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -49,6 +49,7 @@"@stripe/stripe-js": "^1.46.0","@tanstack/react-query": "^4.23.0","@types/argon2-browser": "^1.18.1",+ "@ucast/mongo2js": "^1.3.4","add": "^2.0.6","argon2-browser": "^1.18.0","axios": "^0.27.2",@@ -73,6 +74,7 @@"markdown-it": "^13.0.1","next": "^12.3.4","nprogress": "^0.2.0",+ "picomatch": "^2.3.1","posthog-js": "^1.58.0","query-string": "^7.1.3","react": "^17.0.2",@@ -114,6 +116,7 @@"@tailwindcss/typography": "^0.5.4","@types/jsrp": "^0.2.4","@types/node": "^18.11.9",+ "@types/picomatch": "^2.3.0","@types/react": "^18.0.26","@types/sanitize-html": "^2.9.0","@typescript-eslint/eslint-plugin": "^5.48.1",diff --git a/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx b/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsxindex a8b9652699..77ca8c24f5 100644--- a/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx+++ b/frontend/src/components/AddTagPopoverContent/AddTagPopoverContent.tsx@@ -1,78 +1,92 @@-import { faPlus } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { Checkbox, PopoverContent } from "@app/components/v2";+import { Button, Checkbox, PopoverContent } from "@app/components/v2";+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";import { WsTag } from "../../hooks/api/tags/types";+import { ProjectPermissionCan } from "../permissions";interface Props {- wsTags: WsTag[] | undefined;- secKey: string;- selectedTagIds: Record<string, boolean>;- handleSelectTag: (wsTag: WsTag) => void;- handleTagOnMouseEnter: (wsTag: WsTag) => void;- handleTagOnMouseLeave: () => void;- checkIfTagIsVisible: (wsTag: WsTag) => boolean;- handleOnCreateTagOpen: () => void+ wsTags: WsTag[] | undefined;+ secKey: string;+ selectedTagIds: Record<string, boolean>;+ handleSelectTag: (wsTag: WsTag) => void;+ handleTagOnMouseEnter: (wsTag: WsTag) => void;+ handleTagOnMouseLeave: () => void;+ checkIfTagIsVisible: (wsTag: WsTag) => boolean;+ handleOnCreateTagOpen: () => void;}const AddTagPopoverContent = ({- wsTags,- secKey,- selectedTagIds,- handleSelectTag,- handleTagOnMouseEnter,- handleTagOnMouseLeave,- checkIfTagIsVisible,- handleOnCreateTagOpen+ wsTags,+ secKey,+ selectedTagIds,+ handleSelectTag,+ handleTagOnMouseEnter,+ handleTagOnMouseLeave,+ checkIfTagIsVisible,+ handleOnCreateTagOpen}: Props) => {- return (- <PopoverContent- side="left"- className="relative max-h-96 w-auto min-w-[200px] p-2 overflow-y-auto overflow-x-hidden border border-mineshaft-600 bg-mineshaft-800 text-bunker-200"- hideCloseBtn- >- <div className=" text-center text-sm font-medium text-bunker-200">- Add tags to {secKey || "this secret"}- </div>- <div className="absolute left-0 w-full border-mineshaft-600 border-t mt-2" />- <div className="flex flex-col space-y-1.5">- {wsTags?.map((wsTag: WsTag) => (- <div key={`tag-${wsTag._id}`} className="mt-4 h-[32px] relative flex items-center justify-start hover:border-mineshaft-600 hover:border hover:bg-mineshaft-700 p-2 rounded-md hover:text-bunker-200 bg-none"- onClick={() => handleSelectTag(wsTag)}- onMouseEnter={() => handleTagOnMouseEnter(wsTag)}- onMouseLeave={() => handleTagOnMouseLeave()}- tabIndex={0} role="button"- onKeyDown={() => { }}>- {-- (checkIfTagIsVisible(wsTag) || selectedTagIds?.[wsTag.slug]) && <Checkbox- id="autoCapitalization"- isChecked={selectedTagIds?.[wsTag.slug]}- className="absolute top-[50%] translate-y-[-50%] left-[10px] "- checkIndicatorBg={`${!selectedTagIds?.[wsTag.slug] ? "text-transparent" : "text-mineshaft-800"}`}- />- }- <div className="ml-7 flex items-center gap-3">- <div className="w-[10px] h-[10px] rounded-full" style={{ background: wsTag?.tagColor ? wsTag.tagColor : "#bec2c8" }}> </div>- <span >- {wsTag.slug}- </span>- </div>- </div>- ))}- <div- className="h-[32px] relative flex items-center cursor-pointer justify-start border-mineshaft-600 border bg-mineshaft-700 p-2 rounded-md hover:text-bunker-200 bg-none"- onClick={() => handleOnCreateTagOpen()}- tabIndex={0} role="button"- onKeyDown={() => { }}>- <FontAwesomeIcon icon={faPlus} className="ml-1 mr-2" />- <span> Add new tag</span>- </div>+ return (+ <PopoverContent+ side="left"+ className="relative max-h-96 w-auto min-w-[200px] p-2 overflow-y-auto overflow-x-hidden border border-mineshaft-600 bg-mineshaft-800 text-bunker-200"+ hideCloseBtn+ >+ <div className=" text-center text-sm font-medium text-bunker-200">+ Add tags to {secKey || "this secret"}+ </div>+ <div className="absolute left-0 w-full border-mineshaft-600 border-t mt-2" />+ <div className="flex flex-col space-y-1.5">+ {wsTags?.map((wsTag: WsTag) => (+ <div+ key={`tag-${wsTag._id}`}+ className="mt-4 h-[32px] relative flex items-center justify-start hover:border-mineshaft-600 hover:border hover:bg-mineshaft-700 p-2 rounded-md hover:text-bunker-200 bg-none"+ onClick={() => handleSelectTag(wsTag)}+ onMouseEnter={() => handleTagOnMouseEnter(wsTag)}+ onMouseLeave={() => handleTagOnMouseLeave()}+ tabIndex={0}+ role="button"+ onKeyDown={() => {}}+ >+ {(checkIfTagIsVisible(wsTag) || selectedTagIds?.[wsTag.slug]) && (+ <Checkbox+ id="autoCapitalization"+ isChecked={selectedTagIds?.[wsTag.slug]}+ className="absolute top-[50%] translate-y-[-50%] left-[10px] "+ checkIndicatorBg={`${+ !selectedTagIds?.[wsTag.slug] ? "text-transparent" : "text-mineshaft-800"+ }`}+ />+ )}+ <div className="ml-7 flex items-center gap-3">+ <div+ className="w-[10px] h-[10px] rounded-full"+ style={{ background: wsTag?.tagColor ? wsTag.tagColor : "#bec2c8" }}+ >+ {" "}+ </div>+ <span>{wsTag.slug}</span></div>- </PopoverContent>- )-}+ </div>+ ))}+ <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Tags}>+ {(isAllowed) => (+ <Button+ onClick={() => handleOnCreateTagOpen()}+ isDisabled={!isAllowed}+ size="xs"+ className="mt-2"+ leftIcon={<FontAwesomeIcon icon={faPlus} className="ml-1 mr-2" />}+ >+ Add new tag+ </Button>+ )}+ </ProjectPermissionCan>+ </div>+ </PopoverContent>+ );+};-export default AddTagPopoverContent\ No newline at end of file+export default AddTagPopoverContent;diff --git a/frontend/src/components/permissions/PermissionDeniedBanner.tsx b/frontend/src/components/permissions/PermissionDeniedBanner.tsxnew file mode 100644index 0000000000..5e70d9e724--- /dev/null+++ b/frontend/src/components/permissions/PermissionDeniedBanner.tsx@@ -0,0 +1,40 @@+import { ReactNode } from "react";+import { faLock } from "@fortawesome/free-solid-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { twMerge } from "tailwind-merge";++type Props = {+ containerClassName?: string;+ className?: string;+ children?: ReactNode;+};++export const PermissionDeniedBanner = ({ containerClassName, className, children }: Props) => {+ return (+ <div+ className={twMerge(+ "container h-full mx-auto flex justify-center items-center",+ containerClassName+ )}+ >+ <div+ className={twMerge(+ "rounded-md bg-mineshaft-800 text-bunker-300 p-16 flex space-x-12 items-end",+ className+ )}+ >+ <div>+ <FontAwesomeIcon icon={faLock} size="6x" />+ </div>+ <div>+ <div className="text-4xl font-medium mb-2">Permission Denied</div>+ {children || (+ <div className="text-sm">+ You do not have permission. <br /> Kindly contact your organization administrator+ </div>+ )}+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/permissions/ProjectPermissionCan.tsx b/frontend/src/components/permissions/ProjectPermissionCan.tsxindex 6c76afde9c..7857ac0522 100644--- a/frontend/src/components/permissions/ProjectPermissionCan.tsx+++ b/frontend/src/components/permissions/ProjectPermissionCan.tsx@@ -11,7 +11,11 @@ type Props = {// so when permission is allowed same tooltip will be reused to show helpertextrenderTooltip?: boolean;allowedLabel?: string;-} & BoundCanProps<TProjectPermission>;+ // BUG(akhilmhdh): As a workaround for now i put any but this should be TProjectPermission+ // For some reason when i put TProjectPermission in a wrapper component it just wont work causes a weird ts error+ // tried a lot combinations+ // REF: https://github.com/stalniy/casl/blob/ac081a34f56366a7eaaed05d21689d27041ef005/packages/casl-react/src/factory.ts#L15+} & BoundCanProps<any>;export const ProjectPermissionCan: FunctionComponent<Props> = ({label = "Permission Denied. Kindly contact your project admin",@@ -22,7 +26,6 @@ export const ProjectPermissionCan: FunctionComponent<Props> = ({...props}) => {const permission = useProjectPermission();-return (<Can {...props} passThrough={passThrough} ability={props?.ability || permission}>{(isAllowed, ability) => {diff --git a/frontend/src/components/permissions/index.tsx b/frontend/src/components/permissions/index.tsxindex 24854f0472..8d523c3111 100644--- a/frontend/src/components/permissions/index.tsx+++ b/frontend/src/components/permissions/index.tsx@@ -1,2 +1,3 @@export { OrgPermissionCan } from "./OrgPermissionCan";+export { PermissionDeniedBanner } from "./PermissionDeniedBanner";export { ProjectPermissionCan } from "./ProjectPermissionCan";diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex d81ed068e2..ca1ca13aea 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -27,7 +27,7 @@ export enum ProjectPermissionSub {type SubjectFields = {environment: string;- secretPath?: string;+ secretPath: string;};export type ProjectPermissionSet =diff --git a/frontend/src/hooks/api/roles/queries.tsx b/frontend/src/hooks/api/roles/queries.tsxindex 917b6d5f6a..5415d201c9 100644--- a/frontend/src/hooks/api/roles/queries.tsx+++ b/frontend/src/hooks/api/roles/queries.tsx@@ -1,6 +1,8 @@-import { createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";+import { buildMongoQueryMatcher, createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";import { PackRule, unpackRules } from "@casl/ability/extra";import { useQuery } from "@tanstack/react-query";+import { FieldCondition, FieldInstruction, JsInterpreter } from "@ucast/mongo2js";+import picomatch from "picomatch";import { apiRequest } from "@app/config/request";import { OrgPermissionSet } from "@app/context/OrgPermissionContext/types";@@ -13,6 +15,29 @@ import {TRole} from "./types";+const $glob: FieldInstruction<string> = {+ type: "field",+ validate(instruction, value) {+ if (typeof value !== "string") {+ throw new Error(`"${instruction.name}" expects value to be a string`);+ }+ }+};++const glob: JsInterpreter<FieldCondition<string>> = (node, object, context) => {+ const secretPath = context.get(object, node.field);+ const permissionSecretGlobPath = node.value;+ if (!secretPath) return false;+ // console.log(+ // secretPath,+ // picomatch.isMatch(secretPath, permissionSecretGlobPath, { strictSlashes: false }),+ // permissionSecretGlobPath+ // );+ return picomatch.isMatch(secretPath, permissionSecretGlobPath, { strictSlashes: false });+};++const conditionsMatcher = buildMongoQueryMatcher({ $glob }, { glob });+export const roleQueryKeys = {getRoles: ({ orgId, workspaceId }: TGetRolesDTO) => ["roles", { orgId, workspaceId }] as const,getUserOrgPermissions: ({ orgId }: TGetUserOrgPermissionsDTO) =>@@ -57,7 +82,7 @@ export const useGetUserOrgPermissions = ({ orgId }: TGetUserOrgPermissionsDTO) =enabled: Boolean(orgId),select: (data) => {const rule = unpackRules<RawRuleOf<MongoAbility<OrgPermissionSet>>>(data);- const ability = createMongoAbility<OrgPermissionSet>(rule);+ const ability = createMongoAbility<OrgPermissionSet>(rule, { conditionsMatcher });return ability;}});diff --git a/frontend/src/layouts/AppLayout/AppLayout.tsx b/frontend/src/layouts/AppLayout/AppLayout.tsxindex bd4152b7c4..d03161f300 100644--- a/frontend/src/layouts/AppLayout/AppLayout.tsx+++ b/frontend/src/layouts/AppLayout/AppLayout.tsx@@ -739,16 +739,26 @@ export const AppLayout = ({ children }: LayoutProps) => {<Controllercontrol={control}name="addMembers"- defaultValue+ defaultValue={false}render={({ field: { onBlur, value, onChange } }) => (- <Checkbox- id="add-project-layout"- isChecked={value}- onCheckedChange={onChange}- onBlur={onBlur}+ <OrgPermissionCan+ I={OrgPermissionActions.Read}+ a={OrgPermissionSubjects.Member}>- Add all members of my organization to this project- </Checkbox>+ {(isAllowed) => (+ <div>+ <Checkbox+ id="add-project-layout"+ isChecked={value}+ onCheckedChange={onChange}+ isDisabled={!isAllowed}+ onBlur={onBlur}+ >+ Add all members of my organization to this project+ </Checkbox>+ </div>+ )}+ </OrgPermissionCan>)}/></div>diff --git a/frontend/src/pages/org/[id]/overview/index.tsx b/frontend/src/pages/org/[id]/overview/index.tsxindex ea72be394d..fdd5c2cdf3 100644--- a/frontend/src/pages/org/[id]/overview/index.tsx+++ b/frontend/src/pages/org/[id]/overview/index.tsx@@ -838,16 +838,26 @@ const OrganizationPage = withPermission(<Controllercontrol={control}name="addMembers"- defaultValue+ defaultValue={false}render={({ field: { onBlur, value, onChange } }) => (- <Checkbox- id="add-project-layout"- isChecked={value}- onCheckedChange={onChange}- onBlur={onBlur}+ <OrgPermissionCan+ I={OrgPermissionActions.Read}+ a={OrgPermissionSubjects.Member}>- Add all members of my organization to this project- </Checkbox>+ {(isAllowed) => (+ <div>+ <Checkbox+ id="add-project-layout"+ isChecked={value}+ onCheckedChange={onChange}+ isDisabled={!isAllowed}+ onBlur={onBlur}+ >+ Add all members of my organization to this project+ </Checkbox>+ </div>+ )}+ </OrgPermissionCan>)}/></div>diff --git a/frontend/src/views/DashboardPage/DashboardPage.tsx b/frontend/src/views/DashboardPage/DashboardPage.tsxindex 5c93b61928..6e8509aba4 100644--- a/frontend/src/views/DashboardPage/DashboardPage.tsx+++ b/frontend/src/views/DashboardPage/DashboardPage.tsx@@ -3,6 +3,7 @@ import { FormProvider, useFieldArray, useForm } from "react-hook-form";import { useTranslation } from "react-i18next";import { useRouter } from "next/router";import { subject } from "@casl/ability";+import { Can } from "@casl/react";import {closestCenter,DndContext,@@ -26,7 +27,6 @@ import {faEyeSlash,faFileImport,faFolderPlus,- faLock,faMagnifyingGlass,faPlus} from "@fortawesome/free-solid-svg-icons";@@ -41,7 +41,7 @@ import { useQueryClient } from "@tanstack/react-query";import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";import NavHeader from "@app/components/navigation/NavHeader";-import { ProjectPermissionCan } from "@app/components/permissions";+import { PermissionDeniedBanner, ProjectPermissionCan } from "@app/components/permissions";import {Button,DeleteActionModal,@@ -66,7 +66,6 @@ import {useSubscription,useWorkspace} from "@app/context";-import { withProjectPermission } from "@app/hoc";import { useLeaveConfirm, usePopUp, useToggle } from "@app/hooks";import {useBatchSecretsOp,@@ -92,7 +91,6 @@ import {useUpdateSecretImport} from "@app/hooks/api";import { secretKeys } from "@app/hooks/api/secrets/queries";-import { WorkspaceEnv } from "@app/hooks/api/types";import { CompareSecret } from "./components/CompareSecret";import { CreateTagModal } from "./components/CreateTagModal";@@ -133,944 +131,936 @@ type TDeleteSecretImport = { environment: string; secretPath: string };* Instead when user delete we raise a flag so if user decides to go back to toggle personal before saving* They will get it back*/-export const DashboardPage = withProjectPermission(- () => {- const { subscription } = useSubscription();- const { t } = useTranslation();- const router = useRouter();- const { createNotification } = useNotificationContext();- const queryClient = useQueryClient();- const envQuery = router.query.env as string;- const permission = useProjectPermission();+export const DashboardPage = () => {+ const { subscription } = useSubscription();+ const { t } = useTranslation();+ const router = useRouter();+ const { createNotification } = useNotificationContext();+ const queryClient = useQueryClient();+ const environment = router.query.env as string;+ const permission = useProjectPermission();- const secretContainer = useRef<HTMLDivElement | null>(null);- const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([- "secretDetails",- "addTag",- "secretSnapshots",- "uploadedSecOpts",- "compareSecrets",- "folderForm",- "deleteFolder",- "upgradePlan",- "addSecretImport",- "deleteSecretImport"- ] as const);- const [isSecretValueHidden, setIsSecretValueHidden] = useToggle(true);- const [searchFilter, setSearchFilter] = useState("");- const [snapshotId, setSnaphotId] = useState<string | null>(null);- const [selectedEnv, setSelectedEnv] = useState<WorkspaceEnv | null>(null);- const [sortDir, setSortDir] = useState<"asc" | "desc">("asc");- const deletedSecretIds = useRef<{ id: string; secretName: string }[]>([]);- const { hasUnsavedChanges, setHasUnsavedChanges } = useLeaveConfirm({ initialValue: false });+ const secretContainer = useRef<HTMLDivElement | null>(null);+ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([+ "secretDetails",+ "addTag",+ "secretSnapshots",+ "uploadedSecOpts",+ "compareSecrets",+ "folderForm",+ "deleteFolder",+ "upgradePlan",+ "addSecretImport",+ "deleteSecretImport"+ ] as const);+ const [isSecretValueHidden, setIsSecretValueHidden] = useToggle(true);+ const [searchFilter, setSearchFilter] = useState("");+ const [snapshotId, setSnaphotId] = useState<string | null>(null);+ const [sortDir, setSortDir] = useState<"asc" | "desc">("asc");+ const deletedSecretIds = useRef<{ id: string; secretName: string }[]>([]);+ const { hasUnsavedChanges, setHasUnsavedChanges } = useLeaveConfirm({ initialValue: false });- const folderId = router.query.folderId as string;- const isRollbackMode = Boolean(snapshotId);+ const folderId = router.query.folderId as string;+ const isRollbackMode = Boolean(snapshotId);- const { currentWorkspace, isLoading } = useWorkspace();- const { currentOrg } = useOrganization();- const workspaceId = currentWorkspace?._id as string;- const selectedEnvSlug = selectedEnv?.slug || "";+ const { currentWorkspace, isLoading } = useWorkspace();+ const { currentOrg } = useOrganization();+ const workspaceId = currentWorkspace?._id as string;- const { data: latestFileKey } = useGetUserWsKey(workspaceId);+ const { data: latestFileKey } = useGetUserWsKey(workspaceId);- useEffect(() => {- if (!isLoading && !workspaceId && router.isReady) {- router.push(`/org/${currentOrg?._id}/overview`);- }- }, [isLoading, workspaceId, router.isReady]);+ useEffect(() => {+ if (!isLoading && !workspaceId && router.isReady) {+ router.push(`/org/${currentOrg?._id}/overview`);+ }+ }, [isLoading, workspaceId, router.isReady]);- // fetching data- const { data: userAction } = useGetUserAction(USER_ACTION_PUSH);- const hasUserPushed = Boolean(userAction);+ // fetching data+ const { data: userAction } = useGetUserAction(USER_ACTION_PUSH);+ const hasUserPushed = Boolean(userAction);- const { data: secretVersion } = useGetSecretVersion({- limit: 10,- offset: 0,- secretId: (popUp?.secretDetails?.data as TSecretDetailsOpen)?.id,- decryptFileKey: latestFileKey!- });+ const { data: secretVersion } = useGetSecretVersion({+ limit: 10,+ offset: 0,+ secretId: (popUp?.secretDetails?.data as TSecretDetailsOpen)?.id,+ decryptFileKey: latestFileKey!+ });- const { data: secrets, isLoading: isSecretsLoading } = useGetProjectSecrets({- workspaceId,- env: selectedEnvSlug,- decryptFileKey: latestFileKey!,- isPaused: Boolean(snapshotId),- folderId- });+ const { data: secrets, isLoading: isSecretsLoading } = useGetProjectSecrets({+ workspaceId,+ env: environment,+ decryptFileKey: latestFileKey!,+ isPaused: Boolean(snapshotId),+ folderId+ });- const { data: folderData, isLoading: isFoldersLoading } = useGetProjectFolders({- workspaceId: workspaceId || "",- environment: selectedEnvSlug,- parentFolderId: folderId,- isPaused: isRollbackMode,- sortDir- });+ const { data: folderData, isLoading: isFoldersLoading } = useGetProjectFolders({+ workspaceId: workspaceId || "",+ environment,+ parentFolderId: folderId,+ isPaused: isRollbackMode,+ sortDir+ });- const {- data: secretSnaphots,- fetchNextPage,- hasNextPage,- isFetchingNextPage- } = useGetWorkspaceSecretSnapshots({- workspaceId,- environment: selectedEnvSlug,- folder: folderId,- limit: 10- });+ const {+ data: secretSnaphots,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage+ } = useGetWorkspaceSecretSnapshots({+ workspaceId,+ environment,+ folder: folderId,+ limit: 10+ });- const {- data: snapshotSecret,- isLoading: isSnapshotSecretsLoading,- isFetching: isSnapshotChanging- } = useGetSnapshotSecrets({- snapshotId: snapshotId || "",- env: selectedEnvSlug,- decryptFileKey: latestFileKey!- });+ const {+ data: snapshotSecret,+ isLoading: isSnapshotSecretsLoading,+ isFetching: isSnapshotChanging+ } = useGetSnapshotSecrets({+ snapshotId: snapshotId || "",+ env: environment,+ decryptFileKey: latestFileKey!+ });- const { data: snapshotCount, isLoading: isLoadingSnapshotCount } = useGetWsSnapshotCount(- workspaceId,- selectedEnvSlug,- folderId- );+ const { data: snapshotCount, isLoading: isLoadingSnapshotCount } = useGetWsSnapshotCount(+ workspaceId,+ environment,+ folderId+ );- const { data: wsTags } = useGetWsTags(workspaceId);+ const { data: wsTags } = useGetWsTags(workspaceId);- // mutation calls- const { mutateAsync: batchSecretOp } = useBatchSecretsOp();- const { mutateAsync: performSecretRollback } = usePerformSecretRollback();- const { mutateAsync: registerUserAction } = useRegisterUserAction();- const { mutateAsync: createWsTag } = useCreateWsTag();- const { mutateAsync: createFolder } = useCreateFolder();- const { mutateAsync: updateFolder } = useUpdateFolder(folderId);- const { mutateAsync: deleteFolder } = useDeleteFolder(folderId);+ // mutation calls+ const { mutateAsync: batchSecretOp } = useBatchSecretsOp();+ const { mutateAsync: performSecretRollback } = usePerformSecretRollback();+ const { mutateAsync: registerUserAction } = useRegisterUserAction();+ const { mutateAsync: createWsTag } = useCreateWsTag();+ const { mutateAsync: createFolder } = useCreateFolder();+ const { mutateAsync: updateFolder } = useUpdateFolder(folderId);+ const { mutateAsync: deleteFolder } = useDeleteFolder(folderId);- const { data: secretImportCfg, isFetching: isSecretImportCfgFetching } = useGetSecretImports(- workspaceId,- selectedEnvSlug,- folderId- );+ const { data: secretImportCfg, isFetching: isSecretImportCfgFetching } = useGetSecretImports(+ workspaceId,+ environment,+ folderId+ );- const { data: importedSecrets } = useGetImportedSecrets({- workspaceId,- decryptFileKey: latestFileKey!,- environment: selectedEnvSlug,- folderId- });+ const { data: importedSecrets } = useGetImportedSecrets({+ workspaceId,+ decryptFileKey: latestFileKey!,+ environment,+ folderId+ });- const secretPath = `/${(folderData?.dir || [])- ?.filter(({ name }) => name !== "root")- .join("/")}`;+ const secretPath = `/${(folderData?.dir || [])+ ?.filter(({ name }) => name !== "root")+ ?.map(({ name }) => name)+ .join("/")}`;- const userAvailableEnvs = currentWorkspace?.environments?.filter(({ slug }) =>+ const userAvailableEnvs = currentWorkspace?.environments?.filter(+ ({ slug }) =>permission.can(ProjectPermissionActions.Read,subject(ProjectPermissionSub.Secrets, { environment: slug, secretPath })+ ) ||+ permission.can(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.Folders, { environment: slug, secretPath })+ ) ||+ permission.can(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.SecretImports, { environment: slug, secretPath }))- );-- useEffect(() => {- if (!isLoading && currentWorkspace) {- const env = userAvailableEnvs?.find(({ slug }) => slug === envQuery);- if (env) setSelectedEnv(env);- }- }, [isLoading, workspaceId, userAvailableEnvs]);+ );- // This is for dnd-kit. As react-query state mutation async- // This will act as a placeholder to avoid a glitching animation on dropping items- const [items, setItems] = useState<- Array<{ environment: string; secretPath: string; id: string }>- >([]);+ // This is for dnd-kit. As react-query state mutation async+ // This will act as a placeholder to avoid a glitching animation on dropping items+ const [items, setItems] = useState<+ Array<{ environment: string; secretPath: string; id: string }>+ >([]);- useEffect(() => {- if (- !isSecretImportCfgFetching ||- // case in which u go to a folder and come back to fill in with cache data- (items.length === 0 && secretImportCfg?.imports?.length !== 0 && isSecretImportCfgFetching)- ) {- setItems(- secretImportCfg?.imports?.map((el) => ({- ...el,- id: `${el.environment}-${el.secretPath}`- })) || []- );- }- }, [isSecretImportCfgFetching]);+ useEffect(() => {+ if (+ !isSecretImportCfgFetching ||+ // case in which u go to a folder and come back to fill in with cache data+ (items.length === 0 && secretImportCfg?.imports?.length !== 0 && isSecretImportCfgFetching)+ ) {+ setItems(+ secretImportCfg?.imports?.map((el) => ({+ ...el,+ id: `${el.environment}-${el.secretPath}`+ })) || []+ );+ }+ }, [isSecretImportCfgFetching]);- const { mutateAsync: createSecretImport } = useCreateSecretImport();- const { mutate: updateSecretImportSync } = useUpdateSecretImport();- const { mutateAsync: deleteSecretImport } = useDeleteSecretImport();+ const { mutateAsync: createSecretImport } = useCreateSecretImport();+ const { mutate: updateSecretImportSync } = useUpdateSecretImport();+ const { mutateAsync: deleteSecretImport } = useDeleteSecretImport();- const sensors = useSensors(- useSensor(MouseSensor, {}),- useSensor(TouchSensor, {}),- useSensor(KeyboardSensor, {})- );+ const sensors = useSensors(+ useSensor(MouseSensor, {}),+ useSensor(TouchSensor, {}),+ useSensor(KeyboardSensor, {})+ );- const method = useForm<FormData>({- // why any: well yup inferred ts expects other keys to defined as undefined- defaultValues: secrets as any,- values: secrets as any,- mode: "onBlur",- resolver: yupResolver(schema)- });+ const method = useForm<FormData>({+ // why any: well yup inferred ts expects other keys to defined as undefined+ defaultValues: secrets as any,+ values: secrets as any,+ mode: "onBlur",+ resolver: yupResolver(schema)+ });- const {- register,- control,- handleSubmit,- getValues,- setValue,- formState: { isSubmitting, isDirty, errors },- reset- } = method;- const { fields, prepend, append, remove } = useFieldArray({ control, name: "secrets" });+ const {+ register,+ control,+ handleSubmit,+ getValues,+ setValue,+ formState: { isSubmitting, isDirty, errors },+ reset+ } = method;+ const { fields, prepend, append, remove } = useFieldArray({ control, name: "secrets" });- const isReadOnly =- permission.can(+ const isReadOnly = isFoldersLoading+ ? true+ : permission.can(ProjectPermissionActions.Read,- subject(ProjectPermissionSub.Secrets, { environment: selectedEnvSlug })+ subject(ProjectPermissionSub.Secrets, { environment, secretPath })) &&permission.cannot(ProjectPermissionActions.Edit,- subject(ProjectPermissionSub.Secrets, { environment: selectedEnvSlug })+ subject(ProjectPermissionSub.Secrets, { environment, secretPath }));- const canDoRollback = !isReadOnly;- const isSubmitDisabled = isReadOnly || (!isRollbackMode && !isDirty) || isSubmitting;-- useEffect(() => {- if (!isSnapshotChanging && Boolean(snapshotId)) {- reset({ secrets: snapshotSecret?.secrets, isSnapshotMode: true });- }- }, [isSnapshotChanging]);+ const canDoRollback = !isReadOnly;+ const isSubmitDisabled = isReadOnly || (!isRollbackMode && !isDirty) || isSubmitting;- useEffect(() => {- setHasUnsavedChanges(!isSubmitDisabled);- }, [isSubmitDisabled]);+ useEffect(() => {+ if (!isSnapshotChanging && Boolean(snapshotId)) {+ reset({ secrets: snapshotSecret?.secrets, isSnapshotMode: true });+ }+ }, [isSnapshotChanging]);- const onSortSecrets = () => {- const dir = sortDir === "asc" ? "desc" : "asc";- const sec = getValues("secrets") || [];- const sortedSec = sec.sort((a, b) =>- dir === "asc" ? a?.key?.localeCompare(b?.key || "") : b?.key?.localeCompare(a?.key || "")- );- setValue("secrets", sortedSec);- setSortDir(dir);- };+ useEffect(() => {+ setHasUnsavedChanges(!isSubmitDisabled);+ }, [isSubmitDisabled]);- const handleUploadedEnv = (uploadedSec: TSecOverwriteOpt["secrets"]) => {- const sec = getValues("secrets") || [];- const conflictingSec = sec.filter(({ key }) => Boolean(uploadedSec?.[key]));- const conflictingSecIds = conflictingSec.reduce<Record<string, boolean>>(- (prev, curr) => ({- ...prev,- [curr.key]: true- }),- {}- );- // filter to get all conflicting ones- const conflictingUploadedSec = { ...uploadedSec };- // append non conflicting ones- Object.keys(uploadedSec).forEach((key) => {- if (!conflictingSecIds?.[key]) {- delete conflictingUploadedSec[key];- sec.push({- ...DEFAULT_SECRET_VALUE,- key,- value: uploadedSec[key].value,- comment: uploadedSec[key].comments.join(",")- });- }- });- setValue("secrets", sec, { shouldDirty: true });- if (conflictingSec.length > 0) {- handlePopUpOpen("uploadedSecOpts", { secrets: conflictingUploadedSec });- }- };+ const onSortSecrets = () => {+ const dir = sortDir === "asc" ? "desc" : "asc";+ const sec = getValues("secrets") || [];+ const sortedSec = sec.sort((a, b) =>+ dir === "asc" ? a?.key?.localeCompare(b?.key || "") : b?.key?.localeCompare(a?.key || "")+ );+ setValue("secrets", sortedSec);+ setSortDir(dir);+ };- const onOverwriteSecrets = () => {- const sec = getValues("secrets") || [];- const uploadedSec = (popUp?.uploadedSecOpts?.data as TSecOverwriteOpt)?.secrets;- const data: Array<{ key: string; index: number }> = [];- sec.forEach(({ key }, index) => {- if (uploadedSec?.[key]) data.push({ key, index });- });- data.forEach(({ key, index }) => {- const { value, comments } = uploadedSec[key];- const comment = comments.join(", ");- sec[index] = {+ const handleUploadedEnv = (uploadedSec: TSecOverwriteOpt["secrets"]) => {+ const sec = getValues("secrets") || [];+ const conflictingSec = sec.filter(({ key }) => Boolean(uploadedSec?.[key]));+ const conflictingSecIds = conflictingSec.reduce<Record<string, boolean>>(+ (prev, curr) => ({+ ...prev,+ [curr.key]: true+ }),+ {}+ );+ // filter to get all conflicting ones+ const conflictingUploadedSec = { ...uploadedSec };+ // append non conflicting ones+ Object.keys(uploadedSec).forEach((key) => {+ if (!conflictingSecIds?.[key]) {+ delete conflictingUploadedSec[key];+ sec.push({...DEFAULT_SECRET_VALUE,key,- value,- comment,- tags: sec[index].tags- };- });- setValue("secrets", sec, { shouldDirty: true });- handlePopUpClose("uploadedSecOpts");- };-- const onSecretRollback = async () => {- if (!snapshotSecret?.version) {- createNotification({- text: "Failed to find secret version",- type: "success"- });- return;- }- try {- await performSecretRollback({- workspaceId,- version: snapshotSecret.version,- environment: selectedEnvSlug,- folderId- });- setValue("isSnapshotMode", false);- setSnaphotId(null);- queryClient.invalidateQueries(secretKeys.getProjectSecret(workspaceId, selectedEnvSlug));- createNotification({- text: "Successfully rollback secrets",- type: "success"- });- } catch (error) {- console.log(error);- createNotification({- text: "Failed to rollback secrets",- type: "error"+ value: uploadedSec[key].value,+ comment: uploadedSec[key].comments.join(",")});}- };+ });+ setValue("secrets", sec, { shouldDirty: true });+ if (conflictingSec.length > 0) {+ handlePopUpOpen("uploadedSecOpts", { secrets: conflictingUploadedSec });+ }+ };- const onAppendSecret = () => {- setSearchFilter("");- append(DEFAULT_SECRET_VALUE);- };+ const onOverwriteSecrets = () => {+ const sec = getValues("secrets") || [];+ const uploadedSec = (popUp?.uploadedSecOpts?.data as TSecOverwriteOpt)?.secrets;+ const data: Array<{ key: string; index: number }> = [];+ sec.forEach(({ key }, index) => {+ if (uploadedSec?.[key]) data.push({ key, index });+ });+ data.forEach(({ key, index }) => {+ const { value, comments } = uploadedSec[key];+ const comment = comments.join(", ");+ sec[index] = {+ ...DEFAULT_SECRET_VALUE,+ key,+ value,+ comment,+ tags: sec[index].tags+ };+ });+ setValue("secrets", sec, { shouldDirty: true });+ handlePopUpClose("uploadedSecOpts");+ };- const onSaveSecret = async ({ secrets: userSec = [], isSnapshotMode }: FormData) => {- if (isSnapshotMode) {- await onSecretRollback();- return;- }- // just closing this if save is triggered from drawer- handlePopUpClose("secretDetails");- // encrypt and format the secrets to batch api format- // requests = [ {method:"", secret:""} ]- const batchedSecret = transformSecretsToBatchSecretReq(- deletedSecretIds.current,- latestFileKey,- userSec,- secrets?.secrets- );- // type check- if (!selectedEnv?.slug) return;- if (batchedSecret.length === 0) {- reset();- return;- }- try {- await batchSecretOp({- requests: batchedSecret,- workspaceId,- folderId,- environment: selectedEnv?.slug- });- createNotification({- text: "Successfully saved changes",- type: "success"- });- deletedSecretIds.current = [];- if (!hasUserPushed) {- await registerUserAction(USER_ACTION_PUSH);- }- } catch (error) {- console.log(error);- createNotification({- text: "Failed to save changes",- type: "error"- });- }- };+ const onSecretRollback = async () => {+ if (!snapshotSecret?.version) {+ createNotification({+ text: "Failed to find secret version",+ type: "success"+ });+ return;+ }+ try {+ await performSecretRollback({+ workspaceId,+ version: snapshotSecret.version,+ environment,+ folderId+ });+ setValue("isSnapshotMode", false);+ setSnaphotId(null);+ queryClient.invalidateQueries(secretKeys.getProjectSecret(workspaceId, environment));+ createNotification({+ text: "Successfully rollback secrets",+ type: "success"+ });+ } catch (error) {+ console.log(error);+ createNotification({+ text: "Failed to rollback secrets",+ type: "error"+ });+ }+ };- const onDrawerOpen = useCallback((id: string | undefined, index: number) => {- handlePopUpOpen("secretDetails", { id, index } as TSecretDetailsOpen);- }, []);+ const onAppendSecret = () => {+ setSearchFilter("");+ append(DEFAULT_SECRET_VALUE);+ };- const onEnvChange = (slug: string) => {- if (hasUnsavedChanges) {- // eslint-disable-next-line no-alert- if (!window.confirm(leaveConfirmDefaultMessage)) return;+ const onSaveSecret = async ({ secrets: userSec = [], isSnapshotMode }: FormData) => {+ if (isSnapshotMode) {+ await onSecretRollback();+ return;+ }+ // just closing this if save is triggered from drawer+ handlePopUpClose("secretDetails");+ // encrypt and format the secrets to batch api format+ // requests = [ {method:"", secret:""} ]+ const batchedSecret = transformSecretsToBatchSecretReq(+ deletedSecretIds.current,+ latestFileKey,+ userSec,+ secrets?.secrets+ );+ // type check+ if (batchedSecret.length === 0) {+ reset();+ return;+ }+ try {+ await batchSecretOp({+ requests: batchedSecret,+ workspaceId,+ folderId,+ environment+ });+ createNotification({+ text: "Successfully saved changes",+ type: "success"+ });+ deletedSecretIds.current = [];+ if (!hasUserPushed) {+ await registerUserAction(USER_ACTION_PUSH);}-- const env = userAvailableEnvs?.find((el) => el.slug === slug);- if (env) setSelectedEnv(env);- const query: Record<string, string> = { ...router.query, env: slug };- delete query.folderId;- router.push({- pathname: router.pathname,- query+ } catch (error) {+ console.log(error);+ createNotification({+ text: "Failed to save changes",+ type: "error"});- };+ }+ };- const handleDownloadSecret = () => {- const secretsFromImport: { key: string; value: string; comment: string }[] = [];- importedSecrets?.forEach(({ secrets: impSec }) => {- impSec.forEach((el) => {- secretsFromImport.push({ key: el.key, value: el.value, comment: el.comment });- });- });- downloadSecret(getValues("secrets"), secretsFromImport, selectedEnv?.slug);- };+ const onDrawerOpen = useCallback((id: string | undefined, index: number) => {+ handlePopUpOpen("secretDetails", { id, index } as TSecretDetailsOpen);+ }, []);- // record all deleted ids- // This will make final deletion easier- const onSecretDelete = useCallback(- (index: number, secretName: string, id?: string, overrideId?: string) => {- if (id)- deletedSecretIds.current.push({- id,- secretName- });- if (overrideId)- deletedSecretIds.current.push({- id: overrideId,- secretName- });- remove(index);- // just the case if this is called from drawer- handlePopUpClose("secretDetails");- },- []- );+ const onEnvChange = (slug: string) => {+ if (hasUnsavedChanges) {+ // eslint-disable-next-line no-alert+ if (!window.confirm(leaveConfirmDefaultMessage)) return;+ }- const onCreateWsTag = useCallback(- async (tagName: string, tagColor: string) => {- try {- await createWsTag({- workspaceID: workspaceId,- tagName,- tagColor,- tagSlug: tagName.replace(" ", "_")- });- handlePopUpClose("addTag");- createNotification({- text: "Successfully created a tag",- type: "success"- });- } catch (error) {- console.error(error);- createNotification({- text: "Failed to create a tag",- type: "error"- });- }- },- [workspaceId]- );+ const query: Record<string, string> = { ...router.query, env: slug };+ delete query.folderId;+ router.push({+ pathname: router.pathname,+ query+ });+ };- const handleFolderOpen = useCallback(- (id: string) => {- setSearchFilter("");- router.push({- pathname: router.pathname,- query: {- id: workspaceId,- env: envQuery,- folderId: id- }- });- },- [envQuery, workspaceId]- );+ const handleDownloadSecret = () => {+ const secretsFromImport: { key: string; value: string; comment: string }[] = [];+ importedSecrets?.forEach(({ secrets: impSec }) => {+ impSec.forEach((el) => {+ secretsFromImport.push({ key: el.key, value: el.value, comment: el.comment });+ });+ });+ downloadSecret(getValues("secrets"), secretsFromImport, environment);+ };- const isEditFolder = Boolean(popUp?.folderForm?.data);+ // record all deleted ids+ // This will make final deletion easier+ const onSecretDelete = useCallback(+ (index: number, secretName: string, id?: string, overrideId?: string) => {+ if (id)+ deletedSecretIds.current.push({+ id,+ secretName+ });+ if (overrideId)+ deletedSecretIds.current.push({+ id: overrideId,+ secretName+ });+ remove(index);+ // just the case if this is called from drawer+ handlePopUpClose("secretDetails");+ },+ []+ );- // FOLDER SECTION- const handleFolderCreate = async (name: string) => {+ const onCreateWsTag = useCallback(+ async (tagName: string, tagColor: string) => {try {- await createFolder({- workspaceId,- environment: selectedEnv?.slug || "",- folderName: name,- parentFolderId: folderId+ await createWsTag({+ workspaceID: workspaceId,+ tagName,+ tagColor,+ tagSlug: tagName.replace(" ", "_")});+ handlePopUpClose("addTag");createNotification({- type: "success",- text: "Successfully created folder"+ text: "Successfully created a tag",+ type: "success"});- handlePopUpClose("folderForm");} catch (error) {console.error(error);createNotification({- text: "Failed to create folder",+ text: "Failed to create a tag",type: "error"});}- };+ },+ [workspaceId]+ );- const handleFolderUpdate = useCallback(- async (name: string) => {- const { id } = popUp?.folderForm?.data as TDeleteFolderForm;- try {- await updateFolder({- folderId: id,- workspaceId,- environment: selectedEnv?.slug || "",- name- });- createNotification({- type: "success",- text: "Successfully updated folder"- });- handlePopUpClose("folderForm");- } catch (error) {- console.error(error);- createNotification({- text: "Failed to update folder",- type: "error"- });+ const handleFolderOpen = useCallback(+ (id: string) => {+ setSearchFilter("");+ router.push({+ pathname: router.pathname,+ query: {+ id: workspaceId,+ env: environment,+ folderId: id}- },- [selectedEnv?.slug, (popUp?.folderForm?.data as TDeleteFolderForm)?.id]- );+ });+ },+ [environment, workspaceId]+ );++ const isEditFolder = Boolean(popUp?.folderForm?.data);++ // FOLDER SECTION+ const handleFolderCreate = async (name: string) => {+ try {+ await createFolder({+ workspaceId,+ environment,+ folderName: name,+ parentFolderId: folderId+ });+ createNotification({+ type: "success",+ text: "Successfully created folder"+ });+ handlePopUpClose("folderForm");+ } catch (error) {+ console.error(error);+ createNotification({+ text: "Failed to create folder",+ type: "error"+ });+ }+ };- const handleFolderDelete = useCallback(async () => {- const { id } = popUp?.deleteFolder?.data as TDeleteFolderForm;+ const handleFolderUpdate = useCallback(+ async (name: string) => {+ const { id } = popUp?.folderForm?.data as TDeleteFolderForm;try {- deleteFolder({+ await updateFolder({+ folderId: id,workspaceId,- environment: selectedEnv?.slug || "",- folderId: id+ environment,+ name});createNotification({type: "success",- text: "Successfully removed folder"+ text: "Successfully updated folder"});- handlePopUpClose("deleteFolder");+ handlePopUpClose("folderForm");} catch (error) {console.error(error);createNotification({- text: "Failed to remove folder",+ text: "Failed to update folder",type: "error"});}- }, [selectedEnv?.slug, (popUp?.deleteFolder?.data as TDeleteFolderForm)?.id]);+ },+ [environment, (popUp?.folderForm?.data as TDeleteFolderForm)?.id]+ );- // SECRET IMPORT SECTION- const handleSecretImportCreate = async (env: string, secPath: string) => {- try {- await createSecretImport({+ const handleFolderDelete = useCallback(async () => {+ const { id } = popUp?.deleteFolder?.data as TDeleteFolderForm;+ try {+ deleteFolder({+ workspaceId,+ environment,+ folderId: id+ });+ createNotification({+ type: "success",+ text: "Successfully removed folder"+ });+ handlePopUpClose("deleteFolder");+ } catch (error) {+ console.error(error);+ createNotification({+ text: "Failed to remove folder",+ type: "error"+ });+ }+ }, [(popUp?.deleteFolder?.data as TDeleteFolderForm)?.id]);++ // SECRET IMPORT SECTION+ const handleSecretImportCreate = async (env: string, secPath: string) => {+ try {+ await createSecretImport({+ workspaceId,+ environment,+ folderId,+ secretImport: {+ environment: env,+ secretPath: secPath+ }+ });+ createNotification({+ type: "success",+ text: "Successfully create secret link"+ });+ handlePopUpClose("addSecretImport");+ } catch (err) {+ console.error(err);+ createNotification({+ text: "Failed to create secret link",+ type: "error"+ });+ }+ };++ const handleSecretImportDelete = async () => {+ const { environment: importEnv, secretPath: impSecPath } = popUp.deleteSecretImport+ ?.data as TDeleteSecretImport;+ try {+ if (secretImportCfg?._id) {+ await deleteSecretImport({workspaceId,- environment: selectedEnv?.slug || "",+ environment,folderId,- secretImport: {- environment: env,- secretPath: secPath- }+ id: secretImportCfg?._id,+ secretImportEnv: importEnv,+ secretImportPath: impSecPath});+ handlePopUpClose("deleteSecretImport");createNotification({type: "success",- text: "Successfully create secret link"- });- handlePopUpClose("addSecretImport");- } catch (err) {- console.error(err);- createNotification({- text: "Failed to create secret link",- type: "error"+ text: "Successfully removed secret link"});}- };+ } catch (err) {+ console.error(err);+ createNotification({+ text: "Failed to remove secret link",+ type: "error"+ });+ }+ };- const handleSecretImportDelete = async () => {- const { environment: importEnv, secretPath: impSecPath } = popUp.deleteSecretImport- ?.data as TDeleteSecretImport;- try {- if (secretImportCfg?._id) {- await deleteSecretImport({- workspaceId,- environment: selectedEnvSlug,- folderId,- id: secretImportCfg?._id,- secretImportEnv: importEnv,- secretImportPath: impSecPath- });- handlePopUpClose("deleteSecretImport");- createNotification({- type: "success",- text: "Successfully removed secret link"- });- }- } catch (err) {- console.error(err);- createNotification({- text: "Failed to remove secret link",- type: "error"- });- }- };+ const handleDragEnd = (evt: DragEndEvent) => {+ const { active, over } = evt;+ if (over?.id && active.id !== over.id) {+ const oldIndex = items.findIndex(({ id }) => id === active.id);+ const newIndex = items.findIndex(({ id }) => id === over.id);+ const newImportOrder = arrayMove(items, oldIndex, newIndex);+ setItems(newImportOrder);+ updateSecretImportSync({+ workspaceId,+ environment,+ folderId,+ id: secretImportCfg?._id || "",+ secretImports: newImportOrder.map((el) => ({+ environment: el.environment,+ secretPath: el.secretPath+ }))+ });+ }+ };- const handleDragEnd = (evt: DragEndEvent) => {- const { active, over } = evt;- if (over?.id && active.id !== over.id) {- const oldIndex = items.findIndex(({ id }) => id === active.id);- const newIndex = items.findIndex(({ id }) => id === over.id);- const newImportOrder = arrayMove(items, oldIndex, newIndex);- setItems(newImportOrder);- updateSecretImportSync({- workspaceId,- environment: selectedEnvSlug,- folderId,- id: secretImportCfg?._id || "",- secretImports: newImportOrder.map((el) => ({- environment: el.environment,- secretPath: el.secretPath- }))- });- }- };+ // OPTIMIZATION HOOKS PURELY FOR PERFORMANCE AND TO AVOID RE-RENDERING+ const handleCreateTagModalOpen = useCallback(() => handlePopUpOpen("addTag"), []);+ const handleFolderCreatePopUpOpen = useCallback(+ (id: string, name: string) => handlePopUpOpen("folderForm", { id, name }),+ []+ );+ const handleFolderDeletePopUpOpen = useCallback(+ (id: string, name: string) => handlePopUpOpen("deleteFolder", { id, name }),+ []+ );+ const handleSecretImportDelPopUpOpen = useCallback(+ (impSecEnv: string, impSecPath: string) =>+ handlePopUpOpen("deleteSecretImport", {+ environment: impSecEnv,+ secretPath: impSecPath+ }),+ []+ );- // OPTIMIZATION HOOKS PURELY FOR PERFORMANCE AND TO AVOID RE-RENDERING- const handleCreateTagModalOpen = useCallback(() => handlePopUpOpen("addTag"), []);- const handleFolderCreatePopUpOpen = useCallback(- (id: string, name: string) => handlePopUpOpen("folderForm", { id, name }),- []- );- const handleFolderDeletePopUpOpen = useCallback(- (id: string, name: string) => handlePopUpOpen("deleteFolder", { id, name }),- []- );- const handleSecretImportDelPopUpOpen = useCallback(- (impSecEnv: string, impSecPath: string) =>- handlePopUpOpen("deleteSecretImport", {- environment: impSecEnv,- secretPath: impSecPath- }),- []- );+ // when secrets is not loading and secrets list is empty+ const isDashboardSecretEmpty = !isSecretsLoading && !fields?.length;- // when secrets is not loading and secrets list is empty- const isDashboardSecretEmpty = !isSecretsLoading && !fields?.length;+ // folder list checks+ const isFolderListLoading = isRollbackMode ? isSnapshotSecretsLoading : isFoldersLoading;+ const folderList = isRollbackMode ? snapshotSecret?.folders : folderData?.folders;- // folder list checks- const isFolderListLoading = isRollbackMode ? isSnapshotSecretsLoading : isFoldersLoading;- const folderList = isRollbackMode ? snapshotSecret?.folders : folderData?.folders;+ // when using snapshot mode and snapshot is loading and snapshot list is empty+ const isFoldersEmpty = !isFolderListLoading && !folderList?.length;+ const isSnapshotSecretEmtpy =+ isRollbackMode && !isSnapshotSecretsLoading && !snapshotSecret?.secrets?.length;+ const isSecretEmpty = (!isRollbackMode && isDashboardSecretEmpty) || isSnapshotSecretEmtpy;+ const isSecretImportEmpty = !secretImportCfg?.imports?.length;+ const isEmptyPage = isFoldersEmpty && isSecretEmpty && isSecretImportEmpty;- // when using snapshot mode and snapshot is loading and snapshot list is empty- const isFoldersEmpty = !isFolderListLoading && !folderList?.length;- const isSnapshotSecretEmtpy =- isRollbackMode && !isSnapshotSecretsLoading && !snapshotSecret?.secrets?.length;- const isSecretEmpty = (!isRollbackMode && isDashboardSecretEmpty) || isSnapshotSecretEmtpy;- const isSecretImportEmpty = !secretImportCfg?.imports?.length;- const isEmptyPage = isFoldersEmpty && isSecretEmpty && isSecretImportEmpty;+ if (isSecretsLoading) {+ return (+ <div className="container mx-auto flex h-1/2 w-full items-center justify-center px-8 text-mineshaft-50 dark:[color-scheme:dark]">+ <img src="/images/loading/loading.gif" height={70} width={120} alt="loading animation" />+ </div>+ );+ }- if (isSecretsLoading) {- return (- <div className="container mx-auto flex h-1/2 w-full items-center justify-center px-8 text-mineshaft-50 dark:[color-scheme:dark]">- <img src="/images/loading/loading.gif" height={70} width={120} alt="loading animation" />+ return (+ <div className="container mx-auto h-full px-6 text-mineshaft-50 dark:[color-scheme:dark]">+ <form autoComplete="off" className="h-full flex flex-col">+ {/* breadcrumb row */}+ <div className="relative right-6 -top-2 mb-2 ml-6">+ <NavHeader+ pageName={t("dashboard.title")}+ currentEnv={+ userAvailableEnvs?.filter((envir) => envir.slug === environment)?.[0]?.name || ""+ }+ isFolderMode+ folders={folderData?.dir}+ isProjectRelated+ userAvailableEnvs={userAvailableEnvs}+ onEnvChange={onEnvChange}+ /></div>- );- }-- if (- permission.cannot(- ProjectPermissionActions.Read,- subject(ProjectPermissionSub.Secrets, { environment: envQuery, secretPath })- )- ) {- return (- <div className="container h-full mx-auto flex justify-center items-center">- <div className="rounded-md bg-mineshaft-800 text-bunker-300 p-16 flex space-x-12 items-end">- <div>- <FontAwesomeIcon icon={faLock} size="6x" />- </div>- <div>- <div className="text-4xl font-medium mb-2">Permission Denied</div>- <div className="text-sm">- You do not have permission to this page. <br /> Kindly contact your organization- administrator- </div>- </div>- </div>+ <div className="mb-4">+ <h6 className="text-2xl">{isRollbackMode ? "Secret Snapshot" : ""}</h6>+ {isRollbackMode && Boolean(snapshotSecret) && (+ <Tag colorSchema="green">+ {new Date(snapshotSecret?.createdAt || "").toLocaleString()}+ </Tag>+ )}</div>- );- }-- return (- <div className="container mx-auto h-full px-6 text-mineshaft-50 dark:[color-scheme:dark]">- <form autoComplete="off" className="h-full flex flex-col">- {/* breadcrumb row */}- <div className="relative right-6 -top-2 mb-2 ml-6">- <NavHeader- pageName={t("dashboard.title")}- currentEnv={- userAvailableEnvs?.filter((envir) => envir.slug === envQuery)?.[0]?.name || ""- }- isFolderMode- folders={folderData?.dir}- isProjectRelated- userAvailableEnvs={userAvailableEnvs}- onEnvChange={onEnvChange}+ {/* Environment, search and other action row */}+ <div className="flex items-center justify-between space-x-2">+ <div className="flex max-w-lg flex-grow space-x-2">+ <Input+ className="h-[2.3rem] bg-mineshaft-800 placeholder-mineshaft-50 duration-200 focus:bg-mineshaft-700/80"+ placeholder="Search by folder name, key name, comment..."+ value={searchFilter}+ onChange={(e) => setSearchFilter(e.target.value)}+ leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}/></div>- <div className="mb-4">- <h6 className="text-2xl">{isRollbackMode ? "Secret Snapshot" : ""}</h6>- {isRollbackMode && Boolean(snapshotSecret) && (- <Tag colorSchema="green">- {new Date(snapshotSecret?.createdAt || "").toLocaleString()}- </Tag>- )}- </div>- {/* Environment, search and other action row */}- <div className="flex items-center justify-between space-x-2">- <div className="flex max-w-lg flex-grow space-x-2">- <Input- className="h-[2.3rem] bg-mineshaft-800 placeholder-mineshaft-50 duration-200 focus:bg-mineshaft-700/80"- placeholder="Search by folder name, key name, comment..."- value={searchFilter}- onChange={(e) => setSearchFilter(e.target.value)}- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}- />- </div>- <div className="flex items-center space-x-2">- <div>- <Popover>- <PopoverTrigger asChild>- <IconButton ariaLabel="download" variant="outline_bg">- <FontAwesomeIcon icon={faDownload} />- </IconButton>- </PopoverTrigger>- <PopoverContent- className="w-auto border border-mineshaft-600 bg-mineshaft-800 p-1"- hideCloseBtn- >- <div className="flex flex-col space-y-2">- <Button- onClick={handleDownloadSecret}- colorSchema="primary"- variant="outline_bg"- className="h-8 bg-bunker-700"- >- Download as .env- </Button>- </div>- </PopoverContent>- </Popover>- </div>- <div>- <Tooltip content={isSecretValueHidden ? "Reveal Secrets" : "Hide secrets"}>- <IconButton- ariaLabel="reveal"- variant="outline_bg"- onClick={() => setIsSecretValueHidden.toggle()}- >- <FontAwesomeIcon icon={isSecretValueHidden ? faEye : faEyeSlash} />+ <div className="flex items-center space-x-2">+ <div>+ <Popover>+ <PopoverTrigger asChild>+ <IconButton ariaLabel="download" variant="outline_bg">+ <FontAwesomeIcon icon={faDownload} /></IconButton>- </Tooltip>- </div>- <ProjectPermissionCan- I={ProjectPermissionActions.Read}- a={ProjectPermissionSub.SecretRollback}- >- {(isAllowed) => (- <div className="block xl:hidden">- <Tooltip content="Point-in-time Recovery">- <IconButton- isDisabled={!isAllowed}- ariaLabel="recovery"- variant="outline_bg"- onClick={() => handlePopUpOpen("secretSnapshots")}- >- <FontAwesomeIcon icon={faCodeCommit} />- </IconButton>- </Tooltip>- </div>- )}- </ProjectPermissionCan>- <ProjectPermissionCan- I={ProjectPermissionActions.Read}- a={ProjectPermissionSub.SecretRollback}- >- {(isAllowed) => (- <div className="hidden xl:block">+ </PopoverTrigger>+ <PopoverContent+ className="w-auto border border-mineshaft-600 bg-mineshaft-800 p-1"+ hideCloseBtn+ >+ <div className="flex flex-col space-y-2"><Button+ onClick={handleDownloadSecret}+ colorSchema="primary"variant="outline_bg"- onClick={() => {- if (subscription && subscription.pitRecovery) {- handlePopUpOpen("secretSnapshots");- return;- }-- handlePopUpOpen("upgradePlan");- }}- leftIcon={<FontAwesomeIcon icon={faCodeCommit} />}- isLoading={isLoadingSnapshotCount}- isDisabled={!canDoRollback || !isAllowed}- className="h-10"+ className="h-8 bg-bunker-700">- {snapshotCount} Commits+ Download as .env</Button></div>- )}- </ProjectPermissionCan>- {!isReadOnly && !isRollbackMode && (- <div className="flex flex-row items-center justify-center">- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Secrets}+ </PopoverContent>+ </Popover>+ </div>+ <div>+ <Tooltip content={isSecretValueHidden ? "Reveal Secrets" : "Hide secrets"}>+ <IconButton+ ariaLabel="reveal"+ variant="outline_bg"+ onClick={() => setIsSecretValueHidden.toggle()}+ >+ <FontAwesomeIcon icon={isSecretValueHidden ? faEye : faEyeSlash} />+ </IconButton>+ </Tooltip>+ </div>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Read}+ a={ProjectPermissionSub.SecretRollback}+ >+ {(isAllowed) => (+ <div className="block xl:hidden">+ <Tooltip content="Point-in-time Recovery">+ <IconButton+ isDisabled={!isAllowed}+ ariaLabel="recovery"+ variant="outline_bg"+ onClick={() => handlePopUpOpen("secretSnapshots")}+ >+ <FontAwesomeIcon icon={faCodeCommit} />+ </IconButton>+ </Tooltip>+ </div>+ )}+ </ProjectPermissionCan>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Read}+ a={ProjectPermissionSub.SecretRollback}+ >+ {(isAllowed) => (+ <div className="hidden xl:block">+ <Button+ variant="outline_bg"+ onClick={() => {+ if (subscription && subscription.pitRecovery) {+ handlePopUpOpen("secretSnapshots");+ return;+ }++ handlePopUpOpen("upgradePlan");+ }}+ leftIcon={<FontAwesomeIcon icon={faCodeCommit} />}+ isLoading={isLoadingSnapshotCount}+ isDisabled={!canDoRollback || !isAllowed}+ className="h-10">- {(isAllowed) => (- <button- type="button"- disabled={!isAllowed}- onClick={() => {- if (!(isReadOnly || isRollbackMode)) {- if (secretContainer.current) {- secretContainer.current.scroll({- top: 0,- behavior: "smooth"- });- }- prepend(DEFAULT_SECRET_VALUE, { shouldFocus: false });- setSearchFilter("");+ {snapshotCount} Commits+ </Button>+ </div>+ )}+ </ProjectPermissionCan>+ {!isReadOnly && !isRollbackMode && (+ <div className="flex flex-row items-center justify-center">+ <ProjectPermissionCan+ I={ProjectPermissionActions.Create}+ a={subject(ProjectPermissionSub.Secrets, {+ secretPath,+ environment+ })}+ >+ {(isAllowed) => (+ <button+ type="button"+ disabled={!isAllowed}+ onClick={() => {+ if (!(isReadOnly || isRollbackMode)) {+ if (secretContainer.current) {+ secretContainer.current.scroll({+ top: 0,+ behavior: "smooth"+ });}- }}- className="cursor-pointer rounded-l-md border border-mineshaft-500 bg-mineshaft-600 p-2 pr-4 text-sm font-semibold text-mineshaft-300 duration-200 hover:border-primary/40 hover:bg-primary/[0.1]"- >- <FontAwesomeIcon icon={faPlus} className="px-2" />- Add Secret- </button>- )}- </ProjectPermissionCan>- <DropdownMenu>- <DropdownMenuTrigger asChild className="data-[state=open]:bg-mineshaft-600">- <div className="cursor-pointer rounded-r-md border border-mineshaft-500 bg-mineshaft-600 p-2 text-sm text-mineshaft-300 duration-200 hover:border-primary/40 hover:bg-primary/[0.1]">- <FontAwesomeIcon icon={faAngleDown} className="pr-2 pl-1.5" />+ prepend(DEFAULT_SECRET_VALUE, { shouldFocus: false });+ setSearchFilter("");+ }+ }}+ className="cursor-pointer rounded-l-md border border-mineshaft-500 bg-mineshaft-600 p-2 pr-4 text-sm font-semibold text-mineshaft-300 duration-200 hover:border-primary/40 hover:bg-primary/[0.1]"+ >+ <FontAwesomeIcon icon={faPlus} className="px-2" />+ Add Secret+ </button>+ )}+ </ProjectPermissionCan>+ <DropdownMenu>+ <DropdownMenuTrigger asChild className="data-[state=open]:bg-mineshaft-600">+ <div className="cursor-pointer rounded-r-md border border-mineshaft-500 bg-mineshaft-600 p-2 text-sm text-mineshaft-300 duration-200 hover:border-primary/40 hover:bg-primary/[0.1]">+ <FontAwesomeIcon icon={faAngleDown} className="pr-2 pl-1.5" />+ </div>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="left-20 z-[60] mt-1 w-[10.8rem]">+ <div className="rounded-md border border-mineshaft-600 bg-mineshaft-800 p-1">+ <div className="w-full pb-1">+ <Can+ ability={permission}+ I={ProjectPermissionActions.Delete}+ a={ProjectPermissionSub.SecretRollback}+ >+ {(isAllowed) => (+ <Button+ leftIcon={<FontAwesomeIcon icon={faFolderPlus} />}+ onClick={() => handlePopUpOpen("folderForm")}+ isDisabled={isReadOnly || isRollbackMode || !isAllowed}+ variant="outline_bg"+ className="h-10"+ isFullWidth+ >+ Add Folder+ </Button>+ )}+ </Can></div>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="left-20 z-[60] mt-1 w-[10.8rem]">- <div className="rounded-md border border-mineshaft-600 bg-mineshaft-800 p-1">- <div className="w-full pb-1">- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Folders}- >- {(isAllowed) => (- <Button- leftIcon={<FontAwesomeIcon icon={faFolderPlus} />}- onClick={() => handlePopUpOpen("folderForm")}- isDisabled={isReadOnly || isRollbackMode || !isAllowed}- variant="outline_bg"- className="h-10"- isFullWidth- >- Add Folder- </Button>- )}- </ProjectPermissionCan>- </div>- <div className="w-full">- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.SecretImports}- >- {(isAllowed) => (- <Button- leftIcon={<FontAwesomeIcon icon={faFileImport} />}- onClick={() => handlePopUpOpen("addSecretImport")}- isDisabled={isReadOnly || isRollbackMode || !isAllowed}- variant="outline_bg"- className="h-10"- isFullWidth- >- Add Import- </Button>- )}- </ProjectPermissionCan>- </div>+ <div className="w-full">+ <ProjectPermissionCan+ I={ProjectPermissionActions.Edit}+ a={subject(ProjectPermissionSub.SecretImports, {+ environment,+ secretPath+ })}+ >+ {(isAllowed) => (+ <Button+ leftIcon={<FontAwesomeIcon icon={faFileImport} />}+ onClick={() => handlePopUpOpen("addSecretImport")}+ isDisabled={isReadOnly || isRollbackMode || !isAllowed}+ variant="outline_bg"+ className="h-10"+ isFullWidth+ >+ Add Import+ </Button>+ )}+ </ProjectPermissionCan></div>- </DropdownMenuContent>- </DropdownMenu>- </div>- )}- {isRollbackMode && (+ </div>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ {isRollbackMode && (+ <Button+ variant="star"+ leftIcon={<FontAwesomeIcon icon={faArrowLeft} />}+ onClick={() => {+ setSnaphotId(null);+ reset({ ...secrets, isSnapshotMode: false });+ }}+ className="h-10"+ >+ Go back+ </Button>+ )}+ <ProjectPermissionCan+ I={+ isRollbackMode+ ? ProjectPermissionActions.Create+ : (ProjectPermissionActions.Edit as any)+ }+ a={+ isRollbackMode+ ? ProjectPermissionSub.SecretRollback+ : subject(ProjectPermissionSub.Secrets, {+ environment,+ secretPath+ })+ }+ >+ {(isAllowed) => (<Button- variant="star"- leftIcon={<FontAwesomeIcon icon={faArrowLeft} />}- onClick={() => {- setSnaphotId(null);- reset({ ...secrets, isSnapshotMode: false });- }}- className="h-10"+ isDisabled={isSubmitDisabled || !isAllowed}+ isLoading={isSubmitting}+ leftIcon={<FontAwesomeIcon icon={isRollbackMode ? faClockRotateLeft : faCheck} />}+ onClick={handleSubmit(onSaveSecret)}+ className="h-10 text-black"+ color="primary"+ variant="solid">- Go back+ {isRollbackMode ? "Rollback" : "Save Changes"}</Button>)}- <ProjectPermissionCan- I={- isRollbackMode- ? ProjectPermissionActions.Create- : (ProjectPermissionActions.Edit as any)- }- a={- isRollbackMode- ? ProjectPermissionSub.SecretRollback- : ProjectPermissionSub.Secrets- }- >- {(isAllowed) => (- <Button- isDisabled={isSubmitDisabled || !isAllowed}- isLoading={isSubmitting}- leftIcon={- <FontAwesomeIcon icon={isRollbackMode ? faClockRotateLeft : faCheck} />- }- onClick={handleSubmit(onSaveSecret)}- className="h-10 text-black"- color="primary"- variant="solid"- >- {isRollbackMode ? "Rollback" : "Save Changes"}- </Button>- )}- </ProjectPermissionCan>- </div>+ </ProjectPermissionCan></div>- <div- className={`${- isEmptyPage ? "flex flex-col flex-grow items-center justify-center" : ""- } no-scrollbar::-webkit-scrollbar mt-3 flex flex-col overflow-x-hidden overflow-y-scroll no-scrollbar`}- ref={secretContainer}- >- {!isEmptyPage && (- <DndContext- onDragEnd={handleDragEnd}- sensors={sensors}- collisionDetection={closestCenter}- modifiers={[restrictToVerticalAxis]}- >- <TableContainer className="no-scrollbar::-webkit-scrollbar max-h-[calc(100%-120px)] no-scrollbar flex-grow">- <table className="secret-table relative">- <SecretTableHeader sortDir={sortDir} onSort={onSortSecrets} />- <tbody className="max-h-96 overflow-y-auto">- <SecretImportSection- onSecretImportDelete={handleSecretImportDelPopUpOpen}- secrets={secrets?.secrets}- importedSecrets={importedSecrets}- items={items}- searchTerm={searchFilter}- />- <FolderSection- onFolderOpen={handleFolderOpen}- onFolderUpdate={handleFolderCreatePopUpOpen}- onFolderDelete={handleFolderDeletePopUpOpen}- folders={folderList}- search={searchFilter}- />- {fields.map(({ id, _id }, index) => (+ </div>+ <div+ className={`${+ isEmptyPage ? "flex flex-col flex-grow items-center justify-center" : ""+ } no-scrollbar::-webkit-scrollbar mt-3 flex flex-col overflow-x-hidden overflow-y-scroll no-scrollbar`}+ ref={secretContainer}+ >+ {!isEmptyPage && (+ <DndContext+ onDragEnd={handleDragEnd}+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[restrictToVerticalAxis]}+ >+ <TableContainer className="no-scrollbar::-webkit-scrollbar max-h-[calc(100%-120px)] no-scrollbar flex-grow">+ <table className="secret-table relative">+ <SecretTableHeader sortDir={sortDir} onSort={onSortSecrets} />+ <tbody className="max-h-96 overflow-y-auto">+ <SecretImportSection+ environment={environment}+ secretPath={secretPath}+ onSecretImportDelete={handleSecretImportDelPopUpOpen}+ secrets={secrets?.secrets}+ importedSecrets={importedSecrets}+ items={items}+ searchTerm={searchFilter}+ />+ <FolderSection+ environment={environment}+ secretPath={secretPath}+ onFolderOpen={handleFolderOpen}+ onFolderUpdate={handleFolderCreatePopUpOpen}+ onFolderDelete={handleFolderDeletePopUpOpen}+ folders={folderList}+ search={searchFilter}+ />+ {permission.can(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.Secrets, { environment, secretPath })+ ) ? (+ fields.map(({ id, _id }, index) => (<SecretInputRowkey={id}+ environment={environment}+ secretPath={secretPath}secUniqId={_id}isReadOnly={isReadOnly}isRollbackMode={isRollbackMode}@@ -1088,185 +1078,197 @@ export const DashboardPage = withProjectPermission(setValue={setValue}autoCapitalization={currentWorkspace?.autoCapitalization}/>- ))}- {!isReadOnly && !isRollbackMode && (- <tr>- <td colSpan={3} className="hover:bg-mineshaft-700">- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Secrets}- >- {(isAllowed) => (- <button- type="button"- className="flex h-8 w-full cursor-default items-center justify-start pl-12 font-normal text-bunker-300"- onClick={onAppendSecret}- disabled={!isAllowed}- >- <FontAwesomeIcon icon={faPlus} />- <span className="ml-2 w-20">Add Secret</span>- </button>- )}- </ProjectPermissionCan>- </td>- </tr>- )}- </tbody>- </table>- </TableContainer>- </DndContext>- )}- <FormProvider {...method}>- <PitDrawer- isDrawerOpen={popUp?.secretSnapshots?.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("secretSnapshots", isOpen)}- fetchNextPage={fetchNextPage}- hasNextPage={hasNextPage}- snapshotId={snapshotId}- isFetchingNextPage={isFetchingNextPage}- secretSnaphots={secretSnaphots}- onSelectSnapshot={setSnaphotId}- />- <SecretDetailDrawer- onSave={handleSubmit(onSaveSecret)}- isReadOnly={isReadOnly || isRollbackMode}- onSecretDelete={onSecretDelete}- isDrawerOpen={popUp?.secretDetails?.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("secretDetails", isOpen)}- secretVersion={secretVersion}- index={(popUp?.secretDetails?.data as TSecretDetailsOpen)?.index}- onEnvCompare={(key) => handlePopUpOpen("compareSecrets", key)}- />- </FormProvider>- <SecretDropzone- workspaceId={workspaceId}- isSmaller={!isEmptyPage}- onParsedEnv={handleUploadedEnv}- onAddNewSecret={onAppendSecret}- environments={userAvailableEnvs}- decryptFileKey={latestFileKey!}+ ))+ ) : (+ <tr>+ <td colSpan={3}>+ <PermissionDeniedBanner />+ </td>+ </tr>+ )}+ {!isReadOnly && !isRollbackMode && (+ <tr>+ <td colSpan={3} className="hover:bg-mineshaft-700">+ <ProjectPermissionCan+ I={ProjectPermissionActions.Create}+ a={subject(ProjectPermissionSub.Secrets, {+ environment,+ secretPath+ })}+ >+ {(isAllowed) => (+ <button+ type="button"+ className="flex h-8 w-full cursor-default items-center justify-start pl-12 font-normal text-bunker-300"+ onClick={onAppendSecret}+ disabled={!isAllowed}+ >+ <FontAwesomeIcon icon={faPlus} />+ <span className="ml-2 w-20">Add Secret</span>+ </button>+ )}+ </ProjectPermissionCan>+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </TableContainer>+ </DndContext>+ )}+ <FormProvider {...method}>+ <PitDrawer+ isDrawerOpen={popUp?.secretSnapshots?.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("secretSnapshots", isOpen)}+ fetchNextPage={fetchNextPage}+ hasNextPage={hasNextPage}+ snapshotId={snapshotId}+ isFetchingNextPage={isFetchingNextPage}+ secretSnaphots={secretSnaphots}+ onSelectSnapshot={setSnaphotId}/>- </div>- {/* secrets table and drawers, modals */}- </form>- {/* Create a new tag modal */}- <Modal- isOpen={popUp?.addTag?.isOpen}- onOpenChange={(open) => {- handlePopUpToggle("addTag", open);- }}+ <SecretDetailDrawer+ environment={environment}+ secretPath={secretPath}+ onSave={handleSubmit(onSaveSecret)}+ isReadOnly={isReadOnly || isRollbackMode}+ onSecretDelete={onSecretDelete}+ isDrawerOpen={popUp?.secretDetails?.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("secretDetails", isOpen)}+ secretVersion={secretVersion}+ index={(popUp?.secretDetails?.data as TSecretDetailsOpen)?.index}+ onEnvCompare={(key) => handlePopUpOpen("compareSecrets", key)}+ />+ </FormProvider>+ <SecretDropzone+ environment={environment}+ secretPath={secretPath}+ workspaceId={workspaceId}+ isSmaller={!isEmptyPage}+ onParsedEnv={handleUploadedEnv}+ onAddNewSecret={onAppendSecret}+ environments={userAvailableEnvs}+ decryptFileKey={latestFileKey!}+ />+ </div>+ {/* secrets table and drawers, modals */}+ </form>+ {/* Create a new tag modal */}+ <Modal+ isOpen={popUp?.addTag?.isOpen}+ onOpenChange={(open) => {+ handlePopUpToggle("addTag", open);+ }}+ >+ <ModalContent+ title="Create tag"+ subTitle="Specify your tag name, and the slug will be created automatically.">- <ModalContent- title="Create tag"- subTitle="Specify your tag name, and the slug will be created automatically."- >- <CreateTagModal onCreateTag={onCreateWsTag} />- </ModalContent>- </Modal>- {/* Uploaded env override or not confirmation modal */}- <Modal- isOpen={popUp?.uploadedSecOpts?.isOpen}- onOpenChange={(open) => handlePopUpToggle("uploadedSecOpts", open)}+ <CreateTagModal onCreateTag={onCreateWsTag} />+ </ModalContent>+ </Modal>+ {/* Uploaded env override or not confirmation modal */}+ <Modal+ isOpen={popUp?.uploadedSecOpts?.isOpen}+ onOpenChange={(open) => handlePopUpToggle("uploadedSecOpts", open)}+ >+ <ModalContent+ title="Duplicate Secrets"+ footerContent={[+ <Button+ key="keep-old-btn"+ className="mr-4"+ onClick={() => handlePopUpClose("uploadedSecOpts")}+ >+ Keep old+ </Button>,+ <Button colorSchema="danger" key="overwrite-btn" onClick={onOverwriteSecrets}>+ Overwrite+ </Button>+ ]}>- <ModalContent- title="Duplicate Secrets"- footerContent={[- <Button- key="keep-old-btn"- className="mr-4"- onClick={() => handlePopUpClose("uploadedSecOpts")}- >- Keep old- </Button>,- <Button colorSchema="danger" key="overwrite-btn" onClick={onOverwriteSecrets}>- Overwrite- </Button>- ]}- >- <div className="flex flex-col space-y-2 text-gray-300">- <div>Your file contains following duplicate secrets</div>- <div className="text-sm text-gray-400">- {Object.keys((popUp?.uploadedSecOpts?.data as TSecOverwriteOpt)?.secrets || {})- ?.map((key) => key)- .join(", ")}- </div>- <div>Are you sure you want to overwrite these secrets?</div>+ <div className="flex flex-col space-y-2 text-gray-300">+ <div>Your file contains following duplicate secrets</div>+ <div className="text-sm text-gray-400">+ {Object.keys((popUp?.uploadedSecOpts?.data as TSecOverwriteOpt)?.secrets || {})+ ?.map((key) => key)+ .join(", ")}</div>- </ModalContent>- </Modal>- <Modal- isOpen={popUp?.folderForm?.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("folderForm", isOpen)}- >- <ModalContent title={isEditFolder ? "Edit Folder" : "Create Folder"}>- <FolderForm- isEdit={isEditFolder}- onUpdateFolder={handleFolderUpdate}- onCreateFolder={handleFolderCreate}- defaultFolderName={(popUp?.folderForm?.data as TEditFolderForm)?.name}- />- </ModalContent>- </Modal>- <Modal- isOpen={popUp?.addSecretImport?.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("addSecretImport", isOpen)}+ <div>Are you sure you want to overwrite these secrets?</div>+ </div>+ </ModalContent>+ </Modal>+ <Modal+ isOpen={popUp?.folderForm?.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("folderForm", isOpen)}+ >+ <ModalContent title={isEditFolder ? "Edit Folder" : "Create Folder"}>+ <FolderForm+ isEdit={isEditFolder}+ onUpdateFolder={handleFolderUpdate}+ onCreateFolder={handleFolderCreate}+ defaultFolderName={(popUp?.folderForm?.data as TEditFolderForm)?.name}+ />+ </ModalContent>+ </Modal>+ <Modal+ isOpen={popUp?.addSecretImport?.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("addSecretImport", isOpen)}+ >+ <ModalContent+ title="Add Secret Link"+ subTitle="To inherit secrets from another environment or folder">- <ModalContent- title="Add Secret Link"- subTitle="To inherit secrets from another environment or folder"- >- <SecretImportForm- environments={currentWorkspace?.environments}- onCreate={handleSecretImportCreate}- />- </ModalContent>- </Modal>- <DeleteActionModal- isOpen={popUp.deleteFolder.isOpen}- deleteKey={(popUp.deleteFolder?.data as TDeleteFolderForm)?.name}- title="Do you want to delete this folder?"- onChange={(isOpen) => handlePopUpToggle("deleteFolder", isOpen)}- onDeleteApproved={handleFolderDelete}- />- <DeleteActionModal- isOpen={popUp.deleteSecretImport.isOpen}- deleteKey="unlink"- title="Do you want to remove this secret import?"- subTitle={`This will unlink secrets from environment ${- (popUp.deleteSecretImport?.data as TDeleteSecretImport)?.environment- } of path ${(popUp.deleteSecretImport?.data as TDeleteSecretImport)?.secretPath}?`}- onChange={(isOpen) => handlePopUpToggle("deleteSecretImport", isOpen)}- onDeleteApproved={handleSecretImportDelete}- />- <Modal- isOpen={popUp?.compareSecrets?.isOpen}- onOpenChange={(open) => handlePopUpToggle("compareSecrets", open)}+ <SecretImportForm+ environments={currentWorkspace?.environments}+ onCreate={handleSecretImportCreate}+ />+ </ModalContent>+ </Modal>+ <DeleteActionModal+ isOpen={popUp.deleteFolder.isOpen}+ deleteKey={(popUp.deleteFolder?.data as TDeleteFolderForm)?.name}+ title="Do you want to delete this folder?"+ onChange={(isOpen) => handlePopUpToggle("deleteFolder", isOpen)}+ onDeleteApproved={handleFolderDelete}+ />+ <DeleteActionModal+ isOpen={popUp.deleteSecretImport.isOpen}+ deleteKey="unlink"+ title="Do you want to remove this secret import?"+ subTitle={`This will unlink secrets from environment ${+ (popUp.deleteSecretImport?.data as TDeleteSecretImport)?.environment+ } of path ${(popUp.deleteSecretImport?.data as TDeleteSecretImport)?.secretPath}?`}+ onChange={(isOpen) => handlePopUpToggle("deleteSecretImport", isOpen)}+ onDeleteApproved={handleSecretImportDelete}+ />+ <Modal+ isOpen={popUp?.compareSecrets?.isOpen}+ onOpenChange={(open) => handlePopUpToggle("compareSecrets", open)}+ >+ <ModalContent+ title={popUp?.compareSecrets?.data as string}+ subTitle="Below is the comparison of secret values across available environments"+ overlayClassName="z-[90]">- <ModalContent- title={popUp?.compareSecrets?.data as string}- subTitle="Below is the comparison of secret values across available environments"- overlayClassName="z-[90]"- >- <CompareSecret- workspaceId={workspaceId}- envs={userAvailableEnvs || []}- secretKey={popUp?.compareSecrets?.data as string}- />- </ModalContent>- </Modal>- {subscription && (- <UpgradePlanModal- isOpen={popUp.upgradePlan.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}- text={- subscription.slug === null- ? "You can perform point-in-time recovery under an Enterprise license"- : "You can perform point-in-time recovery if you switch to Infisical's Team plan"- }+ <CompareSecret+ workspaceId={workspaceId}+ envs={userAvailableEnvs || []}+ secretKey={popUp?.compareSecrets?.data as string}/>- )}- </div>- );- },- { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Secrets }-);+ </ModalContent>+ </Modal>+ {subscription && (+ <UpgradePlanModal+ isOpen={popUp.upgradePlan.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}+ text={+ subscription.slug === null+ ? "You can perform point-in-time recovery under an Enterprise license"+ : "You can perform point-in-time recovery if you switch to Infisical's Team plan"+ }+ />+ )}+ </div>+ );+};diff --git a/frontend/src/views/DashboardPage/components/FolderSection/FolderSection.tsx b/frontend/src/views/DashboardPage/components/FolderSection/FolderSection.tsxindex 4fa6df2861..516bb74b4c 100644--- a/frontend/src/views/DashboardPage/components/FolderSection/FolderSection.tsx+++ b/frontend/src/views/DashboardPage/components/FolderSection/FolderSection.tsx@@ -1,4 +1,5 @@import { memo } from "react";+import { subject } from "@casl/ability";import { faEdit, faFolder, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -9,6 +10,8 @@ import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";type Props = {folders?: Array<{ id: string; name: string }>;search?: string;+ environment: string;+ secretPath: string;onFolderUpdate: (folderId: string, name: string) => void;onFolderDelete: (folderId: string, name: string) => void;onFolderOpen: (folderId: string) => void;@@ -20,7 +23,9 @@ export const FolderSection = memo(onFolderDelete: handleFolderDelete,onFolderOpen: handleFolderOpen,search = "",- folders = []+ folders = [],+ environment,+ secretPath}: Props) => {return (<>@@ -51,7 +56,7 @@ export const FolderSection = memo(<div className="duration-0 flex h-10 w-16 items-center justify-end space-x-2.5 overflow-hidden border-l border-mineshaft-600 transition-all"><ProjectPermissionCanI={ProjectPermissionActions.Edit}- a={ProjectPermissionSub.Folders}+ a={subject(ProjectPermissionSub.Folders, { environment, secretPath })}>{(isAllowed) => (<div className="opacity-0 group-hover:opacity-100">@@ -72,7 +77,7 @@ export const FolderSection = memo(</ProjectPermissionCan><ProjectPermissionCanI={ProjectPermissionActions.Delete}- a={ProjectPermissionSub.Folders}+ a={subject(ProjectPermissionSub.Folders, { environment, secretPath })}>{(isAllowed) => (<div className="opacity-0 group-hover:opacity-100">diff --git a/frontend/src/views/DashboardPage/components/SecretDetailDrawer/SecretDetailDrawer.tsx b/frontend/src/views/DashboardPage/components/SecretDetailDrawer/SecretDetailDrawer.tsxindex 9668fe8199..ef85c4896d 100644--- a/frontend/src/views/DashboardPage/components/SecretDetailDrawer/SecretDetailDrawer.tsx+++ b/frontend/src/views/DashboardPage/components/SecretDetailDrawer/SecretDetailDrawer.tsx@@ -1,4 +1,5 @@import { useFormContext, useWatch } from "react-hook-form";+import { subject } from "@casl/ability";import { faCircle, faCircleDot, faShuffle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -23,6 +24,8 @@ import { GenRandomNumber } from "./GenRandomNumber";type Props = {isDrawerOpen: boolean;+ environment: string;+ secretPath: string;onOpenChange: (isOpen: boolean) => void;index: number;isReadOnly?: boolean;@@ -41,7 +44,9 @@ export const SecretDetailDrawer = ({isReadOnly,onSecretDelete,onSave,- onEnvCompare+ onEnvCompare,+ environment,+ secretPath}: Props): JSX.Element => {const [canRevealSecVal, setCanRevealSecVal] = useToggle();const [canRevealSecOverride, setCanRevealSecOverride] = useToggle();@@ -89,7 +94,7 @@ export const SecretDetailDrawer = ({<div className="flex w-full space-x-2"><ProjectPermissionCanI={ProjectPermissionActions.Edit}- a={ProjectPermissionSub.Secrets}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}>{(isAllowed) => (<Button isFullWidth onClick={onSave} isDisabled={isReadOnly || !isAllowed}>@@ -98,8 +103,8 @@ export const SecretDetailDrawer = ({)}</ProjectPermissionCan><ProjectPermissionCan- I={ProjectPermissionActions.Edit}- a={ProjectPermissionSub.Secrets}+ I={ProjectPermissionActions.Delete}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}>{(isAllowed) => (<Buttondiff --git a/frontend/src/views/DashboardPage/components/SecretDropzone/SecretDropzone.tsx b/frontend/src/views/DashboardPage/components/SecretDropzone/SecretDropzone.tsxindex d7d5da1314..df022f4bb5 100644--- a/frontend/src/views/DashboardPage/components/SecretDropzone/SecretDropzone.tsx+++ b/frontend/src/views/DashboardPage/components/SecretDropzone/SecretDropzone.tsx@@ -1,6 +1,7 @@import { ChangeEvent, DragEvent, useEffect, useState } from "react";import { Controller, useForm } from "react-hook-form";import { useTranslation } from "react-i18next";+import { subject } from "@casl/ability";import { faSquareCheck } from "@fortawesome/free-regular-svg-icons";import {faClone,@@ -78,6 +79,8 @@ type Props = {environments?: { name: string; slug: string }[];workspaceId: string;decryptFileKey: UserWsKeyPair;+ environment: string;+ secretPath: string;};export const SecretDropzone = ({@@ -86,7 +89,9 @@ export const SecretDropzone = ({onAddNewSecret,environments = [],workspaceId,- decryptFileKey+ decryptFileKey,+ environment,+ secretPath}: Props): JSX.Element => {const { t } = useTranslation();const [isDragActive, setDragActive] = useToggle();@@ -109,16 +114,16 @@ export const SecretDropzone = ({defaultValues: { secretPath: "/", environment: environments?.[0]?.slug }});- const secretPath = watch("secretPath");+ const envCopySecPath = watch("secretPath");const selectedEnvSlug = watch("environment");- const debouncedSecretPath = useDebounce(secretPath);+ const debouncedEnvCopySecretPath = useDebounce(envCopySecPath);const { data: secrets, isLoading: isSecretsLoading } = useGetProjectSecrets({workspaceId,env: selectedEnvSlug,- secretPath: debouncedSecretPath,+ secretPath: debouncedEnvCopySecretPath,isPaused:- !(Boolean(workspaceId) && Boolean(selectedEnvSlug) && Boolean(debouncedSecretPath)) &&+ !(Boolean(workspaceId) && Boolean(selectedEnvSlug) && Boolean(debouncedEnvCopySecretPath)) &&!popUp.importSecEnv.isOpen,decryptFileKey});@@ -126,7 +131,7 @@ export const SecretDropzone = ({useEffect(() => {setValue("secrets", {});setSearchFilter("");- }, [debouncedSecretPath]);+ }, [debouncedEnvCopySecretPath]);const handleDrag = (e: DragEvent) => {e.preventDefault();@@ -238,7 +243,7 @@ export const SecretDropzone = ({</div><ProjectPermissionCanI={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Secrets}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}>{(isAllowed) => (<input@@ -271,16 +276,22 @@ export const SecretDropzone = ({}}><ModalTrigger asChild>- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Secrets}- >- {(isAllowed) => (- <Button isDisabled={!isAllowed} variant="star" size={isSmaller ? "xs" : "sm"}>- Copy Secrets From An Environment- </Button>- )}- </ProjectPermissionCan>+ <div>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Create}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}+ >+ {(isAllowed) => (+ <Button+ isDisabled={!isAllowed}+ variant="star"+ size={isSmaller ? "xs" : "sm"}+ >+ Copy Secrets From An Environment+ </Button>+ )}+ </ProjectPermissionCan>+ </div></ModalTrigger><ModalContentclassName="max-w-2xl"@@ -416,7 +427,7 @@ export const SecretDropzone = ({{!isSmaller && (<ProjectPermissionCanI={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Secrets}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}>{(isAllowed) => (<Button variant="star" onClick={onAddNewSecret} isDisabled={!isAllowed}>diff --git a/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportItem.tsx b/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportItem.tsxindex 866578b730..6d9f23e470 100644--- a/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportItem.tsx+++ b/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportItem.tsx@@ -1,4 +1,5 @@import { useEffect } from "react";+import { subject } from "@casl/ability";import { useSortable } from "@dnd-kit/sortable";import {faFileImport,@@ -11,11 +12,13 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { ProjectPermissionCan } from "@app/components/permissions";import { EmptyState, IconButton, SecretInput, TableContainer, Tooltip } from "@app/components/v2";-import { ProjectPermissionActions, ProjectPermissionSub,useWorkspace } from "@app/context";+import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";import { useToggle } from "@app/hooks";type Props = {onDelete: (environment: string, secretPath: string) => void;+ environment: string;+ secretPath: string;importedEnv: string;importedSecPath: string;importedSecrets: { key: string; value: string; overriden: { env: string; secretPath: string } }[];@@ -40,7 +43,9 @@ export const SecretImportItem = ({importedSecPath,onDelete,importedSecrets = [],- searchTerm = ""+ searchTerm = "",+ secretPath,+ environment}: Props) => {const [isExpanded, setIsExpanded] = useToggle();const { attributes, listeners, transform, transition, setNodeRef, isDragging } = useSortable({@@ -114,7 +119,7 @@ export const SecretImportItem = ({</div><ProjectPermissionCanI={ProjectPermissionActions.Delete}- a={ProjectPermissionSub.SecretImports}+ a={subject(ProjectPermissionSub.SecretImports, { environment, secretPath })}>{(isAllowed) => (<div className="opacity-0 group-hover:opacity-100">diff --git a/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportSection.tsx b/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportSection.tsxindex 9d796d0797..db12e84a49 100644--- a/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportSection.tsx+++ b/frontend/src/views/DashboardPage/components/SecretImportSection/SecretImportSection.tsx@@ -59,13 +59,23 @@ export const computeImportedSecretRows = (type Props = {secrets?: DecryptedSecret[];importedSecrets?: TImportedSecrets;+ environment: string;+ secretPath: string;onSecretImportDelete: (env: string, secPath: string) => void;items: { id: string; environment: string; secretPath: string }[];searchTerm: string;};export const SecretImportSection = memo(- ({ secrets = [], importedSecrets = [], onSecretImportDelete, items = [], searchTerm = "" }: Props) => {+ ({+ secrets = [],+ environment,+ secretPath,+ importedSecrets = [],+ onSecretImportDelete,+ items = [],+ searchTerm = ""+ }: Props) => {const { currentWorkspace } = useWorkspace();const environments = currentWorkspace?.environments || [];@@ -82,6 +92,8 @@ export const SecretImportSection = memo(secrets,environments)}+ secretPath={secretPath}+ environment={environment}onDelete={onSecretImportDelete}importedSecPath={impSecPath}searchTerm={searchTerm}diff --git a/frontend/src/views/DashboardPage/components/SecretInputRow/SecretInputRow.tsx b/frontend/src/views/DashboardPage/components/SecretInputRow/SecretInputRow.tsxindex 307cc981b2..c31c6df2e5 100644--- a/frontend/src/views/DashboardPage/components/SecretInputRow/SecretInputRow.tsx+++ b/frontend/src/views/DashboardPage/components/SecretInputRow/SecretInputRow.tsx@@ -8,6 +8,7 @@ import {UseFormSetValue,useWatch} from "react-hook-form";+import { subject } from "@casl/ability";import {faCheck,faCodeBranch,@@ -22,31 +23,34 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { cx } from "cva";import { twMerge } from "tailwind-merge";+// TODO:(akhilmhdh): Refactor this+import AddTagPopoverContent from "@app/components/AddTagPopoverContent/AddTagPopoverContent";import { ProjectPermissionCan } from "@app/components/permissions";import {+ FormControl,HoverCard,HoverCardContent,HoverCardTrigger,IconButton,Input,Popover,+ PopoverContent,PopoverTrigger,SecretInput,Tag,+ TextArea,Tooltip} from "@app/components/v2";-import {- ProjectPermissionActions,- ProjectPermissionSub-} from "@app/context/ProjectPermissionContext/types";+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";import { useToggle } from "@app/hooks";import { WsTag } from "@app/hooks/api/types";-import AddTagPopoverContent from "../../../../components/AddTagPopoverContent/AddTagPopoverContent";import { FormData, SecretActionType } from "../../DashboardPage.utils";type Props = {index: number;+ environment: string;+ secretPath: string;// backend generated unique idsecUniqId?: string;// permission and external state's that decided to hide or show@@ -74,6 +78,8 @@ type Props = {export const SecretInputRow = memo(({index,+ secretPath,+ environment,isSecretValueHidden,onRowExpand,isReadOnly,@@ -84,7 +90,7 @@ export const SecretInputRow = memo(onSecretDelete,searchTerm,control,- // register,+ register,setValue,isKeyError,keyError,@@ -222,7 +228,6 @@ export const SecretInputRow = memo(<td className="flex h-10 w-10 items-center justify-center border-none px-4"><div className="w-10 text-center text-xs text-bunker-400">{index + 1}</div></td>-<Controllercontrol={control}defaultValue=""@@ -361,16 +366,24 @@ export const SecretInputRow = memo(<Popover><PopoverTrigger asChild><div className="w-0 group-hover:w-6 data-[state=open]:w-6">- <Tooltip content="Add tags">- <IconButton- variant="plain"- size="md"- ariaLabel="add-tag"- className="py-[0.42rem]"- >- <FontAwesomeIcon icon={faTags} />- </IconButton>- </Tooltip>+ <ProjectPermissionCan+ renderTooltip+ allowedLabel="Add Tags"+ I={ProjectPermissionActions.Edit}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}+ >+ {(isAllowed) => (+ <IconButton+ isDisabled={!isAllowed}+ variant="plain"+ size="md"+ ariaLabel="add-tags"+ className="py-[0.42rem]"+ >+ <FontAwesomeIcon icon={faTags} />+ </IconButton>+ )}+ </ProjectPermissionCan></div></PopoverTrigger><AddTagPopoverContent@@ -390,55 +403,76 @@ export const SecretInputRow = memo(<div className="flex h-8 flex-row items-center pr-2">{!isAddOnly && (<div>- <Tooltip content="Override with a personal value">- <IconButton- variant="plain"- className={twMerge(- "mt-0.5 w-0 overflow-hidden p-0 group-hover:ml-1 group-hover:w-7",- isOverridden && "ml-1 w-7 text-primary"- )}- onClick={onSecretOverride}- size="md"- isDisabled={isRollbackMode || isReadOnly}- ariaLabel="info"- >- <div className="flex items-center space-x-1">- <FontAwesomeIcon icon={faCodeBranch} className="text-base" />- </div>- </IconButton>- </Tooltip>- </div>- )}- <Tooltip content="Comment">- <div className="mt-0.5 overflow-hidden ">- <Popover>- <PopoverTrigger asChild>+ <ProjectPermissionCan+ renderTooltip+ allowedLabel="Override with a personal value"+ I={ProjectPermissionActions.Edit}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}+ >+ {(isAllowed) => (<IconButton+ variant="plain"className={twMerge(- "w-7 overflow-hidden p-0",- "w-0 group-hover:w-7 data-[state=open]:w-7",- hasComment ? "w-7 text-primary" : "group-hover:w-7"+ "mt-0.5 w-0 overflow-hidden p-0 group-hover:ml-1 group-hover:w-7",+ isOverridden && "ml-1 w-7 text-primary")}- variant="plain"+ onClick={onSecretOverride}size="md"- ariaLabel="add-tag"+ isDisabled={isRollbackMode || isReadOnly || !isAllowed}+ ariaLabel="info">- <FontAwesomeIcon icon={faComment} />+ <div className="flex items-center space-x-1">+ <FontAwesomeIcon icon={faCodeBranch} className="text-base" />+ </div></IconButton>- </PopoverTrigger>- <AddTagPopoverContent- wsTags={wsTags}- secKey={secKey || "this secret"}- selectedTagIds={selectedTagIds}- handleSelectTag={(wsTag: WsTag) => onSelectTag(wsTag)}- handleTagOnMouseEnter={(wsTag: WsTag) => handleTagOnMouseEnter(wsTag)}- handleTagOnMouseLeave={() => handleTagOnMouseLeave()}- checkIfTagIsVisible={(wsTag: WsTag) => checkIfTagIsVisible(wsTag)}- handleOnCreateTagOpen={() => onCreateTagOpen()}- />- </Popover>+ )}+ </ProjectPermissionCan></div>- </Tooltip>+ )}+ <div className="mt-0.5 overflow-hidden ">+ <Popover>+ <PopoverTrigger asChild>+ <div>+ <ProjectPermissionCan+ renderTooltip+ allowedLabel="Comment"+ I={ProjectPermissionActions.Edit}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}+ >+ {(isAllowed) => (+ <IconButton+ className={twMerge(+ "w-7 overflow-hidden p-0",+ "w-0 group-hover:w-7 data-[state=open]:w-7",+ hasComment ? "w-7 text-primary" : "group-hover:w-7"+ )}+ isDisabled={!isAllowed}+ variant="plain"+ size="md"+ ariaLabel="add-comment"+ >+ <FontAwesomeIcon icon={faComment} />+ </IconButton>+ )}+ </ProjectPermissionCan>+ </div>+ </PopoverTrigger>+ <PopoverContent+ className="w-auto border border-mineshaft-600 bg-mineshaft-800 p-2 drop-shadow-2xl"+ sticky="always"+ >+ <FormControl label="Comment" className="mb-0">+ <TextArea+ isDisabled={isReadOnly || isRollbackMode || shouldBeBlockedInAddOnly}+ className="border border-mineshaft-600 text-sm"+ {...register(`secrets.${index}.comment`)}+ rows={8}+ cols={30}+ />+ </FormControl>+ </PopoverContent>+ </Popover>+ </div></div><div className="duration-0 flex w-16 justify-center overflow-hidden border-l border-mineshaft-600 pl-2 transition-all"><div className="flex h-8 items-center space-x-2.5">@@ -457,29 +491,29 @@ export const SecretInputRow = memo(</Tooltip></div>)}- <ProjectPermissionCan- I={ProjectPermissionActions.Delete}- a={ProjectPermissionSub.Secrets}- >- {(isAllowed) => (- <div className="opacity-0 group-hover:opacity-100">- <Tooltip content="Delete">- <IconButton- size="lg"- variant="plain"- colorSchema="danger"- ariaLabel="delete"- isDisabled={isReadOnly || isRollbackMode || !isAllowed}- onClick={() => {- onSecretDelete(index, secKey, secId, idOverride);- }}- >- <FontAwesomeIcon icon={faXmark} />- </IconButton>- </Tooltip>- </div>- )}- </ProjectPermissionCan>+ <div className="opacity-0 group-hover:opacity-100">+ <ProjectPermissionCan+ I={ProjectPermissionActions.Delete}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}+ renderTooltip+ allowedLabel="Delete"+ >+ {(isAllowed) => (+ <IconButton+ size="lg"+ variant="plain"+ colorSchema="danger"+ ariaLabel="delete"+ isDisabled={isReadOnly || isRollbackMode || !isAllowed}+ onClick={() => {+ onSecretDelete(index, secKey, secId, idOverride);+ }}+ >+ <FontAwesomeIcon icon={faXmark} />+ </IconButton>+ )}+ </ProjectPermissionCan>+ </div></div></div></td>diff --git a/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/MultiEnvProjectPermission.tsx b/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/MultiEnvProjectPermission.tsxindex 780c50bd24..c5025fce53 100644--- a/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/MultiEnvProjectPermission.tsx+++ b/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/MultiEnvProjectPermission.tsx@@ -7,6 +7,7 @@ import { twMerge } from "tailwind-merge";import {Checkbox,+ FormControl,Input,Select,SelectItem,@@ -68,7 +69,7 @@ export const MultiEnvProjectPermission = ({const handlePermissionChange = (val: Permission) => {switch (val) {case Permission.NoAccess:- setValue(`permissions.${formName}`, {}, { shouldDirty: true });+ setValue(`permissions.${formName}`, undefined, { shouldDirty: true });break;case Permission.FullAccess:setValue(@@ -151,7 +152,14 @@ export const MultiEnvProjectPermission = ({name={`permissions.${formName}.${slug}.secretPath`}control={control}render={({ field }) => (- <Input {...field} className="w-full overflow-ellipsis" />+ /* eslint-disable-next-line no-template-curly-in-string */+ <FormControl helperText="Ex pattern: /, /**, /{folder1,folder2}">+ <Input+ {...field}+ className="w-full overflow-ellipsis"+ placeholder="Glob patterns are supported"+ />+ </FormControl>)}/></Td>diff --git a/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.tsx b/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.tsxindex 31406c1a9e..f404001853 100644--- a/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.tsx+++ b/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.tsx@@ -133,6 +133,7 @@ export const ProjectRoleModifySection = ({ role, onGoBack }: Props) => {const handleRoleUpdate = async (el: TFormSchema) => {if (!role?._id) return;+ console.log(el);try {await updateRole({orgId,diff --git a/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.utils.ts b/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.utils.tsindex 1cfddd7c67..7ff043ab7f 100644--- a/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.utils.ts+++ b/frontend/src/views/Project/MembersPage/components/ProjectRoleListTab/components/ProjectRoleModifySection/ProjectRoleModifySection.utils.ts@@ -73,7 +73,7 @@ const multiEnvApi2Form = (}const secretEnv = permission?.conditions?.environment || "all";- const secretPath = permission?.conditions?.secretPath;+ const secretPath = permission?.conditions?.secretPath?.$glob;// initializeif (formVal && !formVal?.[secretEnv]) {formVal[secretEnv] = { read: false, edit: false, create: false, delete: false, secretPath };@@ -109,6 +109,8 @@ const multiEnvForm2Api = (formVal: Record<string, { secretPath?: string } & { [key: string]: boolean }>,subject: (typeof MULTI_ENV_KEY)[number]) => {+ if (!formVal) return;+const isFullAccess = PERMISSION_ACTIONS.every((action) => formVal?.all?.[action]);// if any of them is set in all push it without any conditionPERMISSION_ACTIONS.forEach((action) => {@@ -130,7 +132,8 @@ const multiEnvForm2Api = (// if not full access for an actionif (!formVal?.all?.[action] && action !== "secretPath" && formVal?.[slug]?.[action]) {const conditions: Record<string, unknown> = { environment: slug };- if (formVal[slug]?.secretPath) conditions.secretPath = formVal?.[slug]?.secretPath;+ if (formVal[slug]?.secretPath)+ conditions.secretPath = { $glob: formVal?.[slug]?.secretPath };permissions.push({ action, subject, conditions });}@@ -141,17 +144,22 @@ const multiEnvForm2Api = (export const formRolePermission2API = (formVal: TFormSchema["permissions"]) => {const permissions: TProjectPermission[] = [];- MULTI_ENV_KEY.forEach((formName) => {- multiEnvForm2Api(permissions, JSON.parse(JSON.stringify(formVal?.[formName] || {})), formName);- });// other than workspace everything else follows same// if in future there is a different follow the above on how workspace is doneObject.entries(formVal || {}).forEach(([rule, actions]) => {- Object.entries(actions).forEach(([action, isAllowed]) => {- if (isAllowed) {- permissions.push({ subject: rule, action });- }- });+ if (MULTI_ENV_KEY.includes(rule as (typeof MULTI_ENV_KEY)[number])) {+ multiEnvForm2Api(+ permissions,+ JSON.parse(JSON.stringify(actions || {})),+ rule as (typeof MULTI_ENV_KEY)[number]+ );+ } else {+ Object.entries(actions).forEach(([action, isAllowed]) => {+ if (isAllowed) {+ permissions.push({ subject: rule, action });+ }+ });+ }});return permissions;};diff --git a/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx b/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsxindex 0edadfe91a..6ad913dad1 100644--- a/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx+++ b/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx@@ -13,6 +13,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";import NavHeader from "@app/components/navigation/NavHeader";+import { PermissionDeniedBanner } from "@app/components/permissions";import {Button,EmptyState,@@ -36,7 +37,6 @@ import {useProjectPermission,useWorkspace} from "@app/context";-import { withProjectPermission } from "@app/hoc";import {useCreateSecretV3,useDeleteSecretV3,@@ -50,7 +50,7 @@ import { FolderBreadCrumbs } from "./components/FolderBreadCrumbs";import { SecretOverviewFolderRow } from "./components/SecretOverviewFolderRow";import { SecretOverviewTableRow } from "./components/SecretOverviewTableRow";-const SecretOverview = () => {+export const SecretOverviewPage = () => {const { t } = useTranslation();const { createNotification } = useNotificationContext();const router = useRouter();@@ -91,11 +91,20 @@ const SecretOverview = () => {}, [isWorkspaceLoading, workspaceId, router.isReady]);const userAvailableEnvs =- currentWorkspace?.environments?.filter(({ slug }) =>- permission.can(- ProjectPermissionActions.Read,- subject(ProjectPermissionSub.Secrets, { environment: slug, secretPath: secretPath || "/" })- )+ currentWorkspace?.environments?.filter(+ ({ slug }) =>+ permission.can(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.Secrets, { environment: slug, secretPath })+ ) ||+ permission.can(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.Folders, { environment: slug, secretPath })+ ) ||+ permission.can(+ ProjectPermissionActions.Read,+ subject(ProjectPermissionSub.SecretImports, { environment: slug, secretPath })+ )) || [];const {@@ -371,18 +380,23 @@ const SecretOverview = () => {onClick={handleFolderClick}/>))}- {filteredSecretNames.map((key, index) => (- <SecretOverviewTableRow- onSecretCreate={handleSecretCreate}- onSecretDelete={handleSecretDelete}- onSecretUpdate={handleSecretUpdate}- key={`overview-${key}-${index + 1}`}- environments={userAvailableEnvs}- secretKey={key}- getSecretByKey={getSecretByKey}- expandableColWidth={expandableTableWidth}- />- ))}+ {userAvailableEnvs?.length > 0 ? (+ filteredSecretNames.map((key, index) => (+ <SecretOverviewTableRow+ secretPath={secretPath}+ onSecretCreate={handleSecretCreate}+ onSecretDelete={handleSecretDelete}+ onSecretUpdate={handleSecretUpdate}+ key={`overview-${key}-${index + 1}`}+ environments={userAvailableEnvs}+ secretKey={key}+ getSecretByKey={getSecretByKey}+ expandableColWidth={expandableTableWidth}+ />+ ))+ ) : (+ <PermissionDeniedBanner />+ )}</TBody><TFoot><Tr className="sticky bottom-0 z-10 border-0 bg-mineshaft-800">@@ -414,8 +428,3 @@ const SecretOverview = () => {</div>);};--export const SecretOverviewPage = withProjectPermission(SecretOverview, {- action: ProjectPermissionActions.Read,- subject: ProjectPermissionSub.Secrets-});diff --git a/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx b/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsxindex c2d15a9242..ff0508d435 100644--- a/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx+++ b/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx@@ -1,4 +1,5 @@import { Controller, useForm } from "react-hook-form";+import { subject } from "@casl/ability";import { faCheck, faCopy, faTrash, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -14,6 +15,7 @@ type Props = {isCreatable?: boolean;isVisible?: boolean;environment: string;+ secretPath: string;onSecretCreate: (env: string, key: string, value: string) => Promise<void>;onSecretUpdate: (env: string, key: string, value: string) => Promise<void>;onSecretDelete: (env: string, key: string) => Promise<void>;@@ -27,6 +29,7 @@ export const SecretEditRow = ({onSecretCreate,onSecretDelete,environment,+ secretPath,isVisible}: Props) => {const {@@ -95,7 +98,7 @@ export const SecretEditRow = ({<><ProjectPermissionCanI={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Secrets}+ a={subject(ProjectPermissionSub.Secrets, { environment, secretPath })}>{(isAllowed) => (<div>diff --git a/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx b/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsxindex 32d32a63a8..ec74dd00a1 100644--- a/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx+++ b/frontend/src/views/SecretOverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx@@ -18,6 +18,7 @@ import { SecretEditRow } from "./SecretEditRow";type Props = {secretKey: string;+ secretPath: string;environments: { name: string; slug: string }[];expandableColWidth: number;getSecretByKey: (slug: string, key: string) => DecryptedSecret | undefined;@@ -29,6 +30,7 @@ type Props = {export const SecretOverviewTableRow = ({secretKey,environments = [],+ secretPath,getSecretByKey,onSecretUpdate,onSecretCreate,@@ -73,9 +75,11 @@ export const SecretOverviewTableRow = ({><div className="h-full w-full border-r border-mineshaft-600 py-[0.85rem] px-5"><div className="flex justify-center">- {!isSecretEmpty && <Tooltip content={isSecretPresent ? "Present secret" : "Missing secret"}>- <FontAwesomeIcon icon={isSecretPresent ? faCheck : faXmark} />- </Tooltip>}+ {!isSecretEmpty && (+ <Tooltip content={isSecretPresent ? "Present secret" : "Missing secret"}>+ <FontAwesomeIcon icon={isSecretPresent ? faCheck : faXmark} />+ </Tooltip>+ )}{isSecretEmpty && (<Tooltip content="Empty value"><FontAwesomeIcon icon={faCircle} />@@ -141,6 +145,7 @@ export const SecretOverviewTableRow = ({</td><td className="col-span-2 h-8 w-full"><SecretEditRow+ secretPath={secretPath}isVisible={isSecretVisible}secretName={secretKey}defaultValue={secret?.value}diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsSection.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsSection.tsxindex cf8efdc0c3..9ef12bf138 100644--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsSection.tsx+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgIncidentContactsSection/OrgIncidentContactsSection.tsx@@ -2,53 +2,49 @@ import { useTranslation } from "react-i18next";import { faPlus } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { OrgPermissionCan } from "@app/components/permissions";+import { OrgPermissionCan, PermissionDeniedBanner } from "@app/components/permissions";import { Button } from "@app/components/v2";-import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context";-import { withPermission } from "@app/hoc";+import { OrgPermissionActions, OrgPermissionSubjects, useOrgPermission } from "@app/context";import { usePopUp } from "@app/hooks";import { AddOrgIncidentContactModal } from "./AddOrgIncidentContactModal";import { OrgIncidentContactsTable } from "./OrgIncidentContactsTable";-export const OrgIncidentContactsSection = withPermission(- () => {- const { t } = useTranslation();- const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([- "addContact"- ] as const);+export const OrgIncidentContactsSection = () => {+ const { t } = useTranslation();+ const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([+ "addContact"+ ] as const);+ const permission = useOrgPermission();- return (- <div className="p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">- <div className="flex justify-between mb-4">- <p className="min-w-max text-xl font-semibold">- {t("section.incident.incident-contacts")}- </p>- <OrgPermissionCan- I={OrgPermissionActions.Create}- a={OrgPermissionSubjects.IncidentAccount}- >- {(isAllowed) => (- <Button- colorSchema="secondary"- type="submit"- isDisabled={!isAllowed}- leftIcon={<FontAwesomeIcon icon={faPlus} />}- onClick={() => handlePopUpOpen("addContact")}- >- Add contact- </Button>- )}- </OrgPermissionCan>- </div>- <OrgIncidentContactsTable />- <AddOrgIncidentContactModal- popUp={popUp}- handlePopUpClose={handlePopUpClose}- handlePopUpToggle={handlePopUpToggle}- />+ return (+ <div className="p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">+ <div className="flex justify-between mb-4">+ <p className="min-w-max text-xl font-semibold">{t("section.incident.incident-contacts")}</p>+ <OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.IncidentAccount}>+ {(isAllowed) => (+ <Button+ colorSchema="secondary"+ type="submit"+ isDisabled={!isAllowed}+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ onClick={() => handlePopUpOpen("addContact")}+ >+ Add contact+ </Button>+ )}+ </OrgPermissionCan></div>- );- },- { action: OrgPermissionActions.Read, subject: OrgPermissionSubjects.IncidentAccount }-);+ {permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.IncidentAccount) ? (+ <OrgIncidentContactsTable />+ ) : (+ <PermissionDeniedBanner />+ )}+ <AddOrgIncidentContactModal+ popUp={popUp}+ handlePopUpClose={handlePopUpClose}+ handlePopUpToggle={handlePopUpToggle}+ />+ </div>+ );+};diff --git a/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx b/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsxindex 9158091425..f202712109 100644--- a/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx+++ b/frontend/src/views/Settings/OrgSettingsPage/components/OrgNameChangeSection/OrgNameChangeSection.tsx@@ -7,7 +7,6 @@ import { useNotificationContext } from "@app/components/context/Notifications/Noimport { OrgPermissionCan } from "@app/components/permissions";import { Button, FormControl, Input } from "@app/components/v2";import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";-import { withPermission } from "@app/hoc";import { useRenameOrg } from "@app/hooks/api";const formSchema = yup.object({@@ -16,77 +15,70 @@ const formSchema = yup.object({type FormData = yup.InferType<typeof formSchema>;-export const OrgNameChangeSection = withPermission(- (): JSX.Element => {- const { currentOrg } = useOrganization();- const { createNotification } = useNotificationContext();- const { handleSubmit, control, reset } = useForm<FormData>({- resolver: yupResolver(formSchema)- });- const { mutateAsync, isLoading } = useRenameOrg();+export const OrgNameChangeSection = (): JSX.Element => {+ const { currentOrg } = useOrganization();+ const { createNotification } = useNotificationContext();+ const { handleSubmit, control, reset } = useForm<FormData>({+ resolver: yupResolver(formSchema)+ });+ const { mutateAsync, isLoading } = useRenameOrg();- useEffect(() => {- if (currentOrg) {- reset({ name: currentOrg.name });- }- }, [currentOrg]);+ useEffect(() => {+ if (currentOrg) {+ reset({ name: currentOrg.name });+ }+ }, [currentOrg]);- const onFormSubmit = async ({ name }: FormData) => {- try {- if (!currentOrg?._id) return;- if (name === "") return;+ const onFormSubmit = async ({ name }: FormData) => {+ try {+ if (!currentOrg?._id) return;+ if (name === "") return;- await mutateAsync({ orgId: currentOrg?._id, newOrgName: name });- createNotification({- text: "Successfully renamed organization",- type: "success"- });- } catch (error) {- console.error(error);- createNotification({- text: "Failed to rename organization",- type: "error"- });- }- };+ await mutateAsync({ orgId: currentOrg?._id, newOrgName: name });+ createNotification({+ text: "Successfully renamed organization",+ type: "success"+ });+ } catch (error) {+ console.error(error);+ createNotification({+ text: "Failed to rename organization",+ type: "error"+ });+ }+ };- return (- <form- onSubmit={handleSubmit(onFormSubmit)}- className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600"- >- <p className="text-xl font-semibold text-mineshaft-100 mb-4">Organization name</p>- <div className="mb-2 max-w-md">- <Controller- defaultValue=""- render={({ field, fieldState: { error } }) => (- <FormControl isError={Boolean(error)} errorText={error?.message}>- <Input placeholder="Acme Corp" {...field} />- </FormControl>- )}- control={control}- name="name"- />- </div>- <OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Settings}>- {(isAllowed) => (- <Button- isLoading={isLoading}- isDisabled={!isAllowed}- colorSchema="primary"- variant="outline_bg"- type="submit"- >- Save- </Button>+ return (+ <form+ onSubmit={handleSubmit(onFormSubmit)}+ className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600"+ >+ <p className="text-xl font-semibold text-mineshaft-100 mb-4">Organization name</p>+ <div className="mb-2 max-w-md">+ <Controller+ defaultValue=""+ render={({ field, fieldState: { error } }) => (+ <FormControl isError={Boolean(error)} errorText={error?.message}>+ <Input placeholder="Acme Corp" {...field} />+ </FormControl>)}- </OrgPermissionCan>- </form>- );- },- {- action: OrgPermissionActions.Read,- subject: OrgPermissionSubjects.Settings,- containerClassName: "mb-4"- }-);+ control={control}+ name="name"+ />+ </div>+ <OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Settings}>+ {(isAllowed) => (+ <Button+ isLoading={isLoading}+ isDisabled={!isAllowed}+ colorSchema="primary"+ variant="outline_bg"+ type="submit"+ >+ Save+ </Button>+ )}+ </OrgPermissionCan>+ </form>+ );+};diff --git a/frontend/src/views/Settings/ProjectSettingsPage/ProjectSettingsPage.tsx b/frontend/src/views/Settings/ProjectSettingsPage/ProjectSettingsPage.tsxindex 864d906a89..b70760d7f3 100644--- a/frontend/src/views/Settings/ProjectSettingsPage/ProjectSettingsPage.tsx+++ b/frontend/src/views/Settings/ProjectSettingsPage/ProjectSettingsPage.tsx@@ -3,8 +3,6 @@ import { useTranslation } from "react-i18next";import { Tab } from "@headlessui/react";import NavHeader from "@app/components/navigation/NavHeader";-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";-import { withProjectPermission } from "@app/hoc";import { ProjectGeneralTab } from "./components/ProjectGeneralTab";import { ProjectServiceTokensTab } from "./components/ProjectServiceTokensTab";@@ -16,50 +14,47 @@ const tabs = [{ name: "Webhooks", key: "tab-project-webhooks" }];-export const ProjectSettingsPage = withProjectPermission(- () => {- const { t } = useTranslation();- return (- <div className="flex w-full justify-center bg-bunker-800 px-6 text-white">- <div className="w-full max-w-screen-lg">- <div className="relative right-5 ml-4">- <NavHeader pageName={t("settings.project.title")} isProjectRelated />- </div>- <div className="my-8">- <p className="text-3xl font-semibold text-gray-200">{t("settings.project.title")}</p>- </div>- <Tab.Group>- <Tab.List className="mb-4 w-full border-b-2 border-mineshaft-800">- {tabs.map((tab) => (- <Tab as={Fragment} key={tab.key}>- {({ selected }) => (- <button- type="button"- className={`w-30 py-2 mx-2 mr-4 font-medium text-sm outline-none ${- selected ? "border-b border-white text-white" : "text-mineshaft-400"- }`}- >- {tab.name}- </button>- )}- </Tab>- ))}- </Tab.List>- <Tab.Panels>- <Tab.Panel>- <ProjectGeneralTab />- </Tab.Panel>- <Tab.Panel>- <ProjectServiceTokensTab />- </Tab.Panel>- <Tab.Panel>- <WebhooksTab />- </Tab.Panel>- </Tab.Panels>- </Tab.Group>+export const ProjectSettingsPage = () => {+ const { t } = useTranslation();+ return (+ <div className="flex w-full justify-center bg-bunker-800 px-6 text-white">+ <div className="w-full max-w-screen-lg">+ <div className="relative right-5 ml-4">+ <NavHeader pageName={t("settings.project.title")} isProjectRelated /></div>+ <div className="my-8">+ <p className="text-3xl font-semibold text-gray-200">{t("settings.project.title")}</p>+ </div>+ <Tab.Group>+ <Tab.List className="mb-4 w-full border-b-2 border-mineshaft-800">+ {tabs.map((tab) => (+ <Tab as={Fragment} key={tab.key}>+ {({ selected }) => (+ <button+ type="button"+ className={`w-30 py-2 mx-2 mr-4 font-medium text-sm outline-none ${+ selected ? "border-b border-white text-white" : "text-mineshaft-400"+ }`}+ >+ {tab.name}+ </button>+ )}+ </Tab>+ ))}+ </Tab.List>+ <Tab.Panels>+ <Tab.Panel>+ <ProjectGeneralTab />+ </Tab.Panel>+ <Tab.Panel>+ <ProjectServiceTokensTab />+ </Tab.Panel>+ <Tab.Panel>+ <WebhooksTab />+ </Tab.Panel>+ </Tab.Panels>+ </Tab.Group></div>- );- },- { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Settings }-);+ </div>+ );+};diff --git a/frontend/src/views/Settings/ProjectSettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx b/frontend/src/views/Settings/ProjectSettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsxindex c0cb0e4746..58e345a120 100644--- a/frontend/src/views/Settings/ProjectSettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx+++ b/frontend/src/views/Settings/ProjectSettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx@@ -4,61 +4,57 @@ import { useNotificationContext } from "@app/components/context/Notifications/Noimport { ProjectPermissionCan } from "@app/components/permissions";import { Checkbox } from "@app/components/v2";import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";-import { withProjectPermission } from "@app/hoc";import { useToggleAutoCapitalization } from "@app/hooks/api";-export const AutoCapitalizationSection = withProjectPermission(- () => {- const { t } = useTranslation();- const { createNotification } = useNotificationContext();- const { currentWorkspace } = useWorkspace();- const { mutateAsync } = useToggleAutoCapitalization();+export const AutoCapitalizationSection = () => {+ const { t } = useTranslation();+ const { createNotification } = useNotificationContext();+ const { currentWorkspace } = useWorkspace();+ const { mutateAsync } = useToggleAutoCapitalization();- const handleToggleCapitalizationToggle = async (state: boolean) => {- try {- if (!currentWorkspace?._id) return;+ const handleToggleCapitalizationToggle = async (state: boolean) => {+ try {+ if (!currentWorkspace?._id) return;- await mutateAsync({- workspaceID: currentWorkspace._id,- state- });+ await mutateAsync({+ workspaceID: currentWorkspace._id,+ state+ });- const text = `Successfully ${state ? "enabled" : "disabled"} auto capitalization`;- createNotification({- text,- type: "success"- });- } catch (err) {- console.error(err);- createNotification({- text: "Failed to update auto capitalization",- type: "error"- });- }- };+ const text = `Successfully ${state ? "enabled" : "disabled"} auto capitalization`;+ createNotification({+ text,+ type: "success"+ });+ } catch (err) {+ console.error(err);+ createNotification({+ text: "Failed to update auto capitalization",+ type: "error"+ });+ }+ };- return (- <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">- <p className="mb-3 text-xl font-semibold">{t("settings.project.auto-capitalization")}</p>- <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>- {(isAllowed) => (- <div className="w-max">- <Checkbox- className="data-[state=checked]:bg-primary"- id="autoCapitalization"- isDisabled={!isAllowed}- isChecked={currentWorkspace?.autoCapitalization ?? false}- onCheckedChange={(state) => {- handleToggleCapitalizationToggle(state as boolean);- }}- >- {t("settings.project.auto-capitalization-description")}- </Checkbox>- </div>- )}- </ProjectPermissionCan>- </div>- );- },- { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Settings }-);+ return (+ <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">+ <p className="mb-3 text-xl font-semibold">{t("settings.project.auto-capitalization")}</p>+ <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>+ {(isAllowed) => (+ <div className="w-max">+ <Checkbox+ className="data-[state=checked]:bg-primary"+ id="autoCapitalization"+ isDisabled={!isAllowed}+ isChecked={currentWorkspace?.autoCapitalization ?? false}+ onCheckedChange={(state) => {+ handleToggleCapitalizationToggle(state as boolean);+ }}+ >+ {t("settings.project.auto-capitalization-description")}+ </Checkbox>+ </div>+ )}+ </ProjectPermissionCan>+ </div>+ );+};diff --git a/frontend/src/views/Settings/ProjectSettingsPage/components/E2EESection/E2EESection.tsx b/frontend/src/views/Settings/ProjectSettingsPage/components/E2EESection/E2EESection.tsxindex 24091b4450..11e6128e77 100644--- a/frontend/src/views/Settings/ProjectSettingsPage/components/E2EESection/E2EESection.tsx+++ b/frontend/src/views/Settings/ProjectSettingsPage/components/E2EESection/E2EESection.tsx@@ -5,113 +5,106 @@ import {} from "@app/components/utilities/cryptography/crypto";import { Checkbox } from "@app/components/v2";import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";-import { withProjectPermission } from "@app/hoc";import { useGetUserWsKey, useGetWorkspaceBot, useUpdateBotActiveStatus } from "@app/hooks/api";-export const E2EESection = withProjectPermission(- () => {- const { currentWorkspace } = useWorkspace();- const { data: bot } = useGetWorkspaceBot(currentWorkspace?._id ?? "");- const { mutateAsync: updateBotActiveStatus } = useUpdateBotActiveStatus();- const { data: wsKey } = useGetUserWsKey(currentWorkspace?._id ?? "");+export const E2EESection = () => {+ const { currentWorkspace } = useWorkspace();+ const { data: bot } = useGetWorkspaceBot(currentWorkspace?._id ?? "");+ const { mutateAsync: updateBotActiveStatus } = useUpdateBotActiveStatus();+ const { data: wsKey } = useGetUserWsKey(currentWorkspace?._id ?? "");- /**- * Activate bot for project by performing the following steps:- * 1. Get the (encrypted) project key- * 2. Decrypt project key with user's private key- * 3. Encrypt project key with bot's public key- * 4. Send encrypted project key to backend and set bot status to active- */- const toggleBotActivate = async () => {- let botKey;- try {- if (!currentWorkspace?._id) return;+ /**+ * Activate bot for project by performing the following steps:+ * 1. Get the (encrypted) project key+ * 2. Decrypt project key with user's private key+ * 3. Encrypt project key with bot's public key+ * 4. Send encrypted project key to backend and set bot status to active+ */+ const toggleBotActivate = async () => {+ let botKey;+ try {+ if (!currentWorkspace?._id) return;- if (bot && wsKey) {- // case: there is a bot+ if (bot && wsKey) {+ // case: there is a bot- if (!bot.isActive) {- // bot is not active -> activate bot+ if (!bot.isActive) {+ // bot is not active -> activate bot- const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY");+ const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY");- if (!PRIVATE_KEY) {- throw new Error("Private Key missing");- }+ if (!PRIVATE_KEY) {+ throw new Error("Private Key missing");+ }- const WORKSPACE_KEY = decryptAssymmetric({- ciphertext: wsKey.encryptedKey,- nonce: wsKey.nonce,- publicKey: wsKey.sender.publicKey,- privateKey: PRIVATE_KEY- });+ const WORKSPACE_KEY = decryptAssymmetric({+ ciphertext: wsKey.encryptedKey,+ nonce: wsKey.nonce,+ publicKey: wsKey.sender.publicKey,+ privateKey: PRIVATE_KEY+ });- const { ciphertext, nonce } = encryptAssymmetric({- plaintext: WORKSPACE_KEY,- publicKey: bot.publicKey,- privateKey: PRIVATE_KEY- });+ const { ciphertext, nonce } = encryptAssymmetric({+ plaintext: WORKSPACE_KEY,+ publicKey: bot.publicKey,+ privateKey: PRIVATE_KEY+ });- botKey = {- encryptedKey: ciphertext,- nonce- };+ botKey = {+ encryptedKey: ciphertext,+ nonce+ };- await updateBotActiveStatus({- workspaceId: currentWorkspace._id,- botKey,- isActive: true,- botId: bot._id- });- } else {- // bot is active -> deactivate bot- await updateBotActiveStatus({- isActive: false,- botId: bot._id,- workspaceId: currentWorkspace._id- });- }+ await updateBotActiveStatus({+ workspaceId: currentWorkspace._id,+ botKey,+ isActive: true,+ botId: bot._id+ });+ } else {+ // bot is active -> deactivate bot+ await updateBotActiveStatus({+ isActive: false,+ botId: bot._id,+ workspaceId: currentWorkspace._id+ });}- } catch (err) {- console.error(err);}- };+ } catch (err) {+ console.error(err);+ }+ };- return bot ? (- <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">- <p className="mb-3 text-xl font-semibold">End-to-End Encryption</p>- <p className="text-gray-400 mb-8">- Disabling, end-to-end encryption (E2EE) unlocks capabilities like native integrations to- cloud providers as well as HTTP calls to get secrets back raw but enables the server to- read/decrypt your secret values.- </p>- <p className="text-gray-400 mb-8">- Note that, even with E2EE disabled, your secrets are always encrypted at rest.- </p>- <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>- {(isAllowed) => (- <div className="w-max">- <Checkbox- className="data-[state=checked]:bg-primary"- id="autoCapitalization"- isChecked={!bot.isActive}- isDisabled={!isAllowed}- onCheckedChange={async () => {- await toggleBotActivate();- }}- >- End-to-end encryption enabled- </Checkbox>- </div>- )}- </ProjectPermissionCan>- </div>- ) : (- <div />- );- },- {- action: ProjectPermissionActions.Read,- subject: ProjectPermissionSub.Settings- }-);+ return bot ? (+ <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">+ <p className="mb-3 text-xl font-semibold">End-to-End Encryption</p>+ <p className="text-gray-400 mb-8">+ Disabling, end-to-end encryption (E2EE) unlocks capabilities like native integrations to+ cloud providers as well as HTTP calls to get secrets back raw but enables the server to+ read/decrypt your secret values.+ </p>+ <p className="text-gray-400 mb-8">+ Note that, even with E2EE disabled, your secrets are always encrypted at rest.+ </p>+ <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>+ {(isAllowed) => (+ <div className="w-max">+ <Checkbox+ className="data-[state=checked]:bg-primary"+ id="autoCapitalization"+ isChecked={!bot.isActive}+ isDisabled={!isAllowed}+ onCheckedChange={async () => {+ await toggleBotActivate();+ }}+ >+ End-to-end encryption enabled+ </Checkbox>+ </div>+ )}+ </ProjectPermissionCan>+ </div>+ ) : (+ <div />+ );+};diff --git a/frontend/src/views/Settings/ProjectSettingsPage/components/EnvironmentSection/EnvironmentSection.tsx b/frontend/src/views/Settings/ProjectSettingsPage/components/EnvironmentSection/EnvironmentSection.tsxindex 229fc9b5f8..1676ce62b1 100644--- a/frontend/src/views/Settings/ProjectSettingsPage/components/EnvironmentSection/EnvironmentSection.tsx+++ b/frontend/src/views/Settings/ProjectSettingsPage/components/EnvironmentSection/EnvironmentSection.tsx@@ -2,15 +2,15 @@ import { faPlus } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";-import { ProjectPermissionCan } from "@app/components/permissions";+import { PermissionDeniedBanner, ProjectPermissionCan } from "@app/components/permissions";import { Button, DeleteActionModal, UpgradePlanModal } from "@app/components/v2";import {ProjectPermissionActions,ProjectPermissionSub,+ useProjectPermission,useSubscription,useWorkspace} from "@app/context";-import { withProjectPermission } from "@app/hoc";import { useDeleteWsEnvironment } from "@app/hooks/api";import { usePopUp } from "@app/hooks/usePopUp";@@ -18,111 +18,113 @@ import { AddEnvironmentModal } from "./AddEnvironmentModal";import { EnvironmentTable } from "./EnvironmentTable";import { UpdateEnvironmentModal } from "./UpdateEnvironmentModal";-export const EnvironmentSection = withProjectPermission(- () => {- const { createNotification } = useNotificationContext();- const { subscription } = useSubscription();- const { currentWorkspace } = useWorkspace();+export const EnvironmentSection = () => {+ const { createNotification } = useNotificationContext();+ const { subscription } = useSubscription();+ const { currentWorkspace } = useWorkspace();+ const permision = useProjectPermission();- const deleteWsEnvironment = useDeleteWsEnvironment();+ const deleteWsEnvironment = useDeleteWsEnvironment();- const isMoreEnvironmentsAllowed =- subscription?.environmentLimit && currentWorkspace?.environments- ? currentWorkspace.environments.length < subscription.environmentLimit- : true;+ const isMoreEnvironmentsAllowed =+ subscription?.environmentLimit && currentWorkspace?.environments+ ? currentWorkspace.environments.length < subscription.environmentLimit+ : true;- const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([- "createEnv",- "updateEnv",- "deleteEnv",- "upgradePlan"- ] as const);+ const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([+ "createEnv",+ "updateEnv",+ "deleteEnv",+ "upgradePlan"+ ] as const);- const onEnvDeleteSubmit = async (environmentSlug: string) => {- try {- if (!currentWorkspace?._id) return;+ const onEnvDeleteSubmit = async (environmentSlug: string) => {+ try {+ if (!currentWorkspace?._id) return;- await deleteWsEnvironment.mutateAsync({- workspaceID: currentWorkspace._id,- environmentSlug- });+ await deleteWsEnvironment.mutateAsync({+ workspaceID: currentWorkspace._id,+ environmentSlug+ });- createNotification({- text: "Successfully deleted environment",- type: "success"- });+ createNotification({+ text: "Successfully deleted environment",+ type: "success"+ });- handlePopUpClose("deleteEnv");- } catch (err) {- console.error(err);- createNotification({- text: "Failed to delete environment",- type: "error"- });- }- };+ handlePopUpClose("deleteEnv");+ } catch (err) {+ console.error(err);+ createNotification({+ text: "Failed to delete environment",+ type: "error"+ });+ }+ };- return (- <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">- <div className="flex justify-between mb-8">- <p className="text-xl font-semibold text-mineshaft-100">Environments</p>- <div>- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Environments}- >- {(isAllowed) => (- <Button- colorSchema="secondary"- leftIcon={<FontAwesomeIcon icon={faPlus} />}- onClick={() => {- if (isMoreEnvironmentsAllowed) {- handlePopUpOpen("createEnv");- } else {- handlePopUpOpen("upgradePlan");- }- }}- isDisabled={!isAllowed}- >- Create environment- </Button>- )}- </ProjectPermissionCan>- </div>+ return (+ <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">+ <div className="flex justify-between mb-8">+ <p className="text-xl font-semibold text-mineshaft-100">Environments</p>+ <div>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Create}+ a={ProjectPermissionSub.Environments}+ >+ {(isAllowed) => (+ <Button+ colorSchema="secondary"+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ onClick={() => {+ if (isMoreEnvironmentsAllowed) {+ handlePopUpOpen("createEnv");+ } else {+ handlePopUpOpen("upgradePlan");+ }+ }}+ isDisabled={!isAllowed}+ >+ Create environment+ </Button>+ )}+ </ProjectPermissionCan></div>- <p className="text-gray-400 mb-8">- Choose which environments will show up in your dashboard like development, staging,- production- </p>- <EnvironmentTable handlePopUpOpen={handlePopUpOpen} />- <AddEnvironmentModal- popUp={popUp}- handlePopUpClose={handlePopUpClose}- handlePopUpToggle={handlePopUpToggle}- />- <UpdateEnvironmentModal- popUp={popUp}- handlePopUpClose={handlePopUpClose}- handlePopUpToggle={handlePopUpToggle}- />- <DeleteActionModal- isOpen={popUp.deleteEnv.isOpen}- title={`Are you sure want to delete ${- (popUp?.deleteEnv?.data as { name: string })?.name || " "- }?`}- onChange={(isOpen) => handlePopUpToggle("deleteEnv", isOpen)}- deleteKey={(popUp?.deleteEnv?.data as { slug: string })?.slug || ""}- onDeleteApproved={() =>- onEnvDeleteSubmit((popUp?.deleteEnv?.data as { slug: string })?.slug)- }- />- <UpgradePlanModal- isOpen={popUp.upgradePlan.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}- text="You can add custom environments if you switch to Infisical's Team plan."- /></div>- );- },- { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Environments }-);+ <p className="text-gray-400 mb-8">+ Choose which environments will show up in your dashboard like development, staging,+ production+ </p>+ {permision.can(ProjectPermissionActions.Read, ProjectPermissionSub.Environments) ? (+ <EnvironmentTable handlePopUpOpen={handlePopUpOpen} />+ ) : (+ <PermissionDeniedBanner />+ )}+ <AddEnvironmentModal+ popUp={popUp}+ handlePopUpClose={handlePopUpClose}+ handlePopUpToggle={handlePopUpToggle}+ />+ <UpdateEnvironmentModal+ popUp={popUp}+ handlePopUpClose={handlePopUpClose}+ handlePopUpToggle={handlePopUpToggle}+ />+ <DeleteActionModal+ isOpen={popUp.deleteEnv.isOpen}+ title={`Are you sure want to delete ${+ (popUp?.deleteEnv?.data as { name: string })?.name || " "+ }?`}+ onChange={(isOpen) => handlePopUpToggle("deleteEnv", isOpen)}+ deleteKey={(popUp?.deleteEnv?.data as { slug: string })?.slug || ""}+ onDeleteApproved={() =>+ onEnvDeleteSubmit((popUp?.deleteEnv?.data as { slug: string })?.slug)+ }+ />+ <UpgradePlanModal+ isOpen={popUp.upgradePlan.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}+ text="You can add custom environments if you switch to Infisical's Team plan."+ />+ </div>+ );+};diff --git a/frontend/src/views/Settings/ProjectSettingsPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx b/frontend/src/views/Settings/ProjectSettingsPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsxindex c9a7ea360e..ca2e14eb95 100644--- a/frontend/src/views/Settings/ProjectSettingsPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx+++ b/frontend/src/views/Settings/ProjectSettingsPage/components/ProjectIndexSecretsSection/ProjectIndexSecretsSection.tsx@@ -5,7 +5,6 @@ import {} from "@app/components/utilities/cryptography/crypto";import { Button } from "@app/components/v2";import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";-import { withProjectPermission } from "@app/hoc";import {useGetUserWsKey,useGetWorkspaceIndexStatus,@@ -16,73 +15,70 @@ import {// TODO: add check so that this only shows up if user is// an admin in the workspace-export const ProjectIndexSecretsSection = withProjectPermission(- () => {- const { currentWorkspace } = useWorkspace();- const { data: isBlindIndexed, isLoading: isBlindIndexedLoading } = useGetWorkspaceIndexStatus(- currentWorkspace?._id ?? ""- );- const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?._id ?? "");- const { data: encryptedSecrets } = useGetWorkspaceSecrets(currentWorkspace?._id ?? "");- const nameWorkspaceSecrets = useNameWorkspaceSecrets();+export const ProjectIndexSecretsSection = () => {+ const { currentWorkspace } = useWorkspace();+ const { data: isBlindIndexed, isLoading: isBlindIndexedLoading } = useGetWorkspaceIndexStatus(+ currentWorkspace?._id ?? ""+ );+ const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?._id ?? "");+ const { data: encryptedSecrets } = useGetWorkspaceSecrets(currentWorkspace?._id ?? "");+ const nameWorkspaceSecrets = useNameWorkspaceSecrets();- const onEnableBlindIndices = async () => {- if (!currentWorkspace?._id) return;- if (!encryptedSecrets) return;- if (!latestFileKey) return;+ const onEnableBlindIndices = async () => {+ if (!currentWorkspace?._id) return;+ if (!encryptedSecrets) return;+ if (!latestFileKey) return;- const key = decryptAssymmetric({- ciphertext: latestFileKey.encryptedKey,- nonce: latestFileKey.nonce,- publicKey: latestFileKey.sender.publicKey,- privateKey: localStorage.getItem("PRIVATE_KEY") as string- });-- const secretsToUpdate = encryptedSecrets.map((encryptedSecret) => {- const secretName = decryptSymmetric({- ciphertext: encryptedSecret.secretKeyCiphertext,- iv: encryptedSecret.secretKeyIV,- tag: encryptedSecret.secretKeyTag,- key- });+ const key = decryptAssymmetric({+ ciphertext: latestFileKey.encryptedKey,+ nonce: latestFileKey.nonce,+ publicKey: latestFileKey.sender.publicKey,+ privateKey: localStorage.getItem("PRIVATE_KEY") as string+ });- return {- secretName,- _id: encryptedSecret._id- };+ const secretsToUpdate = encryptedSecrets.map((encryptedSecret) => {+ const secretName = decryptSymmetric({+ ciphertext: encryptedSecret.secretKeyCiphertext,+ iv: encryptedSecret.secretKeyIV,+ tag: encryptedSecret.secretKeyTag,+ key});- await nameWorkspaceSecrets.mutateAsync({- workspaceId: currentWorkspace._id,- secretsToUpdate- });- };+ return {+ secretName,+ _id: encryptedSecret._id+ };+ });++ await nameWorkspaceSecrets.mutateAsync({+ workspaceId: currentWorkspace._id,+ secretsToUpdate+ });+ };- return !isBlindIndexedLoading && !isBlindIndexed ? (- <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">- <p className="mb-3 text-xl font-semibold">Blind Indices</p>- <p className="text-gray-400 mb-8">- Your project, created before the introduction of blind indexing, contains unindexed- secrets. To access individual secrets by name through the SDK and public API, please- enable blind indexing.- </p>- <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>- {(isAllowed) => (- <Button- onClick={onEnableBlindIndices}- isDisabled={!isAllowed}- color="mineshaft"- size="sm"- type="submit"- >- Enable Blind Indexing- </Button>- )}- </ProjectPermissionCan>- </div>- ) : (- <div />- );- },- { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Settings }-);+ return !isBlindIndexedLoading && !isBlindIndexed ? (+ <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">+ <p className="mb-3 text-xl font-semibold">Blind Indices</p>+ <p className="text-gray-400 mb-8">+ Your project, created before the introduction of blind indexing, contains unindexed secrets.+ To access individual secrets by name through the SDK and public API, please enable blind+ indexing.+ </p>+ <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>+ {(isAllowed) => (+ <Button+ onClick={onEnableBlindIndices}+ isDisabled={!isAllowed}+ color="mineshaft"+ size="sm"+ type="submit"+ >+ Enable Blind Indexing+ </Button>+ )}+ </ProjectPermissionCan>+ </div>+ ) : (+ <div />+ );+};diff --git a/frontend/src/views/Settings/ProjectSettingsPage/components/SecretTagsSection/SecretTagsSection.tsx b/frontend/src/views/Settings/ProjectSettingsPage/components/SecretTagsSection/SecretTagsSection.tsxindex 6dc8949263..fb5b2c7bba 100644--- a/frontend/src/views/Settings/ProjectSettingsPage/components/SecretTagsSection/SecretTagsSection.tsx+++ b/frontend/src/views/Settings/ProjectSettingsPage/components/SecretTagsSection/SecretTagsSection.tsx@@ -2,10 +2,9 @@ import { faPlus } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";-import { ProjectPermissionCan } from "@app/components/permissions";+import { PermissionDeniedBanner, ProjectPermissionCan } from "@app/components/permissions";import { Button, DeleteActionModal } from "@app/components/v2";-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";-import { withProjectPermission } from "@app/hoc";+import { ProjectPermissionActions, ProjectPermissionSub, useProjectPermission } from "@app/context";import { usePopUp } from "@app/hooks";import { useDeleteWsTag } from "@app/hooks/api";@@ -14,80 +13,82 @@ import { SecretTagsTable } from "./SecretTagsTable";type DeleteModalData = { name: string; id: string };-export const SecretTagsSection = withProjectPermission(- (): JSX.Element => {- const { createNotification } = useNotificationContext();- const { popUp, handlePopUpToggle, handlePopUpClose, handlePopUpOpen } = usePopUp([- "CreateSecretTag",- "deleteTagConfirmation"- ] as const);+export const SecretTagsSection = (): JSX.Element => {+ const { createNotification } = useNotificationContext();+ const { popUp, handlePopUpToggle, handlePopUpClose, handlePopUpOpen } = usePopUp([+ "CreateSecretTag",+ "deleteTagConfirmation"+ ] as const);+ const permission = useProjectPermission();- const deleteWsTag = useDeleteWsTag();+ const deleteWsTag = useDeleteWsTag();- const onDeleteApproved = async () => {- try {- await deleteWsTag.mutateAsync({- tagID: (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.id- });+ const onDeleteApproved = async () => {+ try {+ await deleteWsTag.mutateAsync({+ tagID: (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.id+ });- createNotification({- text: "Successfully deleted tag",- type: "success"- });+ createNotification({+ text: "Successfully deleted tag",+ type: "success"+ });- handlePopUpClose("deleteTagConfirmation");- } catch (err) {- console.error(err);- createNotification({- text: "Failed to delete the tag",- type: "error"- });- }- };+ handlePopUpClose("deleteTagConfirmation");+ } catch (err) {+ console.error(err);+ createNotification({+ text: "Failed to delete the tag",+ type: "error"+ });+ }+ };- return (- <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">- <div className="flex justify-between mb-8">- <p className="mb-3 text-xl font-semibold">Secret Tags</p>- <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Tags}>- {(isAllowed) => (- <Button- colorSchema="secondary"- leftIcon={<FontAwesomeIcon icon={faPlus} />}- onClick={() => {- console.log("x");- handlePopUpOpen("CreateSecretTag");- console.log("x2");- }}- isDisabled={!isAllowed}- >- Create tag- </Button>- )}- </ProjectPermissionCan>- </div>- <p className="text-gray-400 mb-8">- Every secret can be assigned to one or more tags. Here you can add and remove tags for the- current project.- </p>- <SecretTagsTable handlePopUpOpen={handlePopUpOpen} />- <AddSecretTagModal- popUp={popUp}- handlePopUpClose={handlePopUpClose}- handlePopUpToggle={handlePopUpToggle}- />- <DeleteActionModal- isOpen={popUp.deleteTagConfirmation.isOpen}- title={`Delete ${- (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.name || " "- } api key?`}- onChange={(isOpen) => handlePopUpToggle("deleteTagConfirmation", isOpen)}- deleteKey={(popUp?.deleteTagConfirmation?.data as DeleteModalData)?.name}- onClose={() => handlePopUpClose("deleteTagConfirmation")}- onDeleteApproved={onDeleteApproved}- />+ return (+ <div className="mb-6 p-4 bg-mineshaft-900 rounded-lg border border-mineshaft-600">+ <div className="flex justify-between mb-8">+ <p className="mb-3 text-xl font-semibold">Secret Tags</p>+ <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Tags}>+ {(isAllowed) => (+ <Button+ colorSchema="secondary"+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ onClick={() => {+ console.log("x");+ handlePopUpOpen("CreateSecretTag");+ console.log("x2");+ }}+ isDisabled={!isAllowed}+ >+ Create tag+ </Button>+ )}+ </ProjectPermissionCan></div>- );- },- { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Tags }-);+ <p className="text-gray-400 mb-8">+ Every secret can be assigned to one or more tags. Here you can add and remove tags for the+ current project.+ </p>+ {permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ? (+ <SecretTagsTable handlePopUpOpen={handlePopUpOpen} />+ ) : (+ <PermissionDeniedBanner />+ )}+ <AddSecretTagModal+ popUp={popUp}+ handlePopUpClose={handlePopUpClose}+ handlePopUpToggle={handlePopUpToggle}+ />+ <DeleteActionModal+ isOpen={popUp.deleteTagConfirmation.isOpen}+ title={`Delete ${+ (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.name || " "+ } api key?`}+ onChange={(isOpen) => handlePopUpToggle("deleteTagConfirmation", isOpen)}+ deleteKey={(popUp?.deleteTagConfirmation?.data as DeleteModalData)?.name}+ onClose={() => handlePopUpClose("deleteTagConfirmation")}+ onDeleteApproved={onDeleteApproved}+ />+ </div>+ );+};