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
fix: harden dashboard workflow and module guidance
Mafifrizi28d166cdd831
diff --git a/ares/api/server.py b/ares/api/server.pyindex b02034f..1903dbb 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -1212,6 +1212,16 @@ async def list_modules(return enriched[email protected]("/modules/execution-chains", tags=["modules"])+async def list_execution_chains(+ actor: AuthenticatedUser = _api_key_read_dep,+) -> list[dict[str, Any]]:+ """Return read-only execution-chain guidance for the Modules page."""+ from ares.core.execution_chains import list_execution_chains as get_chains++ return get_chains()++class RunRequest(BaseModel):campaign_id: strparams: dict[str, Any] = {}@@ -2069,6 +2079,15 @@ async def delete_report(# ── Telemetry ─────────────────────────────────────────────────────────────────[email protected]("/stats/monthly", tags=["telemetry"])+async def get_monthly_stats(+ actor: AuthenticatedUser = _api_key_read_dep,+ db: AresDatabase = Depends(get_db),+) -> dict[str, Any]:+ """Return confirmed findings grouped by day in the current calendar month."""+ return await db.get_monthly_confirmed_finding_stats()++@app.get("/telemetry", tags=["telemetry"])async def get_telemetry(actor: AuthenticatedUser = _api_key_read_dep,diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.pyindex 26ff29d..2836280 100644--- a/ares/cli/typer_main.py+++ b/ares/cli/typer_main.py@@ -1546,9 +1546,18 @@ def build_frontend_command(npm_command: str, ui_host: str, ui_port: int) -> listui_host,"--port",str(ui_port),+ "--strictPort",]+def is_port_in_use(host: str, port: int, *, timeout_seconds: float = 0.5) -> bool:+ try:+ with socket.create_connection((host, port), timeout=timeout_seconds):+ return True+ except OSError:+ return False++def wait_for_port(host: str, port: int, *, timeout_seconds: float = 30.0) -> bool:deadline = time.monotonic() + timeout_secondswhile time.monotonic() < deadline:@@ -1814,6 +1823,7 @@ def _run_dashboard_dev(os_name: str | None = None,popen_factory: Callable[..., subprocess.Popen] = subprocess.Popen,run_func: Callable[..., subprocess.CompletedProcess] = subprocess.run,+ port_in_use_func: Callable[[str, int], bool] = is_port_in_use,wait_for_port_func: Callable[..., bool] = wait_for_port,open_browser_func: Callable[[str], object] = webbrowser.open,sleep_func: Callable[[float], object] = time.sleep,@@ -1824,6 +1834,21 @@ def _run_dashboard_dev(console.print(f"[red]Frontend directory not found:[/red] {frontend_dir}")raise typer.Exit(1)+ for label, host, port in (+ ("backend", api_host, api_port),+ ("frontend", ui_host, ui_port),+ ):+ if port_in_use_func(host, port):+ console.print(f"[red]Cannot start dashboard: {label} port {host}:{port} is already occupied.[/red]")+ console.print(+ "[yellow]Likely cause: a stale Python or Node dashboard process is still running.[/yellow]"+ )+ console.print(+ "Cleanup suggestion: Get-Process python,node -ErrorAction SilentlyContinue "+ "| Stop-Process -Force -ErrorAction SilentlyContinue"+ )+ raise typer.Exit(1)+npm_command = resolve_npm_command(os_name=os_name)_ensure_frontend_dependencies(frontend_dir,@@ -1882,12 +1907,13 @@ def _run_dashboard_dev(threads.append(thread)if open_browser:- if wait_for_port_func(ui_host, ui_port, timeout_seconds=30.0):- console.print(f"[green]Opening dashboard:[/green] {dashboard_url}")- else:+ if not wait_for_port_func(ui_host, ui_port, timeout_seconds=30.0):console.print(- "[yellow]Dashboard port was not ready yet; opening the URL anyway.[/yellow]"+ f"[red]Frontend did not become ready on {ui_host}:{ui_port}; "+ "dashboard was not opened.[/red]")+ return 1+ console.print(f"[green]Opening dashboard:[/green] {dashboard_url}")open_browser_func(dashboard_url)else:console.print("[dim]Browser open skipped because --no-open was provided.[/dim]")diff --git a/ares/core/execution_chains.py b/ares/core/execution_chains.pynew file mode 100644index 0000000..48b9845--- /dev/null+++ b/ares/core/execution_chains.py@@ -0,0 +1,429 @@+"""Read-only execution-chain guidance for the Modules experience."""++from __future__ import annotations++from copy import deepcopy+from typing import Any, Final, TypedDict+++class ExecutionChainStage(TypedDict):+ order: int+ title: str+ module_ids: list[str]+ purpose: str+ required_inputs: list[str]+ uses_previous_output: bool+ produces: list[str]+ next_action: str+ final_goal: bool+++class ExecutionChain(TypedDict):+ id: str+ title: str+ category: str+ description: str+ stages: list[ExecutionChainStage]+++MODULE_EXECUTION_CHAINS: Final[tuple[ExecutionChain, ...]] = (+ {+ "id": "ad-kerberos-exposure-chain",+ "title": "AD Kerberos Exposure Chain",+ "category": "Active Directory",+ "description": "Move from account and SPN discovery to targeted Kerberos evidence and reporting.",+ "stages": [+ {+ "order": 1,+ "title": "Enumerate users and AS-REP exposure",+ "module_ids": ["ad.enum_users", "ad.asreproast"],+ "purpose": "Establish user context and identify accounts that may return AS-REP evidence.",+ "required_inputs": ["dc", "domain", "username", "password"],+ "uses_previous_output": False,+ "produces": ["domain user context", "AS-REP candidates or confirmed evidence"],+ "next_action": "Review the user results, then enumerate service principals.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Enumerate service principals",+ "module_ids": ["ad.enum_spn"],+ "purpose": "Find Kerberoastable service accounts and SPN candidates.",+ "required_inputs": ["dc", "domain", "username", "password"],+ "uses_previous_output": True,+ "produces": ["service account and SPN candidates"],+ "next_action": "Choose one discovered service account or SPN for the targeted step.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Request one targeted service ticket",+ "module_ids": ["ad.kerberoast"],+ "purpose": "Request evidence for a selected candidate without broad ticket collection.",+ "required_inputs": ["dc", "domain", "username", "password", "target_user"],+ "uses_previous_output": True,+ "produces": ["confirmed TGS hash evidence when capture succeeds"],+ "next_action": "Run ad.enum_spn first, then set target_user to a discovered account or SPN and run the module.",+ "final_goal": False,+ },+ {+ "order": 4,+ "title": "Export campaign evidence",+ "module_ids": [],+ "purpose": "Review confirmed findings, confidence, remediation, and redacted evidence.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["JSON, HTML, Markdown, or PDF report artifact"],+ "next_action": "Open Reports, generate the required format, and review the library.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "ad-domain-enumeration-chain",+ "title": "AD Domain Enumeration Chain",+ "category": "Active Directory",+ "description": "Build a scoped domain inventory, then review access-control and identity exposure evidence.",+ "stages": [+ {+ "order": 1,+ "title": "Build the domain inventory",+ "module_ids": ["ad.enum_users", "ad.enum_computers", "ad.enum_spn"],+ "purpose": "Collect the users, computers, and service principals needed for an initial inventory.",+ "required_inputs": ["dc", "domain", "username", "password"],+ "uses_previous_output": False,+ "produces": ["domain accounts, computers, and SPN inventory"],+ "next_action": "Review inventory coverage before selecting exposure checks.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Review access and identity exposure",+ "module_ids": ["ad.enum_acl", "ad.adcs", "ad.laps_enum"],+ "purpose": "Check delegated access, certificate services, and password-management exposure.",+ "required_inputs": ["dc", "domain", "username", "password"],+ "uses_previous_output": True,+ "produces": ["access-control and identity exposure evidence"],+ "next_action": "Validate any material exposure with the authorized campaign scope.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Validate domain abuse paths",+ "module_ids": ["ad.coerce", "ad.dcsync", "ad.delegation_abuse", "ad.sccm"],+ "purpose": "Use the inventory to assess explicitly authorized delegation, replication, coercion, or SCCM paths.",+ "required_inputs": ["dc", "domain", "username", "password"],+ "uses_previous_output": True,+ "produces": ["validated domain exposure evidence or controlled outcomes"],+ "next_action": "Review results and retain only confirmed, authorized findings.",+ "final_goal": False,+ },+ {+ "order": 4,+ "title": "Report the domain inventory",+ "module_ids": [],+ "purpose": "Package the inventory and confirmed exposure evidence for review.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["domain inventory report"],+ "next_action": "Generate a report from the Reports page.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "web-api-exposure-chain",+ "title": "Web/API Exposure Chain",+ "category": "Web and Network",+ "description": "Identify reachable services, fingerprint exposed HTTP surfaces, and review confirmed evidence.",+ "stages": [+ {+ "order": 1,+ "title": "Fingerprint the target environment",+ "module_ids": ["recon.fingerprint"],+ "purpose": "Establish the target technology and environment context.",+ "required_inputs": ["target"],+ "uses_previous_output": False,+ "produces": ["target environment context"],+ "next_action": "Use the target context to scope network discovery.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Discover reachable services",+ "module_ids": ["network.dns_enum", "network.port_scan", "network.service_detect"],+ "purpose": "Resolve the target and identify services inside the campaign scope.",+ "required_inputs": ["target"],+ "uses_previous_output": True,+ "produces": ["resolved hosts, ports, and services"],+ "next_action": "Select authorized HTTP/API surfaces for focused validation.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Validate HTTP and API surfaces",+ "module_ids": ["network.http_fingerprint"],+ "purpose": "Fingerprint web responses and API exposure on discovered services.",+ "required_inputs": ["target"],+ "uses_previous_output": True,+ "produces": ["web/API evidence and service details"],+ "next_action": "Review findings and generate a campaign report.",+ "final_goal": False,+ },+ {+ "order": 4,+ "title": "Export confirmed evidence",+ "module_ids": [],+ "purpose": "Collect validated web/API observations in the campaign report.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["web/API exposure report"],+ "next_action": "Open Reports and generate the required format.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "cloud-exposure-chain",+ "title": "Cloud Exposure Chain",+ "category": "Cloud",+ "description": "Inventory cloud services, review identity paths, and package confirmed cloud exposure evidence.",+ "stages": [+ {+ "order": 1,+ "title": "Inventory cloud services",+ "module_ids": ["cloud.aws", "cloud.azure", "cloud.gcp", "cloud.azure_ad"],+ "purpose": "Collect the cloud account and identity context available to the authorized assessment.",+ "required_inputs": ["provider credentials or token", "scope"],+ "uses_previous_output": False,+ "produces": ["cloud account and service inventory"],+ "next_action": "Review the inventory and select identity paths for validation.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Review privilege and federation paths",+ "module_ids": ["cloud.aws_privesc", "cloud.identity_federation_abuse"],+ "purpose": "Assess explicitly authorized privilege and federation exposure using the collected context.",+ "required_inputs": ["provider credentials or token", "scope"],+ "uses_previous_output": True,+ "produces": ["cloud identity and privilege evidence"],+ "next_action": "Validate material observations and review remediation.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Report cloud exposure",+ "module_ids": [],+ "purpose": "Package confirmed cloud observations and remediation guidance.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["cloud exposure report"],+ "next_action": "Generate a report from the Reports page.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "credential-secret-exposure-chain",+ "title": "Credential / Secret Exposure Chain",+ "category": "Credentials",+ "description": "Review credential and secret exposure paths with explicit authorization and evidence handling.",+ "stages": [+ {+ "order": 1,+ "title": "Review credential reuse and strength",+ "module_ids": ["credential.reuse", "credential.crack"],+ "purpose": "Assess authorized credential material for reuse or recoverability.",+ "required_inputs": ["campaign scope", "authorized credential material"],+ "uses_previous_output": False,+ "produces": ["credential exposure observations"],+ "next_action": "Review results before any higher-impact credential operation.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Validate credential access paths",+ "module_ids": ["credential.pass_spray", "credential.pass_the_hash", "credential.golden_ticket"],+ "purpose": "Assess only explicitly approved credential paths under the existing RBAC and OPSEC controls.",+ "required_inputs": ["campaign scope", "authorized credential material"],+ "uses_previous_output": True,+ "produces": ["controlled credential-path outcomes"],+ "next_action": "Stop on blocked or operator-error outcomes and review the evidence.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Review secret-bearing artifacts",+ "module_ids": ["exfil.secrets_scan", "windows.dpapi", "windows.lsa_secrets", "windows.lsass_dump", "windows.registry_enum", "windows.token_impersonation"],+ "purpose": "Inspect authorized artifacts for secret exposure while retaining redaction and cleanup controls.",+ "required_inputs": ["target", "authorized artifact context"],+ "uses_previous_output": True,+ "produces": ["redacted secret exposure evidence"],+ "next_action": "Review confirmed evidence and remediation without exporting raw secrets.",+ "final_goal": False,+ },+ {+ "order": 4,+ "title": "Report credential exposure",+ "module_ids": [],+ "purpose": "Export findings with sensitive evidence redacted by default.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["credential exposure report"],+ "next_action": "Generate and review the report library.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "opsec-safety-chain",+ "title": "OPSEC / Safety Chain",+ "category": "Safety",+ "description": "Review campaign coverage and planning context before authorized module execution.",+ "stages": [+ {+ "order": 1,+ "title": "Review OPSEC coverage",+ "module_ids": ["opsec.coverage_predictor"],+ "purpose": "Understand expected noise, coverage, and guardrail implications for the campaign.",+ "required_inputs": ["campaign", "selected modules"],+ "uses_previous_output": False,+ "produces": ["coverage and safety review"],+ "next_action": "Use the review to choose dry-run and authorized execution settings.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Review the execution plan",+ "module_ids": ["ai.autonomous_planner"],+ "purpose": "Review planning suggestions as operator context; execution remains manual and policy-controlled.",+ "required_inputs": ["campaign", "objective"],+ "uses_previous_output": True,+ "produces": ["operator-reviewed plan context"],+ "next_action": "Keep manual selection and approval at the Modules run panel.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Confirm safe evidence handling",+ "module_ids": [],+ "purpose": "Confirm scope, authorization, redaction, and report handling before closing the workflow.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["operator safety decision"],+ "next_action": "Run only the selected authorized modules and review their outcomes.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "reporting-evidence-chain",+ "title": "Reporting / Evidence Chain",+ "category": "Evidence",+ "description": "Review module outcomes, export campaign reports, and keep the artifact library intentional.",+ "stages": [+ {+ "order": 1,+ "title": "Review module results",+ "module_ids": [],+ "purpose": "Check outcome category, findings, confidence, remediation, and next steps.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["reviewed campaign evidence"],+ "next_action": "Select the report format that matches the engagement need.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Generate report artifacts",+ "module_ids": [],+ "purpose": "Create JSON, HTML, Markdown, or PDF output from persisted campaign findings.",+ "required_inputs": ["campaign", "report format"],+ "uses_previous_output": True,+ "produces": ["report artifact in the campaign library"],+ "next_action": "Open the Library tab and download or remove authorized artifacts.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Close the evidence record",+ "module_ids": [],+ "purpose": "Confirm the report contains the intended evidence and no raw secret material.",+ "required_inputs": ["campaign"],+ "uses_previous_output": True,+ "produces": ["final campaign report"],+ "next_action": "Retain only the artifacts required by the authorized engagement.",+ "final_goal": True,+ },+ ],+ },+ {+ "id": "standalone-utilities",+ "title": "Standalone Utilities",+ "category": "Utilities",+ "description": "Focused modules that do not belong to a single ordered family chain; select them manually with the normal safeguards.",+ "stages": [+ {+ "order": 1,+ "title": "Network and pivot utilities",+ "module_ids": ["network.pivot", "network.snmp_enum"],+ "purpose": "Use focused network utilities when the engagement requires a specific capability.",+ "required_inputs": ["target", "campaign scope"],+ "uses_previous_output": False,+ "produces": ["focused network observations"],+ "next_action": "Review the result and choose the next manual module.",+ "final_goal": False,+ },+ {+ "order": 2,+ "title": "Lateral movement utilities",+ "module_ids": ["lateral.dcom", "lateral.mssql", "lateral.ntlm_relay", "lateral.psexec", "lateral.rdp", "lateral.smb_relay", "lateral.ssh_pivot", "lateral.winrm", "lateral.wmiexec"],+ "purpose": "Run only a specifically authorized lateral capability from the manual catalog.",+ "required_inputs": ["target", "campaign scope", "authorized credentials"],+ "uses_previous_output": False,+ "produces": ["focused lateral outcome"],+ "next_action": "Review the result and return to the catalog for the next approved step.",+ "final_goal": False,+ },+ {+ "order": 3,+ "title": "Linux host utilities",+ "module_ids": ["linux.container", "linux.kernel_suggester", "linux.ld_preload", "linux.nfs_escape", "linux.privesc", "linux.service_hijack"],+ "purpose": "Use focused Linux host checks under the campaign scope and existing guardrails.",+ "required_inputs": ["target", "campaign scope"],+ "uses_previous_output": False,+ "produces": ["focused Linux host observations"],+ "next_action": "Review the result and select the next manual module if needed.",+ "final_goal": False,+ },+ {+ "order": 4,+ "title": "Windows and persistence utilities",+ "module_ids": ["persistence.registry_run", "persistence.scheduled_task", "persistence.wmi_subscription", "windows.applocker_bypass", "windows.scheduled_tasks_enum", "windows.uac_bypass"],+ "purpose": "Use focused Windows or persistence checks only when explicitly authorized.",+ "required_inputs": ["target", "campaign scope"],+ "uses_previous_output": False,+ "produces": ["focused Windows or persistence outcome"],+ "next_action": "Review the result and retain only confirmed evidence.",+ "final_goal": False,+ },+ {+ "order": 5,+ "title": "EDR and collection utilities",+ "module_ids": ["edr.bypass_adaptive", "exfil.smb_shares", "exfil.staged_collection"],+ "purpose": "Keep specialized EDR or collection modules available for approved manual use.",+ "required_inputs": ["target", "campaign scope", "authorization"],+ "uses_previous_output": False,+ "produces": ["focused specialized outcome"],+ "next_action": "Review the result, redaction, and campaign evidence handling.",+ "final_goal": True,+ },+ ],+ },+)+++def list_execution_chains() -> list[dict[str, Any]]:+ """Return isolated chain metadata so callers cannot mutate definitions."""+ return deepcopy(list(MODULE_EXECUTION_CHAINS))diff --git a/ares/db/database.py b/ares/db/database.pyindex 9b5f4b4..24d32a1 100644--- a/ares/db/database.py+++ b/ares/db/database.py@@ -436,6 +436,33 @@ class AresDatabase:stats["total"] += r["n"]return stats+ async def get_monthly_confirmed_finding_stats(self) -> dict[str, Any]:+ """Return confirmed findings grouped by day in the current UTC month."""+ period = datetime.now(timezone.utc).strftime("%Y-%m")+ async with self._conn.execute(+ """+ SELECT substr(discovered_at, 1, 10) AS finding_date, COUNT(*) AS n+ FROM findings+ WHERE validated=1+ AND false_positive=0+ AND substr(discovered_at, 1, 7)=?+ GROUP BY substr(discovered_at, 1, 10)+ ORDER BY finding_date+ """,+ (period,),+ ) as cur:+ rows = await cur.fetchall()+ series = [+ {"date": str(row["finding_date"]), "count": int(row["n"])}+ for row in rows+ ]+ return {+ "period": period,+ "label": "Security signals this cycle",+ "total": sum(item["count"] for item in series),+ "series": series,+ }+async def campaign_summary(self, campaign_id: str) -> dict[str, Any]:"""High-level stats for a campaign."""findings = await self.get_findings(campaign_id)diff --git a/ares/db/postgres.py b/ares/db/postgres.pyindex f411c3e..0700e0e 100644--- a/ares/db/postgres.py+++ b/ares/db/postgres.py@@ -422,6 +422,42 @@ class PostgresDatabase:stats["total"] += r["n"]return stats+ async def get_monthly_confirmed_finding_stats(self) -> dict[str, Any]:+ """Return confirmed findings grouped by day in the current UTC month."""+ now = datetime.now(timezone.utc)+ period_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)+ if period_start.month == 12:+ next_month = period_start.replace(year=period_start.year + 1, month=1)+ else:+ next_month = period_start.replace(month=period_start.month + 1)+ period = period_start.strftime("%Y-%m")+ async with self._pool.acquire() as conn:+ rows = await conn.fetch(+ """+ SELECT (discovered_at AT TIME ZONE 'UTC')::date AS finding_date,+ COUNT(*) AS n+ FROM findings+ WHERE validated=1+ AND false_positive=0+ AND discovered_at >= $1+ AND discovered_at < $2+ GROUP BY 1+ ORDER BY 1+ """,+ period_start,+ next_month,+ )+ series = [+ {"date": row["finding_date"].isoformat(), "count": int(row["n"])}+ for row in rows+ ]+ return {+ "period": period,+ "label": "Security signals this cycle",+ "total": sum(item["count"] for item in series),+ "series": series,+ }+# ── Hosts ──────────────────────────────────────────────────────────────────async def upsert_host(self, h: Any) -> str:diff --git a/ares/modules/ad/kerberoast.py b/ares/modules/ad/kerberoast.pyindex d0a13ab..93005a4 100644--- a/ares/modules/ad/kerberoast.py+++ b/ares/modules/ad/kerberoast.py@@ -48,6 +48,26 @@ def format_kerberos_clock_skew() -> str:)+def format_kerberoast_target_required() -> str:+ return (+ "ad.kerberoast requires a specific target user or SPN. Run ad.enum_spn "+ "first, choose a Kerberoastable service account such as svc-sql or an "+ "SPN such as MSSQLSvc/sql01.lab.local:1433, then rerun ad.kerberoast "+ "with target set."+ )+++def _require_kerberoast_target(target_user: Any) -> str:+ target = str(target_user or "").strip()+ if not target:+ raise ModuleValidationError(+ format_kerberoast_target_required(),+ module_id="ad.kerberoast",+ field="target_user",+ )+ return target++def is_kerberos_clock_skew(exc: BaseException) -> bool:error_text = f"{type(exc).__name__}: {exc}".lower()return "krb_ap_err_skew" in error_text or "clock skew too great" in error_text@@ -256,6 +276,7 @@ class KerberoastModule(BaseModule):"pass 'username'/'password' in params or provide a vault credential.",module_id=self.MODULE_ID, field="username",)+ _require_kerberoast_target(ctx.params.get("target_user"))noise = getattr(getattr(ctx, "campaign", None), "noise_profile", None)if noise == NoiseProfile.STEALTH:raise ModuleValidationError(@@ -270,7 +291,7 @@ class KerberoastModule(BaseModule):from ares.modules.base import ModuleResultad = self._extract_ad_params(ctx)dc, domain, username, password = ad["dc"], ad["domain"], ad["username"], ad["password"]- target_user = ctx.params.get("target_user")+ target_user = _require_kerberoast_target(ctx.params.get("target_user"))if getattr(ctx, "dry_run", False):return ModuleResult(status="dry_run", module_id=self.MODULE_ID,@@ -294,6 +315,7 @@ class KerberoastModule(BaseModule):@trace_module("ad.kerberoast")async def run(self, dc, username, password, domain, target_user=None, **kwargs):+ target_user = _require_kerberoast_target(target_user)ensure_ad_dependencies(("impacket", "pyasn1", "pyasn1_modules"),module_id=self.MODULE_ID,diff --git a/ares/modules/params.py b/ares/modules/params.pyindex 3cfff5a..72b69cb 100644--- a/ares/modules/params.py+++ b/ares/modules/params.py@@ -181,7 +181,7 @@ class DomainAuthParams(ModuleParams):class KerberoastParams(DomainAuthParams):target_user: str = param(- "Target specific user (default: all SPN accounts)",+ "Required target user or SPN; run ad.enum_spn first",required=False,default="",max_length=256,diff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.mdindex 11b22d7..f51a35f 100644--- a/docs/dashboard-guide.md+++ b/docs/dashboard-guide.md@@ -26,7 +26,7 @@ Windows virtualenv example:This one-terminal launcher starts:- Backend API: `python -m uvicorn ares.api.server:app --host 127.0.0.1 --port 8080 --reload`-- Frontend: `npm run dev -- --host 127.0.0.1 --port 5173`+- Frontend: `npm run dev -- --host 127.0.0.1 --port 5173 --strictPort`It prints `http://127.0.0.1:5173/dashboard/`, opens it by default, and stopsboth child processes when you press `Ctrl+C`. Login with username `admin` anddiff --git a/docs/modules.md b/docs/modules.mdindex 7b70451..daac1b1 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -28,6 +28,27 @@ The dashboard and API enforce authentication, RBAC, scope validation, parametervalidation, rate limits, and token revocation. The frontend is a conveniencelayer; the backend remains the enforcement boundary.+## Execution Chains inside Modules++The Modules page includes an **Execution Chains** section alongside the manual+module catalog. Chains are read-only execution guidance: they show an ordered+relationship between existing modules, the inputs each step needs, the output+that can feed the next step, and the final evidence goal. They do not auto-run+modules or replace campaign, RBAC, scope, OPSEC, or parameter validation.++The chains cover AD/domain, web/API, cloud, credential/secret, OPSEC/safety,+reporting/evidence, and standalone utility workflows. The **AD Kerberos+Exposure Chain** is the reference example: run `ad.enum_users` or+`ad.asreproast`, then `ad.enum_spn`, then select a discovered service account or+SPN for targeted `ad.kerberoast`, and finish by reviewing a campaign report.+Use a value such as `svc-sql` or `MSSQLSvc/sql01.lab.local:1433` for+`target_user`; an empty target is rejected before Kerberos work begins.++Manual module execution remains available for advanced operators. Selecting a+module chip in a chain only opens that module in the existing Run Panel; the+operator still supplies inputs, chooses dry-run or live execution, and submits+each step explicitly.+## Dry-Run and OutcomesThe module catalog is the source of truth for required and optional parameters,diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex c2290ba..88afaab 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,7 +1,5 @@import {- Activity,AlertTriangle,- BarChart3,Bell,Boxes,CheckCircle2,@@ -52,12 +50,14 @@ import {api,buildModuleRunPayload,campaignEventsPath,+ clearTokens,getAccessToken,getRefreshToken,login as loginRequest,- logout as logoutRequest+ logout as logoutRequest,+ refreshAccessToken} from "./api/client";-import type { ApiKeyMeta, Campaign, Finding, ModuleMeta, ParamField, ReportItem, UserProfile } from "./api/types";+import type { ApiKeyMeta, Campaign, ExecutionChain, Finding, ModuleMeta, MonthlyFindingStats, ParamField, ReportItem, UserProfile } from "./api/types";interface AuthState {user: UserProfile | null;@@ -215,23 +215,29 @@ function AuthProvider({ children }: { children: ReactNode }) {setLoading(false);return;}- api- .me()- .then((profile) => {+ (async () => {+ try {+ if (!(await refreshAccessToken())) {+ if (active) {+ setUser(null);+ }+ return;+ }+ const profile = await api.me();if (active) {setUser(profile);}- })- .catch(() => {+ } catch {+ clearTokens();if (active) {setUser(null);}- })- .finally(() => {+ } finally {if (active) {setLoading(false);}- });+ }+ })();return () => {active = false;};@@ -255,7 +261,11 @@ function AuthProvider({ children }: { children: ReactNode }) {[loading, queryClient, user]);- return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;+ return (+ <AuthContext.Provider value={value}>+ {loading ? <ScreenMessage title="ARES" body="Loading session" /> : children}+ </AuthContext.Provider>+ );}const navItems = [@@ -535,12 +545,13 @@ function ProtectedShell() {const notifications = useMemo<DashboardNotification[]>(() => {const items: DashboardNotification[] = [];const snapshot = telemetry.data as TelemetrySnapshot | undefined;- const healthStatus = String(health.data?.status ?? "").toLowerCase();+ const healthSnapshot = health.data as Record<string, unknown> | undefined;+ const healthStatus = String(healthSnapshot?.status ?? "").toLowerCase();if (health.isError) {items.push({ id: "health:error", title: "Backend health check failed", detail: "ARES API health is not reachable.", tone: "danger" });} else if (health.isSuccess && healthStatus && !["ok", "healthy", "online"].includes(healthStatus)) {- items.push({ id: `health:status:${healthStatus}`, title: "Backend status needs attention", detail: String(health.data?.status), tone: "warn" });+ items.push({ id: `health:status:${healthStatus}`, title: "Backend status needs attention", detail: String(healthSnapshot?.status), tone: "warn" });}if (telemetry.isError) {items.push({ id: "telemetry:error", title: "Telemetry unavailable", detail: "Runtime telemetry could not be loaded.", tone: "warn" });@@ -766,6 +777,7 @@ function ProtectedShell() {<div className="content-shell"><Routes><Route path="/" element={<OverviewPage />} />+ <Route path="/playbooks" element={<Navigate to="/modules" replace />} /><Route path="/campaigns" element={<CampaignsPage />} /><Route path="/modules" element={<ModulesPage />} /><Route path="/reports" element={<ReportsPage />} />@@ -836,26 +848,19 @@ function LoginPage() {}function OverviewPage() {- const health = useQuery({ queryKey: ["health"], queryFn: api.health });const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });+ const monthlyStats = useQuery({ queryKey: ["monthlyStats"], queryFn: api.monthlyStats });const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });const snapshot = telemetry.data as TelemetrySnapshot | undefined;+ const monthlyData = monthlyStats.data as MonthlyFindingStats | undefined;const campaignList = campaigns.data ?? [];const activeCampaigns = campaignList.filter((campaign) => String(campaign.status ?? "").toLowerCase() !== "deleted").length;const findings = typeof snapshot?.findings === "number" ? snapshot.findings : 0;+ const monthlyTotal = typeof monthlyData?.total === "number" ? monthlyData.total : 0;+ const monthlySeries = normalizeMonthlySeries(monthlyData?.period, monthlyData?.series);return (<Pagetitle="Overview"- actions={(- <>- <span className={health.isSuccess ? "status-pill status-low" : "status-pill status-medium"}>- <Activity size={13} /> {String(health.data?.status ?? "checking")}- </span>- <span className={telemetry.isSuccess ? "status-pill status-low" : "status-pill"}>- <BarChart3 size={13} /> {telemetry.isSuccess ? "Telemetry online" : "Telemetry pending"}- </span>- </>- )}><div className="dashboard-grid"><TelemetryPanel snapshot={snapshot} loading={telemetry.isLoading} />@@ -871,10 +876,17 @@ function OverviewPage() {<section className="panel p-4"><SectionHeader title="Monthly Statistics" /><div className="monthly-stat">- <span>+ {formatMetric(findings + activeCampaigns)}</span>- <small>Security signals this cycle</small>+ <span>{formatMetric(monthlyTotal)}</span>+ <small>{monthlyData?.label ?? "Security signals this cycle"}</small></div>- <SparklineBars values={[32, 44, 28, 52, 46, 62, 39, 48, 58, 42, 51, 67]} />+ {monthlyStats.isPending ? <p className="text-sm text-slate-500">Loading monthly activity...</p> : null}+ {monthlyStats.isError ? <p className="text-sm text-slate-500">Monthly activity unavailable.</p> : null}+ {!monthlyStats.isPending && !monthlyStats.isError && monthlyTotal === 0 ? (+ <p className="text-sm text-slate-500">No monthly activity yet</p>+ ) : null}+ {!monthlyStats.isPending && !monthlyStats.isError && monthlyTotal > 0 && monthlySeries.some((value) => value.count > 0) ? (+ <SparklineBars values={monthlySeries} />+ ) : null}</section></div></div>@@ -883,6 +895,29 @@ function OverviewPage() {);}+function normalizeMonthlySeries(+ period: string | undefined,+ series: MonthlyFindingStats["series"] | undefined+): MonthlyFindingStats["series"] {+ if (!period || !/^\d{4}-\d{2}$/.test(period)) return [];+ const [yearText, monthText] = period.split("-");+ const year = Number(yearText);+ const month = Number(monthText);+ if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) return [];++ const counts = new Map<string, number>();+ for (const item of series ?? []) {+ const count = Number(item.count);+ if (item.date && Number.isFinite(count)) counts.set(item.date, Math.max(0, count));+ }++ const daysInMonth = new Date(year, month, 0).getDate();+ return Array.from({ length: daysInMonth }, (_, index) => {+ const date = `${period}-${String(index + 1).padStart(2, "0")}`;+ return { date, count: counts.get(date) ?? 0 };+ });+}+function CampaignsPage() {const queryClient = useQueryClient();const { selectedCampaignId: selected, setSelectedCampaignId: setSelected } = useDashboardUi();@@ -1046,10 +1081,78 @@ function CampaignsPage() {);}+function ExecutionChainsPanel({+ chains,+ moduleIds,+ onSelectModule+}: {+ chains: ExecutionChain[];+ moduleIds: Set<string>;+ onSelectModule: (moduleId: string) => void;+}) {+ if (chains.length === 0) {+ return <EmptyState text="No execution chains are available." />;+ }+ return (+ <section className="grid gap-3">+ {chains.map((chain) => (+ <article className="panel p-4" key={chain.id}>+ <SectionHeader+ title={chain.title}+ eyebrow={chain.category}+ description={chain.description}+ action={<span className="badge">{chain.stages.length} stages</span>}+ />+ <div className="grid gap-3">+ {chain.stages.map((stage) => (+ <div className="compact-row" key={`${chain.id}-${stage.order}`}>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <span className="badge">Step {stage.order}</span>+ <strong>{stage.title}</strong>+ {stage.final_goal && <span className="badge badge-low">Final goal</span>}+ </div>+ <span className="text-xs font-medium text-slate-500">+ {stage.uses_previous_output ? "Uses prior output" : "Starts from campaign inputs"}+ </span>+ </div>+ <p className="mt-2 text-sm text-slate-600">{stage.purpose}</p>+ {stage.module_ids.length > 0 && (+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <strong className="text-sm">Run</strong>+ {stage.module_ids.map((moduleId) => (+ <button+ className="btn btn-compact"+ disabled={!moduleIds.has(moduleId)}+ key={moduleId}+ onClick={() => onSelectModule(moduleId)}+ title={moduleIds.has(moduleId) ? `Open ${moduleId} in the run panel` : "Module is not available in the current catalog"}+ type="button"+ >+ <Play size={13} /> {moduleId}+ </button>+ ))}+ </div>+ )}+ <div className="mt-3 grid gap-1 text-xs text-slate-500">+ <span><strong>Inputs:</strong> {stage.required_inputs.join(", ") || "none"}</span>+ <span><strong>Produces:</strong> {stage.produces.join("; ") || "none"}</span>+ <span><strong>Next:</strong> {stage.next_action}</span>+ </div>+ </div>+ ))}+ </div>+ </article>+ ))}+ </section>+ );+}+function ModulesPage() {const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });const modules = useQuery({ queryKey: ["modules"], queryFn: api.modules });+ const executionChains = useQuery({ queryKey: ["executionChains"], queryFn: api.executionChains });const [selectedId, setSelectedId] = useSessionState("ares.dashboard.modules.selectedId", "");const [search, setSearch] = useSessionState("ares.dashboard.modules.search", "");const [category, setCategory] = useSessionState("ares.dashboard.modules.category", "");@@ -1077,6 +1180,22 @@ function ModulesPage() {}});const list = modules.data ?? [];+ const moduleIds = useMemo(() => new Set(list.map((item) => item.id)), [list]);+ const relatedChainsByModule = useMemo(() => {+ const related = new Map<string, string[]>();+ for (const chain of executionChains.data ?? []) {+ for (const stage of chain.stages) {+ for (const moduleId of stage.module_ids) {+ const current = related.get(moduleId) ?? [];+ if (!current.includes(chain.title)) {+ current.push(chain.title);+ }+ related.set(moduleId, current);+ }+ }+ }+ return related;+ }, [executionChains.data]);const selected = list.find((item) => item.id === selectedId);const selectedCampaign = campaignDetail.data ?? (campaigns.data ?? []).find((item) => item.id === campaignId);const scopeWarning = moduleScopeWarning(selected, selectedCampaign, params, dryRun);@@ -1091,8 +1210,9 @@ function ModulesPage() {});const sensitive = isSensitiveModule(selected);const dryRunSupported = selected?.dry_run_supported !== false;+ const kerberoastTargetMissing = selected?.id === "ad.kerberoast" && !String(params.target_user ?? "").trim();const canRun = Boolean(campaignId && selectedId) && (!sensitive || confirmed) && !run.isPending && (!dryRun || dryRunSupported);- const runBlocked = !canRun || Boolean(scopeWarning);+ const runBlocked = !canRun || Boolean(scopeWarning) || kerberoastTargetMissing;const runHint = moduleRunHint(campaignId, selected, selectedCampaign, sensitive, confirmed, dryRun);const persistedRun = lastRunRecord?.campaignId === campaignId && lastRunRecord.moduleId === selectedId ? lastRunRecord : null;const runResult = (run.data ?? (!persistedRun?.isError ? persistedRun?.payload : undefined)) as Record<string, unknown> | undefined;@@ -1112,7 +1232,7 @@ function ModulesPage() {<Pagetitle="Modules"actions={<span className="status-pill">{visible.length} shown</span>}- tabs={["Catalog", "Run Panel", "Results"]}+ tabs={["Catalog", "Execution Chains", "Run Panel", "Results"]}activeTab={activeTab}onTabChange={setActiveTab}>@@ -1152,6 +1272,9 @@ function ModulesPage() {</div><div className="mt-2 flex flex-wrap gap-1">{(item.mitre_list ?? []).slice(0, 4).map((technique) => <span className="badge" key={technique}>{technique}</span>)}+ {(relatedChainsByModule.get(item.id) ?? []).slice(0, 2).map((chainTitle) => (+ <span className="badge" key={chainTitle}>Chain: {chainTitle}</span>+ ))}</div></button>))}@@ -1161,6 +1284,22 @@ function ModulesPage() {</div></section>)}+ {activeTab === "Execution Chains" && (+ <>+ {executionChains.isPending && <EmptyState text="Loading execution chains..." />}+ {executionChains.error && <DataPanel title="Execution Chain Error" data={executionChains.error} />}+ {!executionChains.isPending && !executionChains.error && (+ <ExecutionChainsPanel+ chains={executionChains.data ?? []}+ moduleIds={moduleIds}+ onSelectModule={(moduleId) => {+ setSelectedId(moduleId);+ setActiveTab("Run Panel");+ }}+ />+ )}+ </>+ )}{activeTab === "Run Panel" && (<section className="panel p-4"><SectionHeader@@ -1199,7 +1338,12 @@ function ModulesPage() {run.mutate();}}>- <ParamForm schema={selected.param_schema} values={params} onChange={setParams} />+ <ParamForm+ schema={selected.param_schema}+ values={params}+ onChange={setParams}+ requiredOverrides={selected.id === "ad.kerberoast" ? { target_user: true } : undefined}+ />{runHint && (<p className="notice">{runHint}@@ -2431,14 +2575,34 @@ function HighlightRow({);}-function SparklineBars({ values }: { values: number[] }) {- const max = Math.max(...values, 1);+function SparklineBars({ values }: { values: MonthlyFindingStats["series"] }) {+ const max = Math.max(...values.map((value) => value.count), 1);+ const labelDays = new Set([1, 7, 14, 21, 28, values.length]);return (- <div className="sparkline" aria-hidden="true">- {values.map((value, index) => (- <span key={`${value}-${index}`} style={{ height: `${Math.max(12, (value / max) * 100)}%` }} />- ))}- </div>+ <>+ <div className="sparkline" aria-hidden="true">+ {values.map((value) => (+ <span+ key={value.date}+ title={`${formatMonthlyDate(value.date)} — ${value.count} ${value.count === 1 ? "security signal" : "security signals"}`}+ style={{ height: value.count > 0 ? `${Math.max(6, (value.count / max) * 100)}%` : "0%" }}+ />+ ))}+ </div>+ <div className="sparkline-axis" aria-hidden="true">+ {values.map((value) => {+ const day = Number(value.date.slice(-2));+ return <span key={value.date}>{labelDays.has(day) ? formatMonthlyDate(value.date) : null}</span>;+ })}+ </div>+ </>+ );+}++function formatMonthlyDate(date: string): string {+ const [year, month, day] = date.split("-").map(Number);+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC" }).format(+ new Date(Date.UTC(year, month - 1, day)));}@@ -2875,11 +3039,13 @@ function LiveEventCard({ event, index }: { event: unknown; index: number }) {function ParamForm({schema,values,- onChange+ onChange,+ requiredOverrides}: {schema: ModuleMeta["param_schema"];values: Record<string, unknown>;onChange: (values: Record<string, unknown>) => void;+ requiredOverrides?: Record<string, boolean>;}) {const entries = Object.entries(schema ?? {});if (entries.length === 0) {@@ -2887,35 +3053,40 @@ function ParamForm({}return (<div className="grid gap-3">- {entries.map(([name, field]) => (- <label className="block text-sm font-semibold" key={name}>- <span className="flex items-center gap-2">- <span>- {name}- {field.required && <span className="text-red-700"> *</span>}+ {entries.map(([name, field]) => {+ const required = requiredOverrides?.[name] ?? field.required;+ const inputField = required === field.required ? field : { ...field, required };+ const description = fieldDescription(name, field);+ return (+ <label className="block text-sm font-semibold" key={name}>+ <span className="flex items-center gap-2">+ <span>+ {name}+ {required && <span className="text-red-700"> *</span>}+ </span>+ {!required && <span className="badge">optional</span>}</span>- {!field.required && <span className="badge">optional</span>}- </span>- <ParamInput- name={name}- field={field}- value={values[name]}- onChange={(value) => {- const next = { ...values };- if (!field.required && isEmptyParamValue(value)) {- delete next[name];- } else {- next[name] = value;- }- onChange(next);- }}- />- {field.description && <span className="mt-1 block text-xs text-slate-600">{field.description}</span>}- {fieldDefaultHint(field) && (- <span className="mt-1 block text-xs font-medium text-slate-500">{fieldDefaultHint(field)}</span>- )}- </label>- ))}+ <ParamInput+ name={name}+ field={inputField}+ value={values[name]}+ onChange={(value) => {+ const next = { ...values };+ if (!required && isEmptyParamValue(value)) {+ delete next[name];+ } else {+ next[name] = value;+ }+ onChange(next);+ }}+ />+ {description && <span className="mt-1 block text-xs text-slate-600">{description}</span>}+ {fieldDefaultHint(field) && (+ <span className="mt-1 block text-xs font-medium text-slate-500">{fieldDefaultHint(field)}</span>+ )}+ </label>+ );+ })}</div>);}@@ -2937,6 +3108,7 @@ function ParamInput({className="ml-2"type="checkbox"checked={Boolean(value)}+ required={field.required}onChange={(event) => onChange(event.target.checked)}/>);@@ -2995,6 +3167,9 @@ function paramPlaceholder(name: string, field: ParamField): string {}}const lower = name.toLowerCase();+ if (lower === "target_user" && field.description === "Required target user or SPN; run ad.enum_spn first") {+ return "svc-sql or MSSQLSvc/sql01.lab.local:1433";+ }if (lower.includes("target")) {return "127.0.0.1";}@@ -3007,6 +3182,13 @@ function paramPlaceholder(name: string, field: ParamField): string {return field.required ? "" : "Leave blank to use the module default";}+function fieldDescription(name: string, field: ParamField): string | undefined {+ if (name === "target_user" && field.description === "Required target user or SPN; run ad.enum_spn first") {+ return "Required target user or SPN; run ad.enum_spn first.";+ }+ return field.description;+}+function formatDefaultValue(value: unknown): string {if (value === undefined || value === null || value === "") {return "";diff --git a/frontend/src/api/client.test.ts b/frontend/src/api/client.test.tsindex 8d58f1f..98acf11 100644--- a/frontend/src/api/client.test.ts+++ b/frontend/src/api/client.test.ts@@ -5,13 +5,16 @@ import {clearTokens,getAccessToken,getRefreshToken,- login+ login,+ refreshAccessToken,+ setRefreshToken} from "./client";describe("api client auth", () => {beforeEach(() => {clearTokens();sessionStorage.clear();+ vi.unstubAllGlobals();vi.restoreAllMocks();});@@ -38,6 +41,38 @@ describe("api client auth", () => {expect(getAccessToken()).toBe("access");expect(getRefreshToken()).toBe("refresh");});++ it("refreshes the access token from the stored refresh token", async () => {+ setRefreshToken("refresh-old");+ const fetchMock = vi.fn(async (_path: string, init?: RequestInit) => {+ expect(init?.method).toBe("POST");+ expect(JSON.parse(String(init?.body))).toEqual({ refresh_token: "refresh-old" });+ return new Response(+ JSON.stringify({+ access_token: "access-new",+ refresh_token: "refresh-new",+ token_type: "bearer",+ expires_in: 3600,+ role: "operator"+ }),+ { status: 200 }+ );+ });+ vi.stubGlobal("fetch", fetchMock);++ await expect(refreshAccessToken()).resolves.toBe(true);+ expect(getAccessToken()).toBe("access-new");+ expect(getRefreshToken()).toBe("refresh-new");+ });++ it("clears tokens when refresh fails", async () => {+ setRefreshToken("expired-refresh");+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 401 })));++ await expect(refreshAccessToken()).resolves.toBe(false);+ expect(getAccessToken()).toBeNull();+ expect(getRefreshToken()).toBeNull();+ });});describe("module execution helpers", () => {diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex 32e58f7..e1a932b 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -2,8 +2,10 @@ import type {ApiKeyCreateResponse,ApiKeyMeta,Campaign,+ ExecutionChain,Finding,ModuleMeta,+ MonthlyFindingStats,ReportItem,TemplateMeta,TokenResponse,@@ -62,24 +64,34 @@ async function parseResponse(response: Response): Promise<unknown> {}}-async function refreshAccessToken(): Promise<boolean> {+export async function refreshAccessToken(): Promise<boolean> {const refreshToken = getRefreshToken();if (!refreshToken) {return false;}- const response = await fetch("/auth/refresh", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ refresh_token: refreshToken })- });- if (!response.ok) {++ try {+ const response = await fetch("/auth/refresh", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ refresh_token: refreshToken })+ });+ if (!response.ok) {+ clearTokens();+ return false;+ }+ const token = (await response.json()) as TokenResponse;+ if (!token.access_token || !token.refresh_token) {+ clearTokens();+ return false;+ }+ setAccessToken(token.access_token);+ setRefreshToken(token.refresh_token);+ return true;+ } catch {clearTokens();return false;}- const token = (await response.json()) as TokenResponse;- setAccessToken(token.access_token);- setRefreshToken(token.refresh_token);- return true;}export async function apiRequest<T>(@@ -164,6 +176,7 @@ export const api = {me: () => apiRequest<UserProfile>("/auth/me"),health: () => apiRequest<Record<string, unknown>>("/health"),telemetry: () => apiRequest<Record<string, unknown>>("/telemetry"),+ monthlyStats: () => apiRequest<MonthlyFindingStats>("/stats/monthly"),campaigns: () => apiRequest<Campaign[]>("/campaigns"),createCampaign: (body: { name: string; client: string; targets: string[]; scope_cidrs: string[]; noise_profile: string }) =>apiRequest<Campaign>("/campaigns", {@@ -187,8 +200,9 @@ export const api = {diffCampaign: (id: string, otherId: string) =>apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/diff/${encodeURIComponent(otherId)}`- ),+ ),modules: () => apiRequest<ModuleMeta[]>("/modules"),+ executionChains: () => apiRequest<ExecutionChain[]>("/modules/execution-chains"),runModule: (moduleId: string, payload: ReturnType<typeof buildModuleRunPayload>) =>apiRequest<Record<string, unknown>>(`/modules/${encodeURIComponent(moduleId)}/run`, {method: "POST",diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.tsindex 5842065..0d38fc0 100644--- a/frontend/src/api/types.ts+++ b/frontend/src/api/types.ts@@ -77,6 +77,33 @@ export interface ModuleMeta {[key: string]: unknown;}+export interface ExecutionChainStage {+ order: number;+ title: string;+ module_ids: string[];+ purpose: string;+ required_inputs: string[];+ uses_previous_output: boolean;+ produces: string[];+ next_action: string;+ final_goal: boolean;+}++export interface ExecutionChain {+ id: string;+ title: string;+ category: string;+ description: string;+ stages: ExecutionChainStage[];+}++export interface MonthlyFindingStats {+ period: string;+ label: string;+ total: number;+ series: Array<{ date: string; count: number }>;+}+export interface ReportItem {filename: string;format: string;diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex c44b699..c8cd54f 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -1027,17 +1027,46 @@ textarea.field {display: flex;height: 92px;align-items: end;- gap: 0.35rem;+ gap: 0.18rem;border-bottom: 1px solid #fed7aa;padding: 0.35rem 0;+ overflow: hidden;}.sparkline span {- flex: 1;- min-width: 7px;- border-radius: 4px 4px 0 0;- background: #f9b233;- opacity: 0.9;+ flex: 1 1 0;+ min-width: 2px;+ max-width: 12px;+ border-radius: 3px 3px 1px 1px;+ background: #f4b84a;+ opacity: 0.82;+}++.sparkline-axis {+ display: flex;+ gap: 0.18rem;+ min-height: 0.85rem;+ margin-top: 0.25rem;+ overflow: hidden;+ color: #94a3b8;+ font-size: 0.64rem;+ line-height: 1;+}++.sparkline-axis span {+ flex: 1 1 0;+ min-width: 0;+ overflow: hidden;+ white-space: nowrap;+ text-align: center;+}++.sparkline-axis span:first-child {+ text-align: left;+}++.sparkline-axis span:last-child {+ text-align: right;}.table-panel {diff --git a/frontend/vite.app.config.mjs b/frontend/vite.app.config.mjsindex 5d0825f..2e9b57f 100644--- a/frontend/vite.app.config.mjs+++ b/frontend/vite.app.config.mjs@@ -6,8 +6,27 @@ import { defineConfig } from "vite";const apiOrigin = process.env.VITE_API_ORIGIN ?? "http://127.0.0.1:8080";const wsOrigin = apiOrigin.replace(/^http/, "ws");+function dashboardBasePathRedirect() {+ return {+ name: "dashboard-base-path-redirect",+ configureServer(server) {+ server.middlewares.use((request, response, next) => {+ const requestUrl = new URL(request.url ?? "/", "http://localhost");+ if (requestUrl.pathname !== "/dashboard") {+ next();+ return;+ }++ response.statusCode = 302;+ response.setHeader("Location", `/dashboard/${requestUrl.search}`);+ response.end();+ });+ },+ };+}+export default defineConfig({- plugins: [react()],+ plugins: [dashboardBasePathRedirect(), react()],base: "/dashboard/",server: {proxy: {@@ -15,6 +34,7 @@ export default defineConfig({"/campaigns": apiOrigin,"/modules": apiOrigin,"/reports": apiOrigin,+ "/stats": apiOrigin,"/telemetry": apiOrigin,"/graph": apiOrigin,"/security": apiOrigin,diff --git a/tests/unit/db/test_database.py b/tests/unit/db/test_database.pyindex 9cbfdc2..91081dc 100644--- a/tests/unit/db/test_database.py+++ b/tests/unit/db/test_database.py@@ -8,6 +8,7 @@ import asyncioimport jsonimport subprocessimport tempfile+from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Anyfrom urllib.parse import unquote, urlparse@@ -191,6 +192,111 @@ class TestDatabase:assert stats["total"] == 1assert stats["high"] == 1+ @pytest.mark.asyncio+ async def test_monthly_confirmed_finding_stats_empty(+ self, db: AresDatabase+ ) -> None:+ stats = await db.get_monthly_confirmed_finding_stats()++ assert stats["period"] == datetime.now(timezone.utc).strftime("%Y-%m")+ assert stats["label"] == "Security signals this cycle"+ assert stats["total"] == 0+ assert stats["series"] == []++ @pytest.mark.asyncio+ async def test_monthly_confirmed_finding_stats_groups_current_month_only(+ self, db: AresDatabase, campaign: Campaign+ ) -> None:+ await db.save_campaign(campaign)+ month_start = datetime.now(timezone.utc).replace(+ day=1, hour=0, minute=0, second=0, microsecond=0+ )+ period = month_start.strftime("%Y-%m")+ day_one = f"{period}-01 12:00:00"+ day_two = f"{period}-02 12:00:00"+ previous_month = (month_start - timedelta(days=1)).strftime(+ "%Y-%m-%d 12:00:00"+ )++ async def save_at(finding: Finding, discovered_at: str) -> None:+ await db.save_finding(campaign.id, finding, finding.module_id)+ await db.conn.execute(+ "UPDATE findings SET discovered_at=? WHERE id=?",+ (discovered_at, finding.id),+ )++ await save_at(+ Finding(+ title="Current confirmed one",+ description="confirmed",+ severity=Severity.HIGH,+ validated=True,+ module_id="test.monthly",+ ),+ day_one,+ )+ await save_at(+ Finding(+ title="Current confirmed two",+ description="confirmed",+ severity=Severity.MEDIUM,+ validated=True,+ module_id="test.monthly",+ ),+ day_one,+ )+ await save_at(+ Finding(+ title="Current confirmed three",+ description="confirmed",+ severity=Severity.LOW,+ validated=True,+ module_id="test.monthly",+ ),+ day_two,+ )+ await save_at(+ Finding(+ title="Previous month",+ description="outside period",+ severity=Severity.HIGH,+ validated=True,+ module_id="test.monthly",+ ),+ previous_month,+ )+ await save_at(+ Finding(+ title="Not validated",+ description="filtered",+ severity=Severity.HIGH,+ validated=False,+ module_id="test.monthly",+ ),+ day_two,+ )+ await save_at(+ Finding(+ title="False positive",+ description="filtered",+ severity=Severity.HIGH,+ validated=True,+ false_positive=True,+ module_id="test.monthly",+ ),+ day_two,+ )+ await db.conn.commit()++ stats = await db.get_monthly_confirmed_finding_stats()++ assert stats["period"] == period+ assert stats["total"] == 3+ assert stats["series"] == [+ {"date": f"{period}-01", "count": 2},+ {"date": f"{period}-02", "count": 1},+ ]+@pytest.mark.asyncioasync def test_upsert_host(self, db: AresDatabase, campaign: Campaign) -> None:await db.save_campaign(campaign)diff --git a/tests/unit/test_ad_bind_behavior.py b/tests/unit/test_ad_bind_behavior.pyindex 67f3e30..d4a2178 100644--- a/tests/unit/test_ad_bind_behavior.py+++ b/tests/unit/test_ad_bind_behavior.py@@ -208,6 +208,48 @@ def test_asreproast_capture_uses_impacket_no_preauth_api(monkeypatch):assert captured["kerberoast_no_preauth"] is True+async def test_kerberoast_empty_target_fails_fast_before_tgs_worker(monkeypatch):+ from ares.modules.ad.kerberoast import KerberoastModule++ async def unexpected_tickets(*args, **kwargs):+ raise AssertionError("empty target must not start TGS or SPN work")++ module, _ = _make_module(KerberoastModule)+ monkeypatch.setattr(module, "_request_tickets", unexpected_tickets)++ with pytest.raises(ModuleValidationError) as exc_info:+ await module.run(+ dc="10.0.0.5",+ domain="lab.local",+ username="[email protected]",+ password="Password1!",+ target_user=" ",+ )++ message = str(exc_info.value)+ assert "ad.kerberoast requires a specific target user or SPN" in message+ assert "ad.enum_spn" in message+ assert "svc-sql" in message+ assert "MSSQLSvc/sql01.lab.local:1433" in message+ assert "Password1!" not in message+++def test_ad_kerberos_execution_chain_metadata_is_guided_and_targeted():+ from ares.core.execution_chains import list_execution_chains++ chain = next(item for item in list_execution_chains() if item["id"] == "ad-kerberos-exposure-chain")+ stages = chain["stages"]+ targeted = next(stage for stage in stages if stage["module_ids"] == ["ad.kerberoast"])++ assert chain["title"] == "AD Kerberos Exposure Chain"+ assert [stage["order"] for stage in stages] == [1, 2, 3, 4]+ assert stages[0]["module_ids"] == ["ad.enum_users", "ad.asreproast"]+ assert stages[1]["module_ids"] == ["ad.enum_spn"]+ assert "target_user" in targeted["required_inputs"]+ assert "ad.enum_spn" in targeted["next_action"]++@pytest.mark.asyncioasync def test_kerberoast_dry_run_does_not_request_tgt_or_spns(monkeypatch):from ares.modules.ad.kerberoast import KerberoastModulediff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex 3a3f0fd..8ee805d 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -93,6 +93,14 @@ def _make_mock_db():db.list_campaigns = AsyncMock(return_value=([], 0))db.get_campaign = AsyncMock(return_value=None)db.list_findings = AsyncMock(return_value=([], 0))+ db.get_monthly_confirmed_finding_stats = AsyncMock(+ return_value={+ "period": "2026-07",+ "label": "Security signals this cycle",+ "total": 0,+ "series": [],+ }+ )db.delete_campaign = AsyncMock(return_value=False)db.verify_api_key = AsyncMock(return_value=None)return db@@ -177,6 +185,28 @@ class TestHealthEndpoint:assert "version" in r.json()+class TestMonthlyStatsEndpoint:+ def setup_method(self):+ _reset_rate_limiter()++ @pytest.mark.asyncio+ async def test_monthly_stats_returns_confirmed_finding_series(self, aclient):+ c, db, _ = aclient+ expected = {+ "period": "2026-07",+ "label": "Security signals this cycle",+ "total": 2,+ "series": [{"date": "2026-07-18", "count": 2}],+ }+ db.get_monthly_confirmed_finding_stats.return_value = expected++ response = await c.get("/stats/monthly", headers=_auth("admin", "team_lead"))++ assert response.status_code == 200+ assert response.json() == expected+ db.get_monthly_confirmed_finding_stats.assert_awaited_once_with()++# ── Security headers ──────────────────────────────────────────────────────────@@ -721,6 +751,7 @@ class TestRouteInventoryAndDashboard:("GET", "/campaigns"),("DELETE", "/campaigns/{campaign_id}"),("GET", "/modules"),+ ("GET", "/modules/execution-chains"),("POST", "/modules/{module_id}/run"),("POST", "/reports/{campaign_id}"),("GET", "/reports/{campaign_id}"),@@ -816,6 +847,21 @@ class TestModuleSchemaEndpoint:assert field in moduleassert module["dry_run_supported"] is True+ @pytest.mark.asyncio # type: ignore[untyped-decorator]+ async def test_execution_chains_are_available_with_module_metadata(+ self, aclient: Any+ ) -> None:+ c, db, _ = aclient+ db.is_access_token_revoked.return_value = False+ response = await c.get("/modules/execution-chains", headers=_auth("admin", "team_lead"))++ assert response.status_code == 200+ chains = response.json()+ assert len(chains) >= 7+ kerberos = next(chain for chain in chains if chain["id"] == "ad-kerberos-exposure-chain")+ assert kerberos["stages"][1]["module_ids"] == ["ad.enum_spn"]+ assert kerberos["stages"][2]["module_ids"] == ["ad.kerberoast"]+# ── Reports safety ───────────────────────────────────────────────────────────diff --git a/tests/unit/test_dashboard_dev_launcher.py b/tests/unit/test_dashboard_dev_launcher.pyindex 5268f57..188b4e1 100644--- a/tests/unit/test_dashboard_dev_launcher.py+++ b/tests/unit/test_dashboard_dev_launcher.py@@ -71,6 +71,7 @@ def test_dashboard_dev_command_builders():"127.0.0.1","--port","5173",+ "--strictPort",]@@ -80,7 +81,11 @@ def test_dashboard_dev_missing_node_modules_prints_clear_instruction(tmp_path, c_make_repo(tmp_path, node_modules=False)with pytest.raises(typer.Exit):- _run_dashboard_dev(root=tmp_path, open_browser=False)+ _run_dashboard_dev(+ root=tmp_path,+ open_browser=False,+ port_in_use_func=lambda host, port: False,+ )output = capsys.readouterr().outassert "frontend/node_modules is missing" in output@@ -88,6 +93,32 @@ def test_dashboard_dev_missing_node_modules_prints_clear_instruction(tmp_path, cassert "--install" in output+def test_dashboard_dev_rejects_occupied_port_before_starting_processes(tmp_path, capsys):+ from ares.cli.typer_main import _run_dashboard_dev++ _make_repo(tmp_path)+ started = []++ def fail_if_started(*args, **kwargs):+ started.append((args, kwargs))+ raise AssertionError("dashboard process should not start")++ with pytest.raises(typer.Exit) as exc_info:+ _run_dashboard_dev(+ root=tmp_path,+ open_browser=False,+ popen_factory=fail_if_started,+ port_in_use_func=lambda host, port: port == 5173,+ )++ assert exc_info.value.exit_code == 1+ assert started == []+ output = capsys.readouterr().out+ assert "frontend port 127.0.0.1:5173 is already occupied" in output+ assert "stale Python or Node dashboard process" in output+ assert "Get-Process python,node" in output++def test_dashboard_dev_install_runs_npm_ci_when_requested(tmp_path):from ares.cli.typer_main import _ensure_frontend_dependencies@@ -134,7 +165,7 @@ def test_dashboard_dev_launches_both_processes_and_cleans_up(monkeypatch, tmp_paself.kwargs = kwargsself.pid = FakeProcess._next_pidFakeProcess._next_pid += 1- self.stdout = []+ self.stdout = ["frontend page reload src/api/client.test.ts\n"]self.stopped = Falseself.signals = []launched.append(self)@@ -175,6 +206,7 @@ def test_dashboard_dev_launches_both_processes_and_cleans_up(monkeypatch, tmp_paos_name="nt",open_browser=False,popen_factory=fake_popen,+ port_in_use_func=lambda host, port: False,wait_for_port_func=lambda *args, **kwargs: True,open_browser_func=lambda url: opened.append(url),sleep_func=interrupt,@@ -197,6 +229,7 @@ def test_dashboard_dev_launches_both_processes_and_cleans_up(monkeypatch, tmp_pa"127.0.0.1","--port","5173",+ "--strictPort",]assert launched[0].kwargs["cwd"] == str(tmp_path)assert launched[1].kwargs["cwd"] == str(tmp_path / "frontend")@@ -209,6 +242,7 @@ def test_dashboard_dev_launches_both_processes_and_cleans_up(monkeypatch, tmp_paassert all("/T" in call[0] and "/F" in call[0] for call in taskkill_calls)output = capsys.readouterr().out+ assert "page reload src/api/client.test.ts" in outputassert "Dashboard URL: http://127.0.0.1:5173/dashboard/" in outputassert "Login username: admin" in outputassert (@@ -216,3 +250,117 @@ def test_dashboard_dev_launches_both_processes_and_cleans_up(monkeypatch, tmp_pain output)assert "DoNotPrintThisSecret123!" not in output+++def test_dashboard_dev_backend_exit_terminates_frontend(monkeypatch, tmp_path, capsys):+ from ares.cli import typer_main++ _make_repo(tmp_path)+ launched = []+ taskkill_calls = []++ class FakeProcess:+ _next_pid = 5000++ def __init__(self, command, exit_code):+ self.command = command+ self.pid = FakeProcess._next_pid+ FakeProcess._next_pid += 1+ self.exit_code = exit_code+ self.stopped = False+ self.stdout = []++ def poll(self):+ if self.stopped:+ return 0+ return self.exit_code++ def wait(self, timeout=None):+ self.stopped = True+ return 0++ def kill(self):+ self.stopped = True++ def fake_popen(command, **kwargs):+ process = FakeProcess(command, 3 if not launched else None)+ launched.append(process)+ return process++ def fake_run(command, **kwargs):+ taskkill_calls.append(command)+ return subprocess.CompletedProcess(command, 0)++ monkeypatch.setattr(typer_main, "resolve_npm_command", lambda os_name=None: "npm.cmd")+ monkeypatch.setattr(typer_main.subprocess, "run", fake_run)++ exit_code = typer_main._run_dashboard_dev(+ root=tmp_path,+ os_name="nt",+ open_browser=False,+ popen_factory=fake_popen,+ port_in_use_func=lambda host, port: False,+ )++ assert exit_code == 3+ assert len(launched) == 2+ assert launched[1].stopped+ assert any(command[:2] == ["taskkill", "/PID"] for command in taskkill_calls)+ assert "Backend process exited with code 3" in capsys.readouterr().out+++def test_dashboard_dev_frontend_exit_terminates_backend(monkeypatch, tmp_path, capsys):+ from ares.cli import typer_main++ _make_repo(tmp_path)+ launched = []+ taskkill_calls = []++ class FakeProcess:+ _next_pid = 6000++ def __init__(self, command, exit_code):+ self.command = command+ self.pid = FakeProcess._next_pid+ FakeProcess._next_pid += 1+ self.exit_code = exit_code+ self.stopped = False+ self.stdout = []++ def poll(self):+ if self.stopped:+ return 0+ return self.exit_code++ def wait(self, timeout=None):+ self.stopped = True+ return 0++ def kill(self):+ self.stopped = True++ def fake_popen(command, **kwargs):+ process = FakeProcess(command, None if not launched else 4)+ launched.append(process)+ return process++ def fake_run(command, **kwargs):+ taskkill_calls.append(command)+ return subprocess.CompletedProcess(command, 0)++ monkeypatch.setattr(typer_main, "resolve_npm_command", lambda os_name=None: "npm.cmd")+ monkeypatch.setattr(typer_main.subprocess, "run", fake_run)++ exit_code = typer_main._run_dashboard_dev(+ root=tmp_path,+ os_name="nt",+ open_browser=False,+ popen_factory=fake_popen,+ port_in_use_func=lambda host, port: False,+ )++ assert exit_code == 4+ assert len(launched) == 2+ assert launched[0].stopped+ assert any(command[:2] == ["taskkill", "/PID"] for command in taskkill_calls)+ assert "Frontend process exited with code 4" in capsys.readouterr().outdiff --git a/tests/unit/test_execution_chains.py b/tests/unit/test_execution_chains.pynew file mode 100644index 0000000..7082a58--- /dev/null+++ b/tests/unit/test_execution_chains.py@@ -0,0 +1,44 @@+from __future__ import annotations+++def test_execution_chains_cover_every_builtin_module():+ from ares.core.execution_chains import list_execution_chains+ from ares.core.plugin.loader import PluginLoader++ loader = PluginLoader()+ loader._load_builtin()+ builtin_ids = {module.MODULE_ID for module in loader.registry.all()}+ chain_ids = {+ module_id+ for chain in list_execution_chains()+ for stage in chain["stages"]+ for module_id in stage["module_ids"]+ }++ assert len(list_execution_chains()) >= 7+ assert chain_ids <= builtin_ids+ assert chain_ids == builtin_ids+++def test_execution_chains_have_ordered_stages_and_final_goals():+ from ares.core.execution_chains import list_execution_chains++ chains = list_execution_chains()+ assert {chain["id"] for chain in chains} >= {+ "ad-kerberos-exposure-chain",+ "ad-domain-enumeration-chain",+ "web-api-exposure-chain",+ "cloud-exposure-chain",+ "credential-secret-exposure-chain",+ "opsec-safety-chain",+ "reporting-evidence-chain",+ "standalone-utilities",+ }+ for chain in chains:+ stages = chain["stages"]+ assert [stage["order"] for stage in stages] == list(range(1, len(stages) + 1))+ assert sum(stage["final_goal"] for stage in stages) == 1+ for stage in stages:+ assert stage["title"]+ assert stage["purpose"]+ assert stage["next_action"]