ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
feat: add report library delete actions
Mafifrizi586b4c8f008f
diff --git a/ares/api/server.py b/ares/api/server.pyindex aba381a..10f8b76 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -1785,6 +1785,7 @@ async def get_cvss_summary(# ── Reports ───────────────────────────────────────────────────────────────────_REPORT_EXTENSIONS = {"html", "pdf", "markdown", "json", "md"}+_REPORT_BULK_DELETE_EXTENSIONS = {"html", "pdf", "json", "md"}def _report_slug(name: str) -> str:@@ -1847,7 +1848,7 @@ def _safe_report_file_path(campaign_id=campaign_id,campaign=campaign,)- root = _report_root()+ root = _report_root().resolve()candidate = (root / safe_filename).resolve()try:candidate.relative_to(root)@@ -1858,8 +1859,36 @@ def _safe_report_file_path(return candidate+def _iter_report_files_for_campaign(+ *,+ campaign_id: str,+ campaign: dict[str, Any],+ extensions: set[str] | None = None,+) -> list[Path]:+ root = _report_root().resolve()+ if not root.exists():+ return []+ prefixes = _report_prefixes(campaign_id, campaign)+ allowed_extensions = extensions or _REPORT_EXTENSIONS+ files: list[Path] = []+ for path in sorted(root.glob("*")):+ if not path.is_file():+ continue+ if path.suffix.lstrip(".").lower() not in allowed_extensions:+ continue+ if not any(path.name.startswith(prefix) for prefix in prefixes):+ continue+ resolved = path.resolve()+ try:+ resolved.relative_to(root)+ except ValueError:+ continue+ files.append(resolved)+ return files++def _delete_report_artifacts_for_campaign(campaign_id: str) -> int:- root = _report_root()+ root = _report_root().resolve()if not root.exists():return 0prefix = f"{_report_slug(campaign_id)}_"@@ -1934,26 +1963,16 @@ async def list_reports(if not campaign:raise HTTPException(404, "Campaign not found")await _require_campaign_access(campaign, actor)- root = _report_root()- prefixes = _report_prefixes(campaign_id, campaign)reports: list[dict[str, Any]] = []- for path in sorted(root.glob("*")):- if not path.is_file():- continue- if path.suffix.lstrip(".").lower() not in _REPORT_EXTENSIONS:- continue- if not any(path.name.startswith(prefix) for prefix in prefixes):- continue- resolved = path.resolve()- try:- resolved.relative_to(root)- except ValueError:- continue+ for resolved in _iter_report_files_for_campaign(+ campaign_id=campaign_id,+ campaign=campaign,+ ):stat = resolved.stat()reports.append({- "filename": path.name,- "format": path.suffix.lstrip(".").lower(),+ "filename": resolved.name,+ "format": resolved.suffix.lstrip(".").lower(),"size_bytes": stat.st_size,"modified_at": stat.st_mtime,}@@ -1961,6 +1980,39 @@ async def list_reports(return {"campaign_id": campaign_id, "reports": reports}[email protected]("/reports/{campaign_id}", tags=["reports"])+async def delete_reports(+ campaign_id: str,+ actor: AuthenticatedUser = _api_key_write_dep,+ db: AresDatabase = _db_dep,+) -> dict[str, Any]:+ campaign = await db.get_campaign(campaign_id)+ if not campaign:+ raise HTTPException(404, "Campaign not found")+ await _require_campaign_access(campaign, actor)+ deleted = 0+ for path in _iter_report_files_for_campaign(+ campaign_id=campaign_id,+ campaign=campaign,+ extensions=_REPORT_BULK_DELETE_EXTENSIONS,+ ):+ try:+ path.unlink()+ except OSError as exc:+ logger.warning(+ "report_artifact_delete_failed", path=str(path), error=str(exc)+ )+ continue+ deleted += 1+ await db.audit(+ actor.username,+ "reports_deleted",+ f"count={deleted}",+ campaign_id,+ )+ return {"status": "deleted", "campaign_id": campaign_id, "deleted": deleted}++@app.get("/reports/{campaign_id}/files/{filename}", tags=["reports"])async def download_report(campaign_id: str,@@ -1976,6 +2028,34 @@ async def download_report(return FileResponse(path, filename=path.name)[email protected]("/reports/{campaign_id}/files/{filename}", tags=["reports"])+async def delete_report(+ campaign_id: str,+ filename: str,+ actor: AuthenticatedUser = _api_key_write_dep,+ db: AresDatabase = _db_dep,+) -> dict[str, str]:+ campaign = await db.get_campaign(campaign_id)+ if not campaign:+ raise HTTPException(404, "Campaign not found")+ await _require_campaign_access(campaign, actor)+ path = _safe_report_file_path(filename, campaign_id=campaign_id, campaign=campaign)+ try:+ path.unlink()+ except FileNotFoundError:+ raise HTTPException(404, "Report not found") from None+ except OSError as exc:+ logger.warning("report_artifact_delete_failed", path=str(path), error=str(exc))+ raise HTTPException(500, "Report could not be deleted") from exc+ await db.audit(+ actor.username,+ "report_deleted",+ f"filename={path.name}",+ campaign_id,+ )+ return {"status": "deleted", "campaign_id": campaign_id, "filename": path.name}++# ── Telemetry ─────────────────────────────────────────────────────────────────diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 9dfb095..134eee8 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1255,6 +1255,7 @@ function ReportsPage() {const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });const [format, setFormat] = useSessionState("ares.dashboard.reports.format", "html");const [warning, setWarning] = useState("");+ const [libraryError, setLibraryError] = useState("");const [lastGenerateResult, setLastGenerateResult] = useSessionState<PersistedResult | null>("ares.dashboard.reports.lastGenerate", null);const [activeTab, setActiveTab] = useSessionState("ares.dashboard.reports.tab", "Generate");const queryClient = useQueryClient();@@ -1263,6 +1264,7 @@ function ReportsPage() {queryFn: () => api.reports(campaignId),enabled: Boolean(campaignId)});+ const reportItems = reports.data?.reports ?? [];const reportResultKey = `${campaignId}:${format}`;const generate = useMutation({mutationFn: () => api.generateReport(campaignId, format),@@ -1292,6 +1294,38 @@ function ReportsPage() {window.setTimeout(() => URL.revokeObjectURL(url), 1000);}});+ const deleteReport = useMutation({+ mutationFn: (item: ReportItem) => api.deleteReport(campaignId, item.filename),+ onSuccess: (_payload, item) => {+ queryClient.setQueryData<{ campaign_id: string; reports: ReportItem[] }>(+ ["reports", campaignId],+ (current) => current+ ? {+ ...current,+ reports: current.reports.filter((report) => report.filename !== item.filename)+ }+ : current+ );+ setLibraryError("");+ },+ onError: (error) => {+ setLibraryError(readableError(error, "Report could not be deleted."));+ }+ });+ const clearReports = useMutation({+ mutationFn: () => api.clearReports(campaignId),+ onSuccess: () => {+ queryClient.setQueryData<{ campaign_id: string; reports: ReportItem[] }>(+ ["reports", campaignId],+ (current) => current ? { ...current, reports: [] } : current+ );+ setLibraryError("");+ },+ onError: (error) => {+ setLibraryError(readableError(error, "Report library could not be cleared."));+ }+ });+ const deleteDisabled = deleteReport.isPending || clearReports.isPending;return (<Pagetitle="Reports"@@ -1349,28 +1383,69 @@ function ReportsPage() {)}{activeTab === "Library" && (<section className="panel table-panel">- <SectionHeader title="Report Library" />+ <SectionHeader+ title="Report Library"+ action={campaignId && reportItems.length > 0 ? (+ <button+ className="btn btn-danger"+ disabled={deleteDisabled}+ onClick={() => {+ if (!window.confirm(`Delete all ${reportItems.length} report artifacts for this campaign? This cannot be undone.`)) {+ return;+ }+ setLibraryError("");+ clearReports.mutate();+ }}+ >+ {clearReports.isPending ? (+ <Loader2 className="spin" size={15} />+ ) : (+ <Trash2 size={15} />+ )}+ Delete all+ </button>+ ) : null}+ /><div className="table-scroll"><table className="table"><thead><tr><th>Filename</th><th>Format</th><th>Size</th><th>Modified</th><th>Actions</th></tr></thead><tbody>- {(reports.data?.reports ?? []).map((item) => (+ {reportItems.map((item) => (<tr key={item.filename}><td className="font-medium text-slate-900">{item.filename}</td><td><span className="badge">{item.format}</span></td><td>{formatBytes(item.size_bytes)}</td><td>{formatReportDate(item.modified_at)}</td><td>- <button className="btn" disabled={download.isPending} onClick={() => download.mutate(item)}>+ <button className="btn" disabled={download.isPending || deleteDisabled} onClick={() => download.mutate(item)}><Download size={15} /> Download</button>+ <button+ className="btn btn-danger"+ disabled={deleteDisabled}+ onClick={() => {+ if (!window.confirm(`Delete report artifact "${item.filename}"? This cannot be undone.`)) {+ return;+ }+ setLibraryError("");+ deleteReport.mutate(item);+ }}+ >+ <Trash2 size={15} /> Delete+ </button></td></tr>))}</tbody></table></div>- {campaignId && (reports.data?.reports ?? []).length === 0 && (+ {libraryError && (+ <p className="notice notice-danger mt-3">+ <AlertTriangle size={16} />+ {libraryError}+ </p>+ )}+ {campaignId && reportItems.length === 0 && (<EmptyState text="No reports generated for this campaign yet." />)}{!campaignId && <EmptyState text="Select a campaign to list reports." />}@@ -3185,6 +3260,22 @@ function serializeError(value: unknown): unknown {return value;}+function readableError(value: unknown, fallback: string): string {+ if (value instanceof ApiError) {+ if (typeof value.detail === "string") {+ return value.detail;+ }+ return value.message || fallback;+ }+ if (value instanceof Error) {+ return value.message || fallback;+ }+ if (typeof value === "string") {+ return value;+ }+ return fallback;+}+function pdfFailureHint(value: unknown): string {if (!value) return "";const serialized = serializeError(value);diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex 0a62738..32e58f7 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -206,6 +206,16 @@ export const api = {`/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`,downloadReport: (campaignId: string, filename: string) =>apiBlobRequest(`/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`),+ deleteReport: (campaignId: string, filename: string) =>+ apiRequest<Record<string, string>>(+ `/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`,+ { method: "DELETE" }+ ),+ clearReports: (campaignId: string) =>+ apiRequest<{ status: string; campaign_id: string; deleted: number }>(+ `/reports/${encodeURIComponent(campaignId)}`,+ { method: "DELETE" }+ ),graph: (campaignId: string) => apiRequest<Record<string, any>>(`/graph/${encodeURIComponent(campaignId)}`),attackPaths: (campaignId: string) =>apiRequest<Record<string, any>>(`/graph/${encodeURIComponent(campaignId)}/attack-paths`),diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex 1e9a9b4..996ced3 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -1391,3 +1391,163 @@ class TestReportEndpoints:)assert r.status_code == 200assert r.text == "owned report"++ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_report_delete_existing_file_succeeds(+ self, aclient: Any, tmp_path: Any, monkeypatch: Any+ ) -> None:+ c, db, _ = aclient+ import ares.api.server as server++ campaign_id = "camp-123"+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": campaign_id,+ "name": "Acme",+ "operator": "admin",+ }+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())+ report = tmp_path / f"{campaign_id}_Acme_20260101_0000.pdf"+ report.write_bytes(b"%PDF-1.4\n")++ r = await c.delete(+ f"/reports/{campaign_id}/files/{report.name}",+ headers=_auth("admin", "team_lead"),+ )++ assert r.status_code == 200+ assert r.json()["filename"] == report.name+ assert not report.exists()++ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_report_delete_missing_file_returns_404(+ self, aclient: Any, tmp_path: Any, monkeypatch: Any+ ) -> None:+ c, db, _ = aclient+ import ares.api.server as server++ campaign_id = "camp-123"+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": campaign_id,+ "name": "Acme",+ "operator": "admin",+ }+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())++ r = await c.delete(+ f"/reports/{campaign_id}/files/{campaign_id}_Acme_missing.pdf",+ headers=_auth("admin", "team_lead"),+ )++ assert r.status_code == 404++ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_report_delete_rejects_path_traversal(+ self, aclient: Any, tmp_path: Any, monkeypatch: Any+ ) -> None:+ c, db, _ = aclient+ import ares.api.server as server++ campaign_id = "camp-123"+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": campaign_id,+ "name": "Acme",+ "operator": "admin",+ }+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())++ r = await c.delete(+ f"/reports/{campaign_id}/files/%2e%2e%5csecret.pdf",+ headers=_auth("admin", "team_lead"),+ )++ assert r.status_code == 400++ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_report_delete_rejects_absolute_path(+ self, aclient: Any, tmp_path: Any, monkeypatch: Any+ ) -> None:+ c, db, _ = aclient+ import ares.api.server as server++ campaign_id = "camp-123"+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": campaign_id,+ "name": "Acme",+ "operator": "admin",+ }+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())++ r = await c.delete(+ f"/reports/{campaign_id}/files/C%3A%5Csecret.pdf",+ headers=_auth("admin", "team_lead"),+ )++ assert r.status_code == 400++ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_report_delete_rejects_nested_path(+ self, aclient: Any, tmp_path: Any, monkeypatch: Any+ ) -> None:+ c, db, _ = aclient+ import ares.api.server as server++ campaign_id = "camp-123"+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": campaign_id,+ "name": "Acme",+ "operator": "admin",+ }+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())++ r = await c.delete(+ f"/reports/{campaign_id}/files/nested%5Creport.pdf",+ headers=_auth("admin", "team_lead"),+ )++ assert r.status_code == 400++ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_report_delete_bulk_deletes_only_allowed_campaign_artifacts(+ self, aclient: Any, tmp_path: Any, monkeypatch: Any+ ) -> None:+ c, db, _ = aclient+ import ares.api.server as server++ campaign_id = "camp-123"+ db.is_access_token_revoked.return_value = False+ db.get_campaign.return_value = {+ "id": campaign_id,+ "name": "Acme",+ "operator": "admin",+ }+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())+ owned_pdf = tmp_path / f"{campaign_id}_Acme_20260101_0000.pdf"+ owned_json = tmp_path / f"{campaign_id}_Acme_20260101_0000.json"+ owned_html = tmp_path / f"{campaign_id}_Acme_20260101_0000.html"+ owned_md = tmp_path / f"{campaign_id}_Acme_20260101_0000.md"+ owned_txt = tmp_path / f"{campaign_id}_Acme_20260101_0000.txt"+ other = tmp_path / "other_Acme_20260101_0000.pdf"+ report_dir = tmp_path / f"{campaign_id}_Acme_20260101_0000.pdf.dir"+ report_dir.mkdir()+ for path in (owned_pdf, owned_json, owned_html, owned_md, owned_txt, other):+ path.write_text("artifact", encoding="utf-8")++ r = await c.delete(+ f"/reports/{campaign_id}",+ headers=_auth("admin", "team_lead"),+ )++ assert r.status_code == 200+ assert r.json()["deleted"] == 4+ assert not owned_pdf.exists()+ assert not owned_json.exists()+ assert not owned_html.exists()+ assert not owned_md.exists()+ assert owned_txt.exists()+ assert other.exists()+ assert report_dir.exists()