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 name of the actor that soft deleted the environment
adilson595de9a624b4
diff --git a/backend/src/db/migrations/20260521120000_add-expire-after-and-requested-soft-delete-at-to-project-environments.ts b/backend/src/db/migrations/20260521120000_add-expire-after-and-requested-soft-delete-at-to-project-environments.tsindex 9e87616605..0d3093e2f2 100644--- a/backend/src/db/migrations/20260521120000_add-expire-after-and-requested-soft-delete-at-to-project-environments.ts+++ b/backend/src/db/migrations/20260521120000_add-expire-after-and-requested-soft-delete-at-to-project-environments.ts@@ -8,11 +8,21 @@ export async function up(knex: Knex): Promise<void> {const hasExpireAfter = await knex.schema.hasColumn(TableName.Environment, "expireAfter");const hasRequestedSoftDeleteAt = await knex.schema.hasColumn(TableName.Environment, "requestedSoftDeleteAt");+ const hasDeletedByUserId = await knex.schema.hasColumn(TableName.Environment, "deletedByUserId");+ const hasDeletedByIdentityId = await knex.schema.hasColumn(TableName.Environment, "deletedByIdentityId");- if (!hasExpireAfter || !hasRequestedSoftDeleteAt) {+ if (!hasExpireAfter || !hasRequestedSoftDeleteAt || !hasDeletedByUserId || !hasDeletedByIdentityId) {await knex.schema.alterTable(TableName.Environment, (t) => {if (!hasExpireAfter) t.timestamp("expireAfter", { useTz: true }).nullable();if (!hasRequestedSoftDeleteAt) t.timestamp("requestedSoftDeleteAt", { useTz: true }).nullable();+ if (!hasDeletedByUserId) {+ t.uuid("deletedByUserId").nullable();+ t.foreign("deletedByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");+ }+ if (!hasDeletedByIdentityId) {+ t.uuid("deletedByIdentityId").nullable();+ t.foreign("deletedByIdentityId").references("id").inTable(TableName.Identity).onDelete("SET NULL");+ }});}}@@ -23,9 +33,13 @@ export async function down(knex: Knex): Promise<void> {const hasExpireAfter = await knex.schema.hasColumn(TableName.Environment, "expireAfter");const hasRequestedSoftDeleteAt = await knex.schema.hasColumn(TableName.Environment, "requestedSoftDeleteAt");+ const hasDeletedByUserId = await knex.schema.hasColumn(TableName.Environment, "deletedByUserId");+ const hasDeletedByIdentityId = await knex.schema.hasColumn(TableName.Environment, "deletedByIdentityId");- if (hasExpireAfter || hasRequestedSoftDeleteAt) {+ if (hasExpireAfter || hasRequestedSoftDeleteAt || hasDeletedByUserId || hasDeletedByIdentityId) {await knex.schema.alterTable(TableName.Environment, (t) => {+ if (hasDeletedByUserId) t.dropColumn("deletedByUserId");+ if (hasDeletedByIdentityId) t.dropColumn("deletedByIdentityId");if (hasExpireAfter) t.dropColumn("expireAfter");if (hasRequestedSoftDeleteAt) t.dropColumn("requestedSoftDeleteAt");});diff --git a/backend/src/db/schemas/project-environments.ts b/backend/src/db/schemas/project-environments.tsindex 2073f8c928..f63dd08695 100644--- a/backend/src/db/schemas/project-environments.ts+++ b/backend/src/db/schemas/project-environments.ts@@ -16,7 +16,9 @@ export const ProjectEnvironmentsSchema = z.object({createdAt: z.date(),updatedAt: z.date(),expireAfter: z.date().nullable().optional(),- requestedSoftDeleteAt: z.date().nullable().optional()+ requestedSoftDeleteAt: z.date().nullable().optional(),+ deletedByUserId: z.string().uuid().nullable().optional(),+ deletedByIdentityId: z.string().uuid().nullable().optional()});export type TProjectEnvironments = z.infer<typeof ProjectEnvironmentsSchema>;diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.tsindex af368c735c..10460df6cf 100644--- a/backend/src/server/routes/v1/project-router.ts+++ b/backend/src/server/routes/v1/project-router.ts@@ -59,7 +59,24 @@ const projectWithEnv = SanitizedProjectSchema.merge(name: z.string(),slug: z.string(),expireAfter: z.date(),- requestedSoftDeleteAt: z.date()+ requestedSoftDeleteAt: z.date(),+ deletedBy: z+ .discriminatedUnion("type", [+ z.object({+ type: z.literal("user"),+ id: z.string(),+ email: z.string().nullable(),+ username: z.string().nullable(),+ firstName: z.string().nullable(),+ lastName: z.string().nullable()+ }),+ z.object({+ type: z.literal("identity"),+ id: z.string(),+ name: z.string()+ })+ ])+ .nullable()}).array()})diff --git a/backend/src/services/project-env/project-env-dal.ts b/backend/src/services/project-env/project-env-dal.tsindex 0dc2cbee05..dbd8addeaa 100644--- a/backend/src/services/project-env/project-env-dal.ts+++ b/backend/src/services/project-env/project-env-dal.ts@@ -72,13 +72,15 @@ export const projectEnvDALFactory = (db: TDbClient) => {projectId: string,expireAfter: Date,requestedSoftDeleteAt: Date,+ deletedByUserId: string | null,+ deletedByIdentityId: string | null,tx?: Knex) => {try {const [doc] = await (tx || db)(TableName.Environment).where({ id, projectId }).whereNull("expireAfter")- .update({ expireAfter, requestedSoftDeleteAt })+ .update({ expireAfter, requestedSoftDeleteAt, deletedByUserId, deletedByIdentityId }).returning("*");return doc as TProjectEnvironments | undefined;} catch (error) {@@ -102,7 +104,13 @@ export const projectEnvDALFactory = (db: TDbClient) => {const [doc] = await (tx || db)(TableName.Environment).where({ id, projectId }).whereNotNull("expireAfter")- .update({ expireAfter: null, requestedSoftDeleteAt: null, position })+ .update({+ expireAfter: null,+ requestedSoftDeleteAt: null,+ deletedByUserId: null,+ deletedByIdentityId: null,+ position+ }).returning("*");return doc as TProjectEnvironments | undefined;} catch (error) {diff --git a/backend/src/services/project-env/project-env-service.ts b/backend/src/services/project-env/project-env-service.tsindex 361289966d..f3605d58aa 100644--- a/backend/src/services/project-env/project-env-service.ts+++ b/backend/src/services/project-env/project-env-service.ts@@ -10,6 +10,7 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";+import { ActorType } from "../auth/auth-type";import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";import { TProjectEnvDALFactory } from "./project-env-dal";import { SOFT_DELETE_GRACE_MS, TProjectEnvQueueFactory } from "./project-env-queue";@@ -278,19 +279,32 @@ export const projectEnvServiceFactory = ({const requestedSoftDeleteAt = new Date();const expireAfter = new Date(requestedSoftDeleteAt.getTime() + SOFT_DELETE_GRACE_MS);- const doc = await projectEnvDAL.softDeleteById(id, projectId, expireAfter, requestedSoftDeleteAt, tx);+ const deletedByUserId = actor === ActorType.USER ? actorId : null;+ const deletedByIdentityId = actor === ActorType.IDENTITY ? actorId : null;+ const doc = await projectEnvDAL.softDeleteById(+ id,+ projectId,+ expireAfter,+ requestedSoftDeleteAt,+ deletedByUserId,+ deletedByIdentityId,+ tx+ );if (!doc)throw new NotFoundError({message: `Environment with id '${id}' in project with ID '${projectId}' not found`,name: "DeleteEnvironment"});- // Schedule inside the tx so a Redis-side failure rolls back the soft-delete.- await projectEnvQueue.scheduleHardDelete(id, projectId, SOFT_DELETE_GRACE_MS);-return doc;});+ if (!hardDelete) {+ // Schedule a hard delete for the environment outside of the transaction+ // so we are sure that the transaction is committed before the hard delete is scheduled+ await projectEnvQueue.scheduleHardDelete(id, projectId, SOFT_DELETE_GRACE_MS);+ }+await keyStore.setItemWithExpiry(KeyStorePrefixes.WaitUntilReadyProjectEnvironmentOperation(projectId),KeyStoreTtls.ProjectEnvironmentOperationMarkerInSeconds,diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex a48358b98d..2c903afcc7 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -456,20 +456,82 @@ export const projectDALFactory = (db: TDbClient) => {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- }));+ type DeletedEnvironmentRow = {+ id: string;+ slug: string;+ name: string;+ expireAfter: Date;+ requestedSoftDeleteAt: Date;+ deletedByUserId: string | null;+ deletedByIdentityId: string | null;+ deletedByUserEmail: string | null;+ deletedByUserUsername: string | null;+ deletedByUserFirstName: string | null;+ deletedByUserLastName: string | null;+ deletedByIdentityName: string | null;+ };++ const rows = (await (tx || db.replicaNode())(TableName.Environment)+ .leftJoin(TableName.Users, `${TableName.Environment}.deletedByUserId`, `${TableName.Users}.id`)+ .leftJoin(TableName.Identity, `${TableName.Environment}.deletedByIdentityId`, `${TableName.Identity}.id`)+ .where(`${TableName.Environment}.projectId`, projectId)+ .whereNotNull(`${TableName.Environment}.expireAfter`)+ .whereNotNull(`${TableName.Environment}.requestedSoftDeleteAt`)+ .select(+ `${TableName.Environment}.id`,+ `${TableName.Environment}.slug`,+ `${TableName.Environment}.name`,+ `${TableName.Environment}.expireAfter`,+ `${TableName.Environment}.requestedSoftDeleteAt`,+ `${TableName.Environment}.deletedByUserId`,+ `${TableName.Environment}.deletedByIdentityId`,+ db.ref("email").withSchema(TableName.Users).as("deletedByUserEmail"),+ db.ref("username").withSchema(TableName.Users).as("deletedByUserUsername"),+ db.ref("firstName").withSchema(TableName.Users).as("deletedByUserFirstName"),+ db.ref("lastName").withSchema(TableName.Users).as("deletedByUserLastName"),+ db.ref("name").withSchema(TableName.Identity).as("deletedByIdentityName")+ )+ .orderBy(`${TableName.Environment}.position`, "asc")) as DeletedEnvironmentRow[];++ return rows.map((row) => {+ let deletedBy:+ | {+ type: "user";+ id: string;+ email: string | null;+ username: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: "identity"; id: string; name: string }+ | null = null;++ if (row.deletedByUserId) {+ deletedBy = {+ type: "user",+ id: row.deletedByUserId,+ email: row.deletedByUserEmail,+ username: row.deletedByUserUsername,+ firstName: row.deletedByUserFirstName,+ lastName: row.deletedByUserLastName+ };+ } else if (row.deletedByIdentityId) {+ deletedBy = {+ type: "identity",+ id: row.deletedByIdentityId,+ name: row.deletedByIdentityName ?? ""+ };+ }++ return {+ id: row.id,+ slug: row.slug,+ name: row.name,+ expireAfter: row.expireAfter,+ requestedSoftDeleteAt: row.requestedSoftDeleteAt,+ deletedBy+ };+ });} catch (error) {throw new DatabaseError({ error, name: "Find project deleted environments" });}diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex 1a34219ca6..b3694e1b9b 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -745,6 +745,17 @@ export const projectServiceFactory = ({slug: string;expireAfter: Date;requestedSoftDeleteAt: Date;+ deletedBy:+ | {+ type: "user";+ id: string;+ email: string | null;+ username: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: "identity"; id: string; name: string }+ | null;}[],_id: project.id};@@ -864,6 +875,17 @@ export const projectServiceFactory = ({slug: string;expireAfter: Date;requestedSoftDeleteAt: Date;+ deletedBy:+ | {+ type: "user";+ id: string;+ email: string | null;+ username: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: "identity"; id: string; name: string }+ | null;}[]}));diff --git a/backend/src/services/secret-folder/secret-folder-version-dal.ts b/backend/src/services/secret-folder/secret-folder-version-dal.tsindex be4989413d..371518585b 100644--- a/backend/src/services/secret-folder/secret-folder-version-dal.ts+++ b/backend/src/services/secret-folder/secret-folder-version-dal.ts@@ -86,6 +86,7 @@ export const secretFolderVersionDALFactory = (db: TDbClient) => {.whereRaw(`folder_cte.row_num > ${TableName.Project}."pitVersionLimit"`)// Projects with version >= 3 will require to have all folder versions for PIT.andWhere(`${TableName.Project}.version`, "<", 3)+ .whereNull(`${TableName.Environment}.expireAfter`).delete();} catch (error) {throw new DatabaseError({diff --git a/backend/src/services/secret/secret-version-dal.ts b/backend/src/services/secret/secret-version-dal.tsindex acd20b4496..96ee9b0359 100644--- a/backend/src/services/secret/secret-version-dal.ts+++ b/backend/src/services/secret/secret-version-dal.ts@@ -176,6 +176,7 @@ export const secretVersionDALFactory = (db: TDbClient) => {.join(TableName.Project, `${TableName.Project}.id`, `${TableName.Environment}.projectId`).join("version_cte", "version_cte.id", `${TableName.SecretVersion}.id`).whereRaw(`version_cte.row_num > ${TableName.Project}."pitVersionLimit"`)+ .whereNull(`${TableName.Environment}.expireAfter`).delete();} catch (error) {throw new DatabaseError({diff --git a/frontend/src/hooks/api/projects/types.ts b/frontend/src/hooks/api/projects/types.tsindex e7aa7f544d..c6575648f3 100644--- a/frontend/src/hooks/api/projects/types.ts+++ b/frontend/src/hooks/api/projects/types.ts@@ -53,9 +53,21 @@ export type ProjectEnv = {slug: string;};+export type ProjectDeletedEnvActor =+ | {+ type: "user";+ id: string;+ email: string | null;+ username: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: "identity"; id: string; name: string };+export type ProjectDeletedEnv = ProjectEnv & {expireAfter: string;requestedSoftDeleteAt: string;+ deletedBy: ProjectDeletedEnvActor | null;};export type ProjectTag = { id: string; name: string; slug: 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 e0f3e215c3..bfa21030a9 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx@@ -173,8 +173,8 @@ export const EnvironmentSection = () => {Schedule deletion of {deleteEnvData?.name ?? "environment"}?</AlertDialogTitle><AlertDialogDescription>- The {deleteEnvData?.slug ?? ""} environment will be inaccessible immediately, then- permanently deleted on{" "}+ The <Badge variant="neutral">{deleteEnvData?.slug ?? ""}</Badge> environment will be+ inaccessible immediately, then permanently deleted on{" "}<span className="font-medium text-foreground">{format(addDays(new Date(), 14), "MMM d, yyyy")}</span>@@ -192,8 +192,9 @@ export const EnvironmentSection = () => {<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.+ Service tokens and integrations referencing{" "}+ <Badge variant="neutral">{deleteEnvData?.slug ?? ""}</Badge> will fail to resolve.+ Fix or remove them before the grace period ends.</p></div><div className="flex gap-2 opacity-80">diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsxindex de4d630fb6..d3dabaf058 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx@@ -1,4 +1,4 @@-import { format } from "date-fns";+import { format, intervalToDuration } from "date-fns";import {ArrowDownIcon,ArrowUpIcon,@@ -40,6 +40,7 @@ import {useSubscription} from "@app/context";import { useRestoreWsEnvironment, useUpdateWsEnvironment } from "@app/hooks/api";+import { ProjectDeletedEnvActor } from "@app/hooks/api/projects/types";import { UsePopUpState } from "@app/hooks/usePopUp";type PopUpKeys = "updateEnv" | "deleteEnv" | "hardDeleteEnv" | "upgradePlan";@@ -50,6 +51,32 @@ type Props = {handlePopUpOpen: (popUpName: keyof UsePopUpState<[PopUpKeys]>, env: EnvPayload) => void;};+const getActorLabel = (actor: ProjectDeletedEnvActor | null): string => {+ if (!actor) return "Someone";+ if (actor.type === "identity") return actor.name || "An identity";++ return actor.firstName || actor.username || actor.email || "A user";+};++const formatRemainingDuration = (target: Date): string | null => {+ const now = new Date();+ if (target.getTime() <= now.getTime()) return null;++ const duration = intervalToDuration({ start: now, end: target });+ const parts: Array<[number | undefined, string]> = [+ [duration.years, "y"],+ [duration.months, "mo"],+ [duration.days, "d"],+ [duration.hours, "h"],+ [duration.minutes, "m"]+ ];++ const nonZero = parts.filter(([value]) => value && value > 0).slice(0, 2);+ if (nonZero.length === 0) return "<1m";++ return nonZero.map(([value, suffix]) => `${value}${suffix}`).join(" ");+};+export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {const { currentProject } = useProject();const { subscription } = useSubscription();@@ -224,62 +251,81 @@ 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>- ))}+ {deletedEnvironments.map(+ ({ name, slug, id, expireAfter, requestedSoftDeleteAt, deletedBy }) => {+ const expireAfterDate = new Date(expireAfter);+ const remaining = formatRemainingDuration(expireAfterDate);++ return (+ <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 className="max-w-xs">+ <div className="flex flex-col gap-1">+ <span className="text-sm font-semibold text-foreground">+ {remaining+ ? `${remaining} until permanent deletion`+ : "Awaiting permanent deletion"}+ </span>+ <span className="text-xs text-mineshaft-300">+ Scheduled for {format(expireAfterDate, "MMM d, yyyy, h:mm a")}+ </span>+ <span className="text-xs text-mineshaft-300">+ Soft-deleted by {getActorLabel(deletedBy)} ·{" "}+ {format(new Date(requestedSoftDeleteAt), "MMM d, yyyy")}+ </span>+ </div>+ </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>);