Add project delete protection

This commit is contained in:
carlosmonastyrski
2025-04-14 21:41:46 -03:00
parent 68ba807b43
commit 101c056f43
12 changed files with 180 additions and 3 deletions

View File

@@ -0,0 +1,21 @@
import { Knex } from "knex";
import { TableName } from "../schemas";
export async function up(knex: Knex): Promise<void> {
const hasCol = await knex.schema.hasColumn(TableName.Project, "hasDeleteProtection");
if (!hasCol) {
await knex.schema.alterTable(TableName.Project, (t) => {
t.boolean("hasDeleteProtection").defaultTo(true);
});
}
}
export async function down(knex: Knex): Promise<void> {
const hasCol = await knex.schema.hasColumn(TableName.Project, "hasDeleteProtection");
if (hasCol) {
await knex.schema.alterTable(TableName.Project, (t) => {
t.dropColumn("hasDeleteProtection");
});
}
}

View File

@@ -26,7 +26,8 @@ export const ProjectsSchema = z.object({
kmsSecretManagerEncryptedDataKey: zodBuffer.nullable().optional(),
description: z.string().nullable().optional(),
type: z.string(),
enforceCapitalization: z.boolean().default(false)
enforceCapitalization: z.boolean().default(false),
hasDeleteProtection: z.boolean().default(true).nullable().optional()
});
export type TProjects = z.infer<typeof ProjectsSchema>;

View File

@@ -255,7 +255,8 @@ export const SanitizedProjectSchema = ProjectsSchema.pick({
upgradeStatus: true,
pitVersionLimit: true,
kmsCertificateKeyId: true,
auditLogsRetentionDays: true
auditLogsRetentionDays: true,
hasDeleteProtection: true
});
export const SanitizedTagSchema = SecretTagsSchema.pick({

View File

@@ -390,6 +390,43 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
});
server.route({
method: "POST",
url: "/:workspaceId/delete-protection",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
workspaceId: z.string().trim()
}),
body: z.object({
hasDeleteProtection: z.boolean()
}),
response: {
200: z.object({
message: z.string(),
workspace: SanitizedProjectSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const workspace = await server.services.project.toggleDeleteProtection({
actorId: req.permission.id,
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
projectId: req.params.workspaceId,
hasDeleteProtection: req.body.hasDeleteProtection
});
return {
message: "Successfully changed workspace settings",
workspace
};
}
});
server.route({
method: "PUT",
url: "/:workspaceSlug/version-limit",

View File

@@ -86,6 +86,7 @@ import {
TProjectAccessRequestDTO,
TSearchProjectsDTO,
TToggleProjectAutoCapitalizationDTO,
TToggleProjectDeleteProtectionDTO,
TUpdateAuditLogsRetentionDTO,
TUpdateProjectDTO,
TUpdateProjectKmsDTO,
@@ -482,6 +483,12 @@ export const projectServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.Project);
if (project.hasDeleteProtection) {
throw new ForbiddenRequestError({
message: "Project delete protection is enabled"
});
}
const deletedProject = await projectDAL.transaction(async (tx) => {
// delete these so that project custom roles can be deleted in cascade effect
// direct deletion of project without these will cause fk error
@@ -648,6 +655,29 @@ export const projectServiceFactory = ({
return updatedProject;
};
const toggleDeleteProtection = async ({
projectId,
actor,
actorId,
actorOrgId,
actorAuthMethod,
hasDeleteProtection
}: TToggleProjectDeleteProtectionDTO) => {
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.Any
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
const updatedProject = await projectDAL.updateById(projectId, { hasDeleteProtection });
return updatedProject;
};
const updateVersionLimit = async ({
actor,
actorId,
@@ -1499,6 +1529,7 @@ export const projectServiceFactory = ({
getProjectUpgradeStatus,
getAProject,
toggleAutoCapitalization,
toggleDeleteProtection,
updateName,
upgradeProject,
listProjectCas,

View File

@@ -66,6 +66,10 @@ export type TToggleProjectAutoCapitalizationDTO = {
autoCapitalization: boolean;
} & TProjectPermission;
export type TToggleProjectDeleteProtectionDTO = {
hasDeleteProtection: boolean;
} & TProjectPermission;
export type TUpdateProjectVersionLimitDTO = {
pitVersionLimit: number;
workspaceSlug: string;

View File

@@ -33,6 +33,7 @@ import {
TGetUpgradeProjectStatusDTO,
TListProjectIdentitiesDTO,
ToggleAutoCapitalizationDTO,
ToggleDeleteProjectProtectionDTO,
TSearchProjectsDTO,
TUpdateWorkspaceIdentityRoleDTO,
TUpdateWorkspaceUserRoleDTO,
@@ -306,6 +307,25 @@ export const useToggleAutoCapitalization = () => {
});
};
export const useToggleDeleteProjectProtection = () => {
const queryClient = useQueryClient();
return useMutation<Workspace, object, ToggleDeleteProjectProtectionDTO>({
mutationFn: async ({ workspaceID, state }) => {
const { data } = await apiRequest.post<{ workspace: Workspace }>(
`/api/v1/workspace/${workspaceID}/delete-protection`,
{
hasDeleteProtection: state
}
);
return data.workspace;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
}
});
};
export const useUpdateWorkspaceVersionLimit = () => {
const queryClient = useQueryClient();

View File

@@ -36,6 +36,7 @@ export type Workspace = {
slug: string;
createdAt: string;
roles?: TProjectRole[];
hasDeleteProtection: boolean;
};
export type WorkspaceEnv = {
@@ -80,6 +81,7 @@ export type UpdateProjectDTO = {
export type UpdatePitVersionLimitDTO = { projectSlug: string; pitVersionLimit: number };
export type UpdateAuditLogsRetentionDTO = { projectSlug: string; auditLogsRetentionDays: number };
export type ToggleAutoCapitalizationDTO = { workspaceID: string; state: boolean };
export type ToggleDeleteProjectProtectionDTO = { workspaceID: string; state: boolean };
export type DeleteWorkspaceDTO = { workspaceID: string };

View File

@@ -0,0 +1,57 @@
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Checkbox } from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
import { useToggleDeleteProjectProtection } from "@app/hooks/api/workspace/queries";
export const DeleteProjectProtection = () => {
const { currentWorkspace } = useWorkspace();
const { mutateAsync } = useToggleDeleteProjectProtection();
const handleToggleDeleteProjectProtection = async (state: boolean) => {
try {
if (!currentWorkspace?.id) return;
await mutateAsync({
workspaceID: currentWorkspace.id,
state
});
const text = `Successfully ${state ? "enabled" : "disabled"} delete protection`;
createNotification({
text,
type: "success"
});
} catch (err) {
console.error(err);
createNotification({
text: "Failed to update delete protection",
type: "error"
});
}
};
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<p className="mb-3 text-xl font-semibold">Delete Protection</p>
<ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>
{(isAllowed) => (
<div className="w-max">
<Checkbox
className="data-[state=checked]:bg-primary"
id="hasDeleteProtection"
isDisabled={!isAllowed}
isChecked={currentWorkspace?.hasDeleteProtection ?? false}
onCheckedChange={(state) => {
handleToggleDeleteProjectProtection(state as boolean);
}}
>
Protects the project from being deleted accidentally. While this option is enabled,
you can&apos;t delete the project.
</Checkbox>
</div>
)}
</ProjectPermissionCan>
</div>
);
};

View File

@@ -0,0 +1 @@
export { DeleteProjectProtection } from "./DeleteProjectProtection";

View File

@@ -144,7 +144,7 @@ export const DeleteProjectSection = () => {
{(isAllowed) => (
<Button
isLoading={isDeleting}
isDisabled={!isAllowed || isDeleting}
isDisabled={!isAllowed || isDeleting || currentWorkspace?.hasDeleteProtection}
colorSchema="danger"
variant="outline_bg"
type="submit"

View File

@@ -5,6 +5,7 @@ import { ProjectType, ProjectVersion } from "@app/hooks/api/workspace/types";
import { AuditLogsRetentionSection } from "../AuditLogsRetentionSection";
import { AutoCapitalizationSection } from "../AutoCapitalizationSection";
import { BackfillSecretReferenceSecretion } from "../BackfillSecretReferenceSection";
import { DeleteProjectProtection } from "../DeleteProjectProtection";
import { DeleteProjectSection } from "../DeleteProjectSection";
import { EnvironmentSection } from "../EnvironmentSection";
import { PointInTimeVersionLimitSection } from "../PointInTimeVersionLimitSection";
@@ -27,6 +28,7 @@ export const ProjectGeneralTab = () => {
{currentWorkspace?.version !== ProjectVersion.V3 && isSecretManager && (
<RebuildSecretIndicesSection />
)}
<DeleteProjectProtection />
<DeleteProjectSection />
</div>
);