Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
ui: add modal and modify environments table to show soft deleted environemnts
adilson2790efea3eee
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.tsindex 9997ff0c36..af368c735c 100644--- a/backend/src/server/routes/v1/project-router.ts+++ b/backend/src/server/routes/v1/project-router.ts@@ -52,7 +52,16 @@ import { sanitizedServiceTokenSchema } from "../v2/service-token-router";const projectWithEnv = SanitizedProjectSchema.merge(z.object({_id: z.string(),- environments: z.object({ name: z.string(), slug: z.string(), id: z.string() }).array()+ environments: z.object({ name: z.string(), slug: z.string(), id: z.string() }).array(),+ deletedEnvironments: z+ .object({+ id: z.string(),+ name: z.string(),+ slug: z.string(),+ expireAfter: z.date(),+ requestedSoftDeleteAt: z.date()+ })+ .array()}));diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex 905e383856..a48358b98d 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -454,6 +454,27 @@ export const projectDALFactory = (db: TDbClient) => {return project;};+ const findProjectDeletedEnvironments = async (projectId: string, tx?: Knex) => {+ try {+ const rows = await (tx || db.replicaNode())(TableName.Environment)+ .where({ projectId })+ .whereNotNull("expireAfter")+ .whereNotNull("requestedSoftDeleteAt")+ .select("id", "slug", "name", "expireAfter", "requestedSoftDeleteAt")+ .orderBy("position", "asc");++ return rows.map((row) => ({+ id: row.id,+ slug: row.slug,+ name: row.name,+ expireAfter: row.expireAfter as Date,+ requestedSoftDeleteAt: row.requestedSoftDeleteAt as Date+ }));+ } catch (error) {+ throw new DatabaseError({ error, name: "Find project deleted environments" });+ }+ };+const countOfOrgProjects = async (orgId: string | null, tx?: Knex) => {try {const subOrgProjects = db.replicaNode()(TableName.Organization).where({ rootOrgId: orgId }).select("id");@@ -484,6 +505,7 @@ export const projectDALFactory = (db: TDbClient) => {checkProjectUpgradeStatus,searchProjects,findProjectByEnvId,+ findProjectDeletedEnvironments,countOfOrgProjects};};diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex d6a5dea9c2..1a34219ca6 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -739,6 +739,13 @@ export const projectServiceFactory = ({return {...project,environments: envs,+ deletedEnvironments: [] as {+ id: string;+ name: string;+ slug: string;+ expireAfter: Date;+ requestedSoftDeleteAt: Date;+ }[],_id: project.id};});@@ -845,10 +852,20 @@ export const projectServiceFactory = ({};const getProjects = async ({ actorId, actor, includeRoles, actorAuthMethod, actorOrgId, type }: TListProjectsDTO) => {- const workspaces =+ const workspaces = (actor === ActorType.IDENTITY? await projectDAL.findIdentityProjects(actorId, actorOrgId, type)- : await projectDAL.findUserProjects(actorId, actorOrgId, type);+ : await projectDAL.findUserProjects(actorId, actorOrgId, type)+ ).map((workspace) => ({+ ...workspace,+ deletedEnvironments: [] as {+ id: string;+ name: string;+ slug: string;+ expireAfter: Date;+ requestedSoftDeleteAt: Date;+ }[]+ }));if (includeRoles) {const { permission } = await permissionService.getOrgPermission({@@ -900,7 +917,9 @@ export const projectServiceFactory = ({actionProjectType: ActionProjectType.Any});- return project;+ const deletedEnvironments = await projectDAL.findProjectDeletedEnvironments(project.id);++ return { ...project, deletedEnvironments };};const updateProject = async ({ actor, actorId, actorOrgId, actorAuthMethod, update, filter }: TUpdateProjectDTO) => {diff --git a/frontend/src/hooks/api/projects/index.tsx b/frontend/src/hooks/api/projects/index.tsxindex 9d97a99c4a..9fa59512d6 100644--- a/frontend/src/hooks/api/projects/index.tsx+++ b/frontend/src/hooks/api/projects/index.tsx@@ -37,6 +37,7 @@ export {useListWorkspaceSshCertificateTemplates,useListWorkspaceSshHostGroups,useListWorkspaceSshHosts,+ useRestoreWsEnvironment,useSearchProjects,useUpdateProject,useUpdateUserWorkspaceRole,diff --git a/frontend/src/hooks/api/projects/queries.tsx b/frontend/src/hooks/api/projects/queries.tsxindex 9d7731c1c8..aa1d1d968f 100644--- a/frontend/src/hooks/api/projects/queries.tsx+++ b/frontend/src/hooks/api/projects/queries.tsx@@ -33,6 +33,7 @@ import {Project,ProjectEnv,ProjectType,+ RestoreEnvironmentDTO,TGetIdentityPermissionAuditResponse,TGetMembershipPermissionAuditResponse,TGetUpgradeProjectStatusDTO,@@ -350,8 +351,25 @@ export const useDeleteWsEnvironment = () => {const queryClient = useQueryClient();return useMutation<object, object, DeleteEnvironmentDTO>({+ mutationFn: ({ id, projectId, hardDelete }) => {+ return apiRequest.delete(`/api/v1/projects/${projectId}/environments/${id}`, {+ params: hardDelete ? { hardDelete: true } : undefined+ });+ },+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: projectKeys.getAllUserProjects()+ });+ }+ });+};++export const useRestoreWsEnvironment = () => {+ const queryClient = useQueryClient();++ return useMutation<object, object, RestoreEnvironmentDTO>({mutationFn: ({ id, projectId }) => {- return apiRequest.delete(`/api/v1/projects/${projectId}/environments/${id}`);+ return apiRequest.post(`/api/v1/projects/${projectId}/environments/restore/${id}`);},onSuccess: () => {queryClient.invalidateQueries({diff --git a/frontend/src/hooks/api/projects/types.ts b/frontend/src/hooks/api/projects/types.tsindex beb52e9f9d..e7aa7f544d 100644--- a/frontend/src/hooks/api/projects/types.ts+++ b/frontend/src/hooks/api/projects/types.ts@@ -34,6 +34,7 @@ export type Project = {updatedAt: string;autoCapitalization: boolean;environments: ProjectEnv[];+ deletedEnvironments: ProjectDeletedEnv[];pitVersionLimit: number;auditLogsRetentionDays: number;slug: string;@@ -52,6 +53,11 @@ export type ProjectEnv = {slug: string;};+export type ProjectDeletedEnv = ProjectEnv & {+ expireAfter: string;+ requestedSoftDeleteAt: string;+};+export type ProjectTag = { id: string; name: string; slug: string };export type NameWorkspaceSecretsDTO = {@@ -121,7 +127,9 @@ export type UpdateEnvironmentDTO = {position?: number;};-export type DeleteEnvironmentDTO = { projectId: string; id: string };+export type DeleteEnvironmentDTO = { projectId: string; id: string; hardDelete?: boolean };++export type RestoreEnvironmentDTO = { projectId: string; id: string };export type TUpdateWorkspaceUserRoleDTO = {membershipId: string;diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsxindex 5a308de271..e0f3e215c3 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx@@ -1,5 +1,13 @@import { useState } from "react";-import { PlusIcon } from "lucide-react";+import { addDays, format } from "date-fns";+import {+ ClockIcon,+ KeyIcon,+ PlusIcon,+ RotateCcwIcon,+ Trash2Icon,+ TriangleAlertIcon+} from "lucide-react";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";import { createNotification } from "@app/components/notifications";@@ -13,6 +21,7 @@ import {AlertDialogFooter,AlertDialogHeader,AlertDialogTitle,+ Badge,Button,Card,CardAction,@@ -42,7 +51,7 @@ export const EnvironmentSection = () => {const { permission } = useProjectPermission();const deleteWsEnvironment = useDeleteWsEnvironment();- const [deleteConfirmation, setDeleteConfirmation] = useState("");+ const [hardDeleteConfirmation, setHardDeleteConfirmation] = useState("");const isMoreEnvironmentsAllowed =subscription?.environmentLimit && currentProject?.environments@@ -53,6 +62,7 @@ export const EnvironmentSection = () => {"createEnv","updateEnv","deleteEnv",+ "hardDeleteEnv","upgradePlan"] as const);@@ -60,6 +70,10 @@ export const EnvironmentSection = () => {| { name: string; slug: string; id: string }| undefined;+ const hardDeleteEnvData = popUp?.hardDeleteEnv?.data as+ | { name: string; slug: string; id: string; expireAfter?: string }+ | undefined;+const onEnvDeleteSubmit = async () => {if (!currentProject?.id || !deleteEnvData?.id) return;@@ -69,12 +83,35 @@ export const EnvironmentSection = () => {});createNotification({- text: "Successfully deleted environment",+ text: "Environment scheduled for deletion",type: "success"});handlePopUpClose("deleteEnv");- setDeleteConfirmation("");+ };++ const onSwitchToHardDelete = () => {+ if (!deleteEnvData) return;+ handlePopUpClose("deleteEnv");+ handlePopUpOpen("hardDeleteEnv", deleteEnvData);+ };++ const onEnvHardDeleteSubmit = async () => {+ if (!currentProject?.id || !hardDeleteEnvData?.id) return;++ await deleteWsEnvironment.mutateAsync({+ projectId: currentProject.id,+ id: hardDeleteEnvData.id,+ hardDelete: true+ });++ createNotification({+ text: "Successfully deleted environment",+ type: "success"+ });++ handlePopUpClose("hardDeleteEnv");+ setHardDeleteConfirmation("");};return (@@ -128,39 +165,119 @@ export const EnvironmentSection = () => {/><AlertDialogopen={popUp.deleteEnv.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("deleteEnv", isOpen)}+ >+ <AlertDialogContent className="sm:max-w-xl!">+ <AlertDialogHeader>+ <AlertDialogTitle>+ Schedule deletion of {deleteEnvData?.name ?? "environment"}?+ </AlertDialogTitle>+ <AlertDialogDescription>+ The {deleteEnvData?.slug ?? ""} environment will be inaccessible immediately, then+ permanently deleted on{" "}+ <span className="font-medium text-foreground">+ {format(addDays(new Date(), 14), "MMM d, yyyy")}+ </span>+ .+ </AlertDialogDescription>+ </AlertDialogHeader>+ <div className="space-y-2 rounded-md border border-border bg-foreground/5 p-3 text-sm">+ <div className="flex gap-2">+ <RotateCcwIcon className="mt-0.5 size-4 shrink-0 text-muted" />+ <p>+ <span className="font-medium text-foreground">Restore anytime within 14 days</span>{" "}+ <span className="opacity-80">secrets, folders, and history are preserved.</span>+ </p>+ </div>+ <div className="flex gap-2 opacity-80">+ <KeyIcon className="mt-0.5 size-4 shrink-0 text-muted" />+ <p>+ Service tokens and integrations referencing {deleteEnvData?.slug ?? ""} will fail to+ resolve. Fix or remove them before the grace period ends.+ </p>+ </div>+ <div className="flex gap-2 opacity-80">+ <ClockIcon className="mt-0.5 size-4 shrink-0 text-muted" />+ <p>After 14 days, all secret data is wiped and cannot be recovered.</p>+ </div>+ </div>+ <AlertDialogFooter className="sm:justify-between">+ <Button+ variant="danger"+ size="sm"+ className="text-danger"+ onClick={onSwitchToHardDelete}+ >+ <Trash2Icon className="size-4" />+ Delete permanently+ </Button>+ <div className="flex gap-2">+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction variant="project" onClick={onEnvDeleteSubmit}>+ Confirm+ </AlertDialogAction>+ </div>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ <AlertDialog+ open={popUp.hardDeleteEnv.isOpen}onOpenChange={(isOpen) => {- handlePopUpToggle("deleteEnv", isOpen);- if (!isOpen) setDeleteConfirmation("");+ handlePopUpToggle("hardDeleteEnv", isOpen);+ if (!isOpen) setHardDeleteConfirmation("");}}>- <AlertDialogContent>+ <AlertDialogContent className="sm:max-w-xl!"><AlertDialogHeader>- <AlertDialogTitle>Delete Environment</AlertDialogTitle>+ <AlertDialogTitle>+ Permanently delete {hardDeleteEnvData?.name ?? "environment"}?+ </AlertDialogTitle><AlertDialogDescription>- Are you sure you want to delete this environment? This action cannot be undone.+ Bypass the grace period and wipe{" "}+ <Badge variant="neutral">{hardDeleteEnvData?.slug ?? ""}</Badge> immediately. All+ secrets, folders, and history will be lost. This cannot be undone.</AlertDialogDescription></AlertDialogHeader>- <div className="w-full pb-4">+ <div className="space-y-2 rounded-md border border-danger/30 bg-danger/5 p-3 text-sm">+ <div className="flex gap-2">+ <Trash2Icon className="mt-0.5 size-4 shrink-0 text-danger" />+ <p>+ <span className="font-medium text-foreground">All secrets and folders</span>{" "}+ <span className="opacity-80">will be wiped from storage and audit reads.</span>+ </p>+ </div>+ <div className="flex gap-2">+ <TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-danger" />+ <span className="opacity-80">+ Any service token or integration referencing {hardDeleteEnvData?.slug ?? ""} will+ fail immediately and cannot be restored from this UI.+ </span>+ </div>+ </div>+ <div className="w-full pt-2 pb-4"><p className="mb-2 text-sm text-muted">- Enter the environment slug{" "}- <span className="font-medium text-foreground">{deleteEnvData?.slug ?? ""}</span> to- confirm the deletion+ Type <Badge variant="neutral">{hardDeleteEnvData?.slug ?? ""}</Badge> to confirm.</p><Input- value={deleteConfirmation}- onChange={(e) => setDeleteConfirmation(e.target.value)}- placeholder={deleteEnvData?.slug ?? ""}+ value={hardDeleteConfirmation}+ onChange={(e) => setHardDeleteConfirmation(e.target.value)}+ placeholder={hardDeleteEnvData?.slug ?? ""}/></div><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction+ <Buttonvariant="danger"- onClick={onEnvDeleteSubmit}- disabled={!deleteEnvData?.slug || deleteConfirmation !== deleteEnvData.slug}+ size="sm"+ className="text-danger"+ onClick={onEnvHardDeleteSubmit}+ isDisabled={+ !hardDeleteEnvData?.slug || hardDeleteConfirmation !== hardDeleteEnvData.slug+ }>- Delete- </AlertDialogAction>+ <Trash2Icon className="size-4" />+ Delete permanently+ </Button></AlertDialogFooter></AlertDialogContent></AlertDialog>diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsxindex 153ae769e3..de4d630fb6 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx@@ -1,8 +1,23 @@-import { ArrowDownIcon, ArrowUpIcon, PencilIcon, XIcon } from "lucide-react";+import { format } from "date-fns";+import {+ ArrowDownIcon,+ ArrowUpIcon,+ HourglassIcon,+ MoreVerticalIcon,+ PencilIcon,+ RotateCcwIcon,+ Trash2Icon,+ XIcon+} from "lucide-react";import { createNotification } from "@app/components/notifications";import { ProjectPermissionCan } from "@app/components/permissions";import {+ Badge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,Empty,EmptyDescription,EmptyHeader,@@ -24,22 +39,15 @@ import {useProject,useSubscription} from "@app/context";-import { useUpdateWsEnvironment } from "@app/hooks/api";+import { useRestoreWsEnvironment, useUpdateWsEnvironment } from "@app/hooks/api";import { UsePopUpState } from "@app/hooks/usePopUp";+type PopUpKeys = "updateEnv" | "deleteEnv" | "hardDeleteEnv" | "upgradePlan";++type EnvPayload = { name: string; slug: string; id: string; expireAfter?: string };+type Props = {- handlePopUpOpen: (- popUpName: keyof UsePopUpState<["updateEnv", "deleteEnv", "upgradePlan"]>,- {- name,- slug,- id- }: {- name: string;- slug: string;- id: string;- }- ) => void;+ handlePopUpOpen: (popUpName: keyof UsePopUpState<[PopUpKeys]>, env: EnvPayload) => void;};export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {@@ -47,6 +55,10 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {const { subscription } = useSubscription();const updateEnvironment = useUpdateWsEnvironment();+ const restoreEnvironment = useRestoreWsEnvironment();++ const activeEnvironments = currentProject.environments ?? [];+ const deletedEnvironments = currentProject.deletedEnvironments ?? [];const handleReorderEnv = async (id: string, position: number) => {if (!currentProject?.id) return;@@ -63,17 +75,39 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {});};+ const handleRestoreEnv = async (id: string) => {+ if (!currentProject?.id) return;++ try {+ await restoreEnvironment.mutateAsync({+ projectId: currentProject.id,+ id+ });++ createNotification({+ text: "Successfully restored environment",+ type: "success"+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : "Failed to restore environment";+ createNotification({+ text: message,+ type: "error"+ });+ }+ };+const isMoreEnvironmentsAllowed =- subscription?.environmentLimit && currentProject?.environments- ? currentProject.environments.length <= subscription.environmentLimit+ subscription?.environmentLimit && activeEnvironments+ ? activeEnvironments.length <= subscription.environmentLimit: true;const environmentsOverPlanLimit =- subscription?.environmentLimit && currentProject?.environments- ? Math.max(0, currentProject.environments.length - subscription.environmentLimit)+ subscription?.environmentLimit && activeEnvironments+ ? Math.max(0, activeEnvironments.length - subscription.environmentLimit): 0;- if (!currentProject.environments?.length) {+ if (!activeEnvironments.length && !deletedEnvironments.length) {return (<Empty className="border"><EmptyHeader>@@ -96,7 +130,7 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {</TableRow></TableHeader><TableBody>- {currentProject.environments.map(({ name, slug, id }, pos) => (+ {activeEnvironments.map(({ name, slug, id }, pos) => (<TableRow key={id}><TableCell>{name}</TableCell><TableCell>{slug}</TableCell>@@ -112,9 +146,9 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {variant="ghost-muted"size="xs"onClick={() =>- handleReorderEnv(id, Math.min(currentProject.environments.length, pos + 2))+ handleReorderEnv(id, Math.min(activeEnvironments.length, pos + 2))}- isDisabled={pos === currentProject.environments.length - 1 || !isAllowed}+ isDisabled={pos === activeEnvironments.length - 1 || !isAllowed}><ArrowDownIcon className="size-4" /></IconButton>@@ -190,6 +224,62 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {</TableCell></TableRow>))}+ {deletedEnvironments.map(({ name, slug, id, expireAfter }) => (+ <TableRow key={id} className="bg-warning/[0.025]">+ <TableCell className="text-mineshaft-400 line-through">{name}</TableCell>+ <TableCell className="text-mineshaft-400">{slug}</TableCell>+ <TableCell>+ <div className="flex items-center justify-end gap-2">+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="warning">+ <HourglassIcon className="size-3" />+ Pending deletion+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ Will be permanently deleted on{" "}+ {format(new Date(expireAfter), "MMM d, yyyy 'at' h:mm a")}+ </TooltipContent>+ </Tooltip>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Delete}+ a={ProjectPermissionSub.Environments}+ >+ {(isAllowed) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={!isAllowed}>+ <IconButton+ aria-label="Environment options"+ variant="ghost-muted"+ size="xs"+ isDisabled={!isAllowed}+ >+ <MoreVerticalIcon className="size-4" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => handleRestoreEnv(id)}>+ <RotateCcwIcon />+ Restore environment+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="danger"+ onClick={() =>+ handlePopUpOpen("hardDeleteEnv", { name, slug, id, expireAfter })+ }+ >+ <Trash2Icon />+ Delete permanently+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </ProjectPermissionCan>+ </div>+ </TableCell>+ </TableRow>+ ))}</TableBody></Table>);