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(security): guard legacy dashboard startup
Mafifrizi5a8d267d6fef
diff --git a/ares/api/dashboard/app.py b/ares/api/dashboard/app.pyindex 84cf9cf..351be63 100644--- a/ares/api/dashboard/app.py+++ b/ares/api/dashboard/app.py@@ -14,6 +14,8 @@ Routes:"""from __future__ import annotations+from collections.abc import AsyncIterator+from contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Any@@ -83,7 +85,29 @@ async def _require_dashboard_auth(logger = get_logger("ares.dashboard")-dashboard_app = FastAPI(title="ARES Dashboard", docs_url=None, redoc_url=None)+_LEGACY_DASHBOARD_DISABLED = (+ "Legacy dashboard ASGI application is disabled. "+ "Use the dashboard served by the main ARES application; "+ "explicit development opt-in is required."+)+++@asynccontextmanager+async def _legacy_dashboard_lifespan(_app: FastAPI) -> AsyncIterator[None]:+ from ares.core.config import get_settings++ settings = get_settings()+ if not (settings.ares_legacy_dashboard_enabled and settings.ares_debug):+ raise RuntimeError(_LEGACY_DASHBOARD_DISABLED)+ yield+++dashboard_app = FastAPI(+ title="ARES Dashboard",+ docs_url=None,+ redoc_url=None,+ lifespan=_legacy_dashboard_lifespan,+)# WebSocket connections for live streaminglive_connections: list[WebSocket] = [] # public — exported for testingdiff --git a/ares/core/config.py b/ares/core/config.pyindex 9e1dde6..a2e7199 100644--- a/ares/core/config.py+++ b/ares/core/config.py@@ -81,6 +81,7 @@ class AresSettings(BaseSettings):ares_jwt_expire_minutes: int = Field(60, ge=5)ares_rate_limit_rpm: int = Field(60, ge=1)ares_debug: bool = False+ ares_legacy_dashboard_enabled: bool = False# Databaseares_database_url: str = "sqlite+aiosqlite:///./ares.db"diff --git a/docs/api-reference.md b/docs/api-reference.mdindex cc765dc..278648a 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -621,6 +621,28 @@ and `WS /ws/campaigns/{campaign_id}/events?token=<token>`. Legacy`/dashboard/api/*` and `/dashboard/ws/live` routes are not the primary datasource.+The supported dashboard is `/dashboard` on the main ARES application. The+older `ares.api.dashboard.app:dashboard_app` FastAPI application is not mounted+by that supported topology. Under normal ASGI lifespan processing, direct+legacy startup is denied by default; development or test execution requires+both `ARES_LEGACY_DASHBOARD_ENABLED=true` and `ARES_DEBUG=true`. All supported+main-application, CLI, Docker, and Compose launch paths use the main ARES+application and normal lifecycle processing. Never enable the legacy+application in production.++Running the legacy target with ASGI lifespan disabled, including+`--lifespan off`, is unsupported. Unmanaged direct ASGI dispatch that sends+HTTP or WebSocket request scopes without entering lifespan is also unsupported+and bypasses this startup guard. This L2 guard contains accidental or default+exposure through supported launchers; it is not a security boundary against a+malicious or privileged deployment operator deliberately bypassing ASGI+lifespan.++Legacy opt-in does not add modern authentication, campaign-ownership,+WebSocket, credential-transport, or deployment parity. In particular, its+query-token and global live-WebSocket risks remain. Final retirement of the+legacy application is the preferred long-term outcome.+Dashboard shell behavior:- The left sidebar routes between pages, and the topbar menu collapses ordiff --git a/docs/security-model.md b/docs/security-model.mdindex 2682e7b..ffecfc5 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -128,9 +128,29 @@ performed from an authenticated browser/JWT session.- `POST /auth/token` — login (takes credentials, returns token)- `GET /health` — health check (no sensitive data)-**Dashboard sub-application** (`/dashboard/*`) uses the same JWT / API-key-tokens but validates them independently via `Authorization: Bearer` header-or `?token=<jwt>` query param (WebSocket only).+The supported dashboard is the React application served by the main ARES+FastAPI application at `/dashboard`. The older+`ares.api.dashboard.app:dashboard_app` FastAPI application is not mounted by+that topology. The executable guard's control objective is to prevent+accidental or default deployment of the legacy surface. Under normal ASGI+lifespan processing, legacy startup is denied unless both+`ARES_LEGACY_DASHBOARD_ENABLED=true` and `ARES_DEBUG=true`; the legacy flag+must never be enabled in production. Supported main-application, CLI, Docker,+and Compose launch paths use the main ARES application and normal lifecycle+processing, so they remain fail-closed by default.++The guard trusts the supported ASGI server to execute application lifespan.+Running the legacy target with lifespan disabled, including `--lifespan off`,+is unsupported. Directly dispatching HTTP or WebSocket request scopes without+managing lifespan is likewise unsupported and bypasses the startup guard. This+is operational containment for supported startup behavior, not parity+hardening or a security boundary against a malicious or privileged deployment+operator who deliberately bypasses ASGI lifespan.++The explicit opt-in does not give the legacy application modern+authentication, campaign-ownership, WebSocket, credential-transport, or+deployment parity. Query-token exposure and its global live-WebSocket design+remain. Full retirement is the preferred final control.Tokens are issued by `POST /auth/token` with valid operator credentials (bcrypt-hashed password). Default expiry: 1 hour.diff --git a/tests/unit/test_dashboard_dev_launcher.py b/tests/unit/test_dashboard_dev_launcher.pyindex 188b4e1..348d4a3 100644--- a/tests/unit/test_dashboard_dev_launcher.py+++ b/tests/unit/test_dashboard_dev_launcher.py@@ -1,5 +1,6 @@from __future__ import annotations+import importlibimport subprocessfrom pathlib import Path@@ -7,6 +8,274 @@ import pytestimport typer+_LEGACY_DASHBOARD_DISABLED = (+ "Legacy dashboard ASGI application is disabled. "+ "Use the dashboard served by the main ARES application; "+ "explicit development opt-in is required."+)+++def _require_fixed(condition: bool, message: str) -> None:+ if not condition:+ pytest.fail(message, pytrace=False)+++def _set_legacy_dashboard_policy(+ monkeypatch: pytest.MonkeyPatch,+ *,+ enabled: bool,+ debug: bool,+) -> None:+ from ares.core.config import clear_settings_cache++ monkeypatch.setenv(+ "ARES_LEGACY_DASHBOARD_ENABLED",+ "true" if enabled else "false",+ )+ monkeypatch.setenv("ARES_DEBUG", "true" if debug else "false")+ clear_settings_cache()+++ ("enabled", "debug", "expected_started"),+ [+ (False, False, False),+ (False, True, False),+ (True, False, False),+ (True, True, True),+ ],+)+async def test_legacy_dashboard_lifespan_requires_both_opt_ins(+ monkeypatch: pytest.MonkeyPatch,+ enabled: bool,+ debug: bool,+ expected_started: bool,+) -> None:+ from ares.api.dashboard.app import dashboard_app+ from ares.core.config import clear_settings_cache++ _set_legacy_dashboard_policy(monkeypatch, enabled=enabled, debug=debug)+ started = False+ error_type_ok = False+ error_message_ok = False+ try:+ try:+ async with dashboard_app.router.lifespan_context(dashboard_app):+ started = True+ except Exception as exc:+ error_type_ok = type(exc) is RuntimeError+ error_message_ok = str(exc) == _LEGACY_DASHBOARD_DISABLED++ if expected_started:+ _require_fixed(started, "expected opted-in legacy lifespan to start")+ _require_fixed(+ not error_type_ok and not error_message_ok,+ "opted-in legacy lifespan raised an unexpected startup error",+ )+ else:+ _require_fixed(not started, "legacy lifespan started without both opt-ins")+ _require_fixed(error_type_ok, "legacy lifespan raised the wrong error type")+ _require_fixed(+ error_message_ok,+ "legacy lifespan did not use the fixed startup error",+ )+ finally:+ clear_settings_cache()+++async def test_legacy_dashboard_enablement_defaults_to_false(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.dashboard.app import dashboard_app+ from ares.core.config import clear_settings_cache, get_settings++ monkeypatch.delenv("ARES_LEGACY_DASHBOARD_ENABLED", raising=False)+ monkeypatch.setenv("ARES_DEBUG", "true")+ clear_settings_cache()+ disabled_by_default = False+ denied = False+ try:+ disabled_by_default = not get_settings().ares_legacy_dashboard_enabled+ try:+ async with dashboard_app.router.lifespan_context(dashboard_app):+ pass+ except Exception as exc:+ denied = (+ type(exc) is RuntimeError+ and str(exc) == _LEGACY_DASHBOARD_DISABLED+ )++ _require_fixed(+ disabled_by_default,+ "legacy dashboard enablement did not default to false",+ )+ _require_fixed(denied, "debug mode enabled the legacy dashboard by default")+ finally:+ clear_settings_cache()+++async def test_invalid_legacy_dashboard_setting_fails_closed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.dashboard.app import dashboard_app+ from ares.core.config import clear_settings_cache++ monkeypatch.setenv("ARES_LEGACY_DASHBOARD_ENABLED", "not-a-boolean")+ monkeypatch.setenv("ARES_DEBUG", "true")+ clear_settings_cache()+ started = False+ rejected = False+ try:+ try:+ async with dashboard_app.router.lifespan_context(dashboard_app):+ started = True+ except Exception:+ rejected = True++ _require_fixed(not started, "invalid legacy configuration started the app")+ _require_fixed(rejected, "invalid legacy configuration was not rejected")+ finally:+ clear_settings_cache()+++async def test_legacy_imports_and_main_topology_remain_available_by_default(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.core.config import clear_settings_cache++ _set_legacy_dashboard_policy(monkeypatch, enabled=False, debug=False)+ try:+ dashboard_package = importlib.import_module("ares.api.dashboard")+ dashboard_module = importlib.import_module("ares.api.dashboard.app")+ server_module = importlib.import_module("ares.api.server")++ import_ok = (+ dashboard_package.dashboard_app is dashboard_module.dashboard_app+ and callable(dashboard_package.broadcast_finding)+ )+ legacy_is_mounted = any(+ getattr(route, "app", None) is dashboard_module.dashboard_app+ for route in server_module.app.routes+ )+ separate_lifespans = (+ server_module.app.router.lifespan_context+ is not dashboard_module.dashboard_app.router.lifespan_context+ )++ _require_fixed(import_ok, "legacy imports were blocked by the execution guard")+ _require_fixed(+ not legacy_is_mounted,+ "main application unexpectedly mounted the legacy dashboard",+ )+ _require_fixed(+ separate_lifespans,+ "main application unexpectedly uses the legacy dashboard lifespan",+ )+ finally:+ clear_settings_cache()+++async def test_legacy_state_assignment_cannot_bypass_guard_or_open_resources(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.dashboard import app as dashboard_module+ from ares.core.config import clear_settings_cache++ _set_legacy_dashboard_policy(monkeypatch, enabled=False, debug=False)+ state = dashboard_module.dashboard_app.state+ had_db = hasattr(state, "db")+ previous_db = getattr(state, "db", None)+ shared_db = object()+ resource_calls = 0++ async def resource_probe():+ nonlocal resource_calls+ resource_calls += 1++ monkeypatch.setattr(dashboard_module, "_get_db", resource_probe)+ state.db = shared_db+ denied = False+ try:+ try:+ async with dashboard_module.dashboard_app.router.lifespan_context(+ dashboard_module.dashboard_app+ ):+ pass+ except Exception as exc:+ denied = (+ type(exc) is RuntimeError+ and str(exc) == _LEGACY_DASHBOARD_DISABLED+ )++ _require_fixed(denied, "shared database state bypassed the legacy guard")+ _require_fixed(+ resource_calls == 0,+ "legacy resource initialization ran before the guard",+ )+ _require_fixed(+ state.db is shared_db,+ "denied legacy startup changed shared database ownership",+ )+ finally:+ if had_db:+ state.db = previous_db+ else:+ del state.db+ clear_settings_cache()+++async def test_legacy_enabled_lifecycle_preserves_shared_state_and_recovers(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.dashboard.app import dashboard_app+ from ares.core.config import clear_settings_cache++ state = dashboard_app.state+ had_db = hasattr(state, "db")+ previous_db = getattr(state, "db", None)+ shared_db = object()+ state.db = shared_db+ denied = False+ entered = 0+ try:+ _set_legacy_dashboard_policy(monkeypatch, enabled=False, debug=False)+ try:+ async with dashboard_app.router.lifespan_context(dashboard_app):+ pass+ except Exception as exc:+ denied = (+ type(exc) is RuntimeError+ and str(exc) == _LEGACY_DASHBOARD_DISABLED+ )++ _set_legacy_dashboard_policy(monkeypatch, enabled=True, debug=True)+ async with dashboard_app.router.lifespan_context(dashboard_app):+ entered += 1+ _require_fixed(+ state.db is shared_db,+ "enabled legacy startup replaced shared database state",+ )++ _require_fixed(denied, "default legacy startup was not denied")+ _require_fixed(entered == 1, "enabled legacy lifespan did not enter once")+ _require_fixed(+ state.db is shared_db,+ "legacy shutdown closed or replaced a resource it did not own",+ )+ finally:+ if had_db:+ state.db = previous_db+ else:+ del state.db+ clear_settings_cache()++def _make_repo(root: Path, *, node_modules: bool = True) -> None:(root / "pyproject.toml").write_text("[project]\nname='ares-test'\n", encoding="utf-8")frontend = root / "frontend"