Compare commits

...

4 Commits

Author SHA1 Message Date
Alan Buscaglia
b151d97793 docs: add interface depth and reuse rules to AGENTS.md 2025-12-18 13:20:04 +01:00
alejandrobailo
0c771e3320 refactor: code improvements 2025-12-18 12:54:57 +01:00
alejandrobailo
e8c8b18c09 feat: add simple Mutelist description 2025-12-18 12:29:28 +01:00
alejandrobailo
a20f4bb21f feat: revert muted finding filter checkbox behavior 2025-12-18 12:01:58 +01:00
12 changed files with 328 additions and 177 deletions

View File

@@ -13,6 +13,32 @@
- ALWAYS: `const X = { A: "a", B: "b" } as const; type T = typeof X[keyof typeof X]`
- NEVER: `type T = "a" | "b"`
### Interfaces
- ALWAYS: One level depth only; object property → dedicated interface (recursive)
- ALWAYS: Reuse via `extends`
- NEVER: Inline nested objects
```typescript
// ✅ CORRECT
interface UserAddress {
street: string;
city: string;
}
interface User {
id: string;
address: UserAddress;
}
interface Admin extends User {
permissions: string[];
}
// ❌ WRONG
interface User {
address: { street: string; city: string };
}
```
### Styling
- Single class: `className="bg-slate-800 text-white"`

View File

@@ -252,16 +252,15 @@ export const updateMuteRule = async (
});
if (!response.ok) {
let errorMessage = `Failed to update mute rule: ${response.statusText}`;
try {
const errorData = await response.json();
throw new Error(
errorData?.errors?.[0]?.detail ||
errorData?.message ||
`Failed to update mute rule: ${response.statusText}`,
);
errorMessage =
errorData?.errors?.[0]?.detail || errorData?.message || errorMessage;
} catch {
throw new Error(`Failed to update mute rule: ${response.statusText}`);
// JSON parsing failed, use default error message
}
throw new Error(errorMessage);
}
revalidatePath("/mutelist");
@@ -306,16 +305,15 @@ export const toggleMuteRule = async (
});
if (!response.ok) {
let errorMessage = `Failed to toggle mute rule: ${response.statusText}`;
try {
const errorData = await response.json();
throw new Error(
errorData?.errors?.[0]?.detail ||
errorData?.message ||
`Failed to toggle mute rule: ${response.statusText}`,
);
errorMessage =
errorData?.errors?.[0]?.detail || errorData?.message || errorMessage;
} catch {
throw new Error(`Failed to toggle mute rule: ${response.statusText}`);
// JSON parsing failed, use default error message
}
throw new Error(errorMessage);
}
revalidatePath("/mutelist");

View File

@@ -1,6 +1,7 @@
"use client";
import { Textarea } from "@heroui/input";
import { Trash2 } from "lucide-react";
import { useActionState, useEffect, useState } from "react";
import {
@@ -9,9 +10,9 @@ import {
getMutedFindingsConfig,
updateMutedFindingsConfig,
} from "@/actions/processors";
import { DeleteIcon } from "@/components/icons";
import { Button, Card, Skeleton } from "@/components/shadcn";
import { useToast } from "@/components/ui";
import { CustomAlertModal } from "@/components/ui/custom";
import { CustomLink } from "@/components/ui/custom/custom-link";
import { fontMono } from "@/config/fonts";
import {
@@ -36,10 +37,22 @@ export function AdvancedMutelistForm() {
}>({ isValid: true });
const [hasUserStartedTyping, setHasUserStartedTyping] = useState(false);
// Unified action that decides to create or update based on ID presence
const saveConfig = async (
_prevState: MutedFindingsConfigActionState,
formData: FormData,
): Promise<MutedFindingsConfigActionState> => {
const id = formData.get("id");
if (id) {
return updateMutedFindingsConfig(_prevState, formData);
}
return createMutedFindingsConfig(_prevState, formData);
};
const [state, formAction, isPending] = useActionState<
MutedFindingsConfigActionState,
FormData
>(config ? updateMutedFindingsConfig : createMutedFindingsConfig, null);
>(saveConfig, null);
const { toast } = useToast();
@@ -62,6 +75,10 @@ export function AdvancedMutelistForm() {
title: "Configuration saved successfully",
description: state.success,
});
// Reload config to get the created/updated data (shows Delete button)
getMutedFindingsConfig().then((result) => {
setConfig(result || null);
});
} else if (state?.errors?.general) {
toast({
variant: "destructive",
@@ -123,7 +140,7 @@ export function AdvancedMutelistForm() {
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-[400px] w-full" />
<div className="flex gap-4">
<div className="flex w-full justify-end gap-4">
<Skeleton className="h-10 w-24" />
<Skeleton className="h-10 w-24" />
</div>
@@ -132,23 +149,24 @@ export function AdvancedMutelistForm() {
);
}
if (showDeleteConfirmation) {
return (
<Card variant="base" className="p-6">
return (
<>
{/* Delete Confirmation Modal */}
<CustomAlertModal
isOpen={showDeleteConfirmation}
onOpenChange={setShowDeleteConfirmation}
title="Delete Mutelist Configuration"
size="md"
>
<div className="flex flex-col gap-4">
<h3 className="text-default-700 text-lg font-semibold">
Delete Mutelist Configuration
</h3>
<p className="text-default-600 text-sm">
Are you sure you want to delete this configuration? This action
cannot be undone.
</p>
<div className="flex w-full justify-center gap-6">
<div className="flex w-full justify-end gap-4">
<Button
type="button"
aria-label="Cancel"
className="w-full bg-transparent"
variant="outline"
variant="ghost"
size="lg"
onClick={() => setShowDeleteConfirmation(false)}
disabled={isDeleting}
@@ -157,107 +175,111 @@ export function AdvancedMutelistForm() {
</Button>
<Button
type="button"
aria-label="Delete"
className="w-full"
variant="destructive"
size="lg"
disabled={isDeleting}
onClick={handleDelete}
>
{isDeleting ? (
"Deleting"
) : (
<>
<DeleteIcon size={24} />
Delete
</>
)}
<Trash2 className="size-4" />
{isDeleting ? "Deleting..." : "Delete"}
</Button>
</div>
</div>
</Card>
);
}
</CustomAlertModal>
return (
<Card variant="base" className="p-6">
<form action={formAction} className="flex flex-col gap-4">
{config && <input type="hidden" name="id" value={config.id} />}
<Card variant="base" className="p-6">
<form action={formAction} className="flex flex-col gap-4">
{config && <input type="hidden" name="id" value={config.id} />}
<div className="flex flex-col gap-4">
<div>
<h3 className="text-default-700 mb-2 text-lg font-semibold">
Advanced Mutelist Configuration
</h3>
<ul className="text-default-600 mb-4 list-disc pl-5 text-sm">
<li>
<strong>
This Mutelist configuration will take effect on the next scan.
</strong>
</li>
<li>
Use this for pattern-based muting with wildcards, regions, and
tags.
</li>
<li>
Learn more about configuring the Mutelist{" "}
<CustomLink
size="sm"
href="https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/prowler-app-mute-findings"
>
here
</CustomLink>
.
</li>
<li>
A default Mutelist is used to exclude certain predefined
resources if no Mutelist is provided.
</li>
</ul>
</div>
<div className="flex flex-col gap-2">
<label
htmlFor="configuration"
className="text-default-700 text-sm font-medium"
>
Mutelist Configuration (YAML)
</label>
<div className="flex flex-col gap-4">
<div>
<Textarea
id="configuration"
name="configuration"
placeholder={defaultMutedFindingsConfig}
variant="bordered"
value={configText}
onChange={(e) => handleConfigChange(e.target.value)}
minRows={20}
maxRows={20}
isInvalid={
(!hasUserStartedTyping && !!state?.errors?.configuration) ||
!yamlValidation.isValid
}
errorMessage={
(!hasUserStartedTyping && state?.errors?.configuration) ||
(!yamlValidation.isValid ? yamlValidation.error : "")
}
classNames={{
input: fontMono.className + " text-sm",
base: "min-h-[400px]",
errorMessage: "whitespace-pre-wrap",
}}
/>
{yamlValidation.isValid && configText && hasUserStartedTyping && (
<div className="text-tiny text-success my-1 flex items-center px-1">
<span>Valid YAML format</span>
</div>
)}
<h3 className="text-default-700 mb-2 text-lg font-semibold">
Advanced Mutelist Configuration
</h3>
<ul className="text-default-600 mb-4 list-disc pl-5 text-sm">
<li>
<strong>
This Mutelist configuration will take effect on the next
scan.
</strong>
</li>
<li>
Use this for pattern-based muting with wildcards, regions, and
tags.
</li>
<li>
Learn more about configuring the Mutelist{" "}
<CustomLink
size="sm"
href="https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/prowler-app-mute-findings"
>
here
</CustomLink>
.
</li>
<li>
A default Mutelist is used to exclude certain predefined
resources if no Mutelist is provided.
</li>
</ul>
</div>
<div className="flex flex-col gap-2">
<label
htmlFor="configuration"
className="text-default-700 text-sm font-medium"
>
Mutelist Configuration (YAML)
</label>
<div>
<Textarea
id="configuration"
name="configuration"
placeholder={defaultMutedFindingsConfig}
variant="bordered"
value={configText}
onChange={(e) => handleConfigChange(e.target.value)}
minRows={20}
maxRows={20}
isInvalid={
(!hasUserStartedTyping && !!state?.errors?.configuration) ||
!yamlValidation.isValid
}
errorMessage={
(!hasUserStartedTyping && state?.errors?.configuration) ||
(!yamlValidation.isValid ? yamlValidation.error : "")
}
classNames={{
input: fontMono.className + " text-sm",
base: "min-h-[400px]",
errorMessage: "whitespace-pre-wrap",
}}
/>
{yamlValidation.isValid &&
configText &&
hasUserStartedTyping && (
<div className="text-tiny text-success my-1 flex items-center px-1">
<span>Valid YAML format</span>
</div>
)}
</div>
</div>
</div>
</div>
<div className="flex flex-col gap-4">
<div className="flex w-full justify-end gap-4">
{config && (
<Button
type="button"
aria-label="Delete Configuration"
variant="outline"
size="lg"
onClick={() => setShowDeleteConfirmation(true)}
disabled={isPending || isDeleting}
>
<Trash2 className="size-4" />
Delete
</Button>
)}
<Button
type="submit"
size="lg"
@@ -268,23 +290,8 @@ export function AdvancedMutelistForm() {
{isPending ? "Saving..." : config ? "Update" : "Save"}
</Button>
</div>
{config && (
<Button
type="button"
aria-label="Delete Configuration"
className="w-full"
variant="outline"
size="default"
onClick={() => setShowDeleteConfirmation(true)}
disabled={isPending}
>
<DeleteIcon size={20} />
Delete Configuration
</Button>
)}
</div>
</form>
</Card>
</form>
</Card>
</>
);
}

View File

@@ -3,13 +3,23 @@ import { Info } from "lucide-react";
import { getMuteRules } from "@/actions/mute-rules";
import { Card, Skeleton } from "@/components/shadcn";
import { DataTable } from "@/components/ui/table";
import { SearchParamsProps } from "@/types/components";
import { muteRulesColumns } from "./mute-rules-columns";
export async function MuteRulesTable() {
interface MuteRulesTableProps {
searchParams: SearchParamsProps;
}
export async function MuteRulesTable({ searchParams }: MuteRulesTableProps) {
const page = parseInt(searchParams.page?.toString() || "1", 10);
const pageSize = parseInt(searchParams.pageSize?.toString() || "10", 10);
const sort = searchParams.sort?.toString() || "-inserted_at";
const muteRulesData = await getMuteRules({
pageSize: 50,
sort: "-inserted_at",
page,
pageSize,
sort,
});
const muteRules = muteRulesData?.data || [];
@@ -36,7 +46,36 @@ export async function MuteRulesTable() {
);
}
return <DataTable columns={muteRulesColumns} data={muteRules} />;
return (
<Card variant="base" className="p-6">
<div className="mb-6">
<h3 className="text-default-700 mb-2 text-lg font-semibold">
Simple Mutelist Rules
</h3>
<ul className="text-default-600 list-disc pl-5 text-sm">
<li>
<strong>
These rules take effect immediately on existing findings.
</strong>
</li>
<li>
Create rules by selecting findings from the Findings page and
clicking &quot;Mute&quot;.
</li>
<li>Toggle rules on/off to enable or disable muting.</li>
</ul>
</div>
<DataTable
columns={muteRulesColumns}
data={muteRules}
metadata={
muteRulesData?.meta
? { ...muteRulesData.meta, version: "" }
: undefined
}
/>
</Card>
);
}
export function MuteRulesTableSkeleton() {

View File

@@ -1,17 +1,25 @@
import { Suspense } from "react";
import { ContentLayout } from "@/components/ui";
import { SearchParamsProps } from "@/types/components";
import { MuteRulesTable, MuteRulesTableSkeleton } from "./_components/simple";
import { MutelistTabs } from "./mutelist-tabs";
export default function MutelistPage() {
export default async function MutelistPage({
searchParams,
}: {
searchParams: Promise<SearchParamsProps>;
}) {
const resolvedSearchParams = await searchParams;
const searchParamsKey = JSON.stringify(resolvedSearchParams);
return (
<ContentLayout title="Mutelist" icon="lucide:volume-x">
<MutelistTabs
simpleContent={
<Suspense fallback={<MuteRulesTableSkeleton />}>
<MuteRulesTable />
<Suspense key={searchParamsKey} fallback={<MuteRulesTableSkeleton />}>
<MuteRulesTable searchParams={resolvedSearchParams} />
</Suspense>
}
/>

View File

@@ -159,9 +159,11 @@ export const ClientAccordionContent = ({
<h4 className="mb-2 text-sm font-medium">Findings</h4>
<DataTable
// Remove select (index 0) and updated_at (index 6) columns for compliance view
// Remove select and updated_at columns for compliance view
columns={getColumnFindings({}, 0).filter(
(_: unknown, index: number) => index !== 0 && index !== 6,
(col) =>
col.id !== "select" &&
!("accessorKey" in col && col.accessorKey === "updated_at"),
)}
data={expandedFindings || []}
metadata={findings?.meta}

View File

@@ -1,44 +1,63 @@
"use client";
import { Checkbox } from "@heroui/checkbox";
import { useSearchParams } from "next/navigation";
import { useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useUrlFilters } from "@/hooks/use-url-filters";
import { Checkbox } from "@/components/shadcn";
// Constants for muted filter URL values
const MUTED_FILTER_VALUES = {
EXCLUDE: "false",
INCLUDE: "include",
} as const;
export const CustomCheckboxMutedFindings = () => {
const { updateFilter, clearFilter } = useUrlFilters();
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [excludeMuted, setExcludeMuted] = useState(
searchParams.get("filter[muted]") === "false",
);
const handleMutedChange = (value: boolean) => {
setExcludeMuted(value);
// Get the current muted filter value from URL
// Middleware ensures filter[muted] is always present when navigating to /findings
const mutedFilterValue = searchParams.get("filter[muted]");
// Only URL update if value is false else remove filter
if (value) {
updateFilter("muted", "false");
// URL states:
// - filter[muted]=false → Exclude muted (checkbox UNCHECKED)
// - filter[muted]=include → Include muted (checkbox CHECKED)
const includeMuted = mutedFilterValue === MUTED_FILTER_VALUES.INCLUDE;
const handleMutedChange = (checked: boolean | "indeterminate") => {
const isChecked = checked === true;
const params = new URLSearchParams(searchParams.toString());
if (isChecked) {
// Include muted: set special value (API will ignore invalid value and show all)
params.set("filter[muted]", MUTED_FILTER_VALUES.INCLUDE);
} else {
clearFilter("muted");
// Exclude muted: apply filter to show only non-muted
params.set("filter[muted]", MUTED_FILTER_VALUES.EXCLUDE);
}
// Reset to page 1 when changing filter
if (params.has("page")) {
params.set("page", "1");
}
router.push(`${pathname}?${params.toString()}`, { scroll: false });
};
return (
<div className="flex h-full text-nowrap">
<div className="flex h-full items-center gap-2 text-nowrap">
<Checkbox
classNames={{
label: "text-small",
wrapper: "checkbox-update",
}}
size="md"
color="primary"
aria-label="Include Mutelist"
isSelected={excludeMuted}
onValueChange={handleMutedChange}
id="include-muted"
checked={includeMuted}
onCheckedChange={handleMutedChange}
aria-label="Include muted findings"
/>
<label
htmlFor="include-muted"
className="cursor-pointer text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Exclude muted findings
</Checkbox>
Include muted findings
</label>
</div>
);
};

View File

@@ -4,14 +4,12 @@ import { VolumeX } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/shadcn";
import { FindingProps } from "@/types";
import { MuteFindingsModal } from "./mute-findings-modal";
interface FloatingMuteButtonProps {
selectedCount: number;
selectedFindingIds: string[];
selectedFindings: FindingProps[];
onComplete?: () => void;
}

View File

@@ -28,19 +28,22 @@ export function FindingsTableWithSelection({
setRowSelection({});
}, [metadata?.pagination?.page]);
// Ensure data is always an array for safe operations
const safeData = data ?? [];
// Get selected finding IDs and data (only non-muted findings can be selected)
const selectedFindingIds = Object.keys(rowSelection)
.filter((key) => rowSelection[key])
.map((idx) => data[parseInt(idx)]?.id)
.map((idx) => safeData[parseInt(idx)]?.id)
.filter(Boolean);
const selectedFindings = Object.keys(rowSelection)
.filter((key) => rowSelection[key])
.map((idx) => data[parseInt(idx)])
.map((idx) => safeData[parseInt(idx)])
.filter(Boolean);
// Count of selectable rows (non-muted findings only)
const selectableRowCount = data.filter((f) => !f.attributes.muted).length;
const selectableRowCount = safeData.filter((f) => !f.attributes.muted).length;
// Function to determine if a row can be selected (muted findings cannot be selected)
const getRowCanSelect = (row: Row<FindingProps>): boolean => {
@@ -75,7 +78,7 @@ export function FindingsTableWithSelection({
>
<DataTable
columns={columns}
data={data}
data={safeData}
metadata={metadata}
enableRowSelection
rowSelection={rowSelection}
@@ -87,7 +90,6 @@ export function FindingsTableWithSelection({
<FloatingMuteButton
selectedCount={selectedFindingIds.length}
selectedFindingIds={selectedFindingIds}
selectedFindings={selectedFindings}
onComplete={handleMuteComplete}
/>
)}

View File

@@ -14,6 +14,7 @@ import { SamlConfigForm } from "./saml-config-form";
export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
const [isSamlModalOpen, setIsSamlModalOpen] = useState(false);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const { toast } = useToast();
const id = samlConfig?.id;
@@ -30,6 +31,7 @@ export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
title: "SAML configuration removed",
description: result.success,
});
setIsDeleteModalOpen(false);
} else if (result.errors?.general) {
toast({
variant: "destructive",
@@ -37,7 +39,7 @@ export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
description: result.errors.general,
});
}
} catch (error) {
} catch {
toast({
variant: "destructive",
title: "Error",
@@ -50,6 +52,7 @@ export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
return (
<>
{/* Configure SAML Modal */}
<CustomAlertModal
isOpen={isSamlModalOpen}
onOpenChange={setIsSamlModalOpen}
@@ -61,6 +64,42 @@ export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
/>
</CustomAlertModal>
{/* Delete Confirmation Modal */}
<CustomAlertModal
isOpen={isDeleteModalOpen}
onOpenChange={setIsDeleteModalOpen}
title="Remove SAML Configuration"
size="md"
>
<div className="flex flex-col gap-4">
<p className="text-default-600 text-sm">
Are you sure you want to remove the SAML SSO configuration? Users
will no longer be able to sign in using SAML.
</p>
<div className="flex w-full justify-end gap-4">
<Button
type="button"
variant="ghost"
size="lg"
onClick={() => setIsDeleteModalOpen(false)}
disabled={isDeleting}
>
Cancel
</Button>
<Button
type="button"
variant="destructive"
size="lg"
disabled={isDeleting}
onClick={handleRemoveSaml}
>
<Trash2Icon className="size-4" />
{isDeleting ? "Removing..." : "Remove"}
</Button>
</div>
</div>
</CustomAlertModal>
<Card variant="base" padding="lg">
<CardHeader>
<div className="flex flex-col gap-1">
@@ -98,11 +137,10 @@ export const SamlIntegrationCard = ({ samlConfig }: { samlConfig?: any }) => {
<Button
size="sm"
variant="destructive"
disabled={isDeleting}
onClick={handleRemoveSaml}
onClick={() => setIsDeleteModalOpen(true)}
>
{!isDeleting && <Trash2Icon size={16} />}
{isDeleting ? "Removing..." : "Remove"}
<Trash2Icon size={16} />
Remove
</Button>
)}
</div>

View File

@@ -70,7 +70,7 @@ export const getMenuList = ({ pathname }: MenuListOptions): GroupProps[] => {
groupLabel: "",
menus: [
{
href: "/findings",
href: "/findings?filter[muted]=false",
label: "Findings",
icon: Tag,
},

View File

@@ -49,6 +49,20 @@ export default auth((req: NextRequest & { auth: any }) => {
}
}
// Redirect /findings to include default muted filter if not present
if (
pathname === "/findings" &&
!req.nextUrl.searchParams.has("filter[muted]")
) {
const findingsUrl = new URL("/findings", req.url);
// Preserve existing search params
req.nextUrl.searchParams.forEach((value, key) => {
findingsUrl.searchParams.set(key, value);
});
findingsUrl.searchParams.set("filter[muted]", "false");
return NextResponse.redirect(findingsUrl);
}
return NextResponse.next();
});