Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

fix(dashboard,db): per-campaign ownership on dashboard, rollback on error (#74)

kraii_f5c7b1439b38
diff --git a/ares/api/dashboard/app.py b/ares/api/dashboard/app.py
index fab1d7c..120de28 100644
--- a/ares/api/dashboard/app.py
+++ b/ares/api/dashboard/app.py
@@ -23,6 +23,7 @@ if TYPE_CHECKING:
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
+from dataclasses import dataclass
from typing import Any
from fastapi import Depends, FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
@@ -39,10 +40,34 @@ from ares.core.logger import get_logger
_bearer_scheme = HTTPBearer(auto_error=False)
+@dataclass(frozen=True)
+class _DashActor:
+ """Minimal authenticated principal for dashboard authorization."""
+
+ username: str
+ role: str
+
+
+def _dashboard_campaign_access(campaign: Any, actor: "_DashActor") -> None:
+ """Raise 404 (not 403, to avoid campaign enumeration) when the actor is not a
+ team_lead and does not own the campaign. Mirrors the main API's
+ _require_campaign_access so the dashboard sub-app enforces the same per-
+ campaign ownership boundary. (AUDIT run-1 H6)
+ """
+ if actor.role == "team_lead":
+ return
+ operator = (
+ campaign.get("operator") if isinstance(campaign, dict)
+ else getattr(campaign, "operator", None)
+ )
+ if operator != actor.username:
+ raise HTTPException(status_code=404, detail="Campaign not found")
+
+
async def _require_dashboard_auth(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer_scheme),
-) -> None:
+) -> "_DashActor":
"""
Validate JWT or API key. Raises 401 if missing/invalid.
Accepts: Authorization: Bearer <token> OR X-API-Key: <key>
@@ -111,8 +136,11 @@ async def _require_dashboard_auth(
status_code=503,
detail="Authentication service temporarily unavailable.",
)
- if decision.status is PrincipalDecisionStatus.AUTHORIZED:
- return
+ if decision.status is PrincipalDecisionStatus.AUTHORIZED and decision.principal is not None:
+ return _DashActor(
+ username=decision.principal.username,
+ role=decision.principal.role,
+ )
# Fall through to API-key check on INVALID: callers may send both
# headers (unlikely but legal); only raise after exhausting them.
@@ -138,7 +166,10 @@ async def _require_dashboard_auth(
except Exception: # pragma: no cover - best-effort cleanup
pass
if user:
- return
+ return _DashActor(
+ username=str(user.get("username", "")),
+ role=str(user.get("role", "")),
+ )
raise HTTPException(status_code=401, detail="Authentication required")
@@ -545,7 +576,7 @@ async def dashboard_root() -> str:
@dashboard_app.get("/api/status")
-async def api_status(_auth: None = Depends(_require_dashboard_auth)) -> dict[str, Any]:
+async def api_status(_actor: "_DashActor" = Depends(_require_dashboard_auth)) -> dict[str, Any]:
return {"status": "online", "version": _ares_version}
@@ -565,34 +596,53 @@ def _get_db() -> "AresDatabase": # noqa: F821
return _DB(s.db_path, s.encryption_key_value)
+def _filter_owned_campaigns(rows: list[dict[str, Any]], actor: "_DashActor") -> list[dict[str, Any]]:
+ # Non-team_lead operators see only their own campaigns. (AUDIT run-1 H6)
+ if actor.role == "team_lead":
+ return rows
+ return [r for r in rows if r.get("operator") == actor.username]
+
+
@dashboard_app.get("/api/campaigns")
-async def api_campaigns(_auth: None = Depends(_require_dashboard_auth)) -> list[dict[str, Any]]:
+async def api_campaigns(actor: "_DashActor" = Depends(_require_dashboard_auth)) -> list[dict[str, Any]]:
try:
db = _get_db()
if getattr(dashboard_app.state, "db", None) is not None:
rows, _ = await db.list_campaigns()
- return rows
+ return _filter_owned_campaigns(rows, actor)
async with db:
rows, _ = await db.list_campaigns()
- return rows
+ return _filter_owned_campaigns(rows, actor)
except Exception as e:
logger.warning("dashboard_api_error", error=str(e)[:200])
raise HTTPException(status_code=500, detail="Internal server error") # noqa: B904
+async def _authorize_campaign(db: Any, campaign_id: str, actor: "_DashActor") -> None:
+ campaign = await db.get_campaign(campaign_id)
+ if not campaign:
+ raise HTTPException(status_code=404, detail="Campaign not found")
+ _dashboard_campaign_access(campaign, actor)
+
+
@dashboard_app.get("/api/campaigns/{campaign_id}/findings")
async def api_findings(campaign_id: str, severity: str | None = None,
- _auth: None = Depends(_require_dashboard_auth)) -> list[dict[str, Any]]:
+ actor: "_DashActor" = Depends(_require_dashboard_auth)) -> list[dict[str, Any]]:
try:
db = _get_db()
- if getattr(dashboard_app.state, "db", None) is not None:
+
+ async def _run(db: Any) -> list[dict[str, Any]]:
+ await _authorize_campaign(db, campaign_id, actor)
rows, _ = await db.list_findings(campaign_id, severity=severity,
validated=True, false_positive=False)
return redact_finding_response_rows(rows)
+
+ if getattr(dashboard_app.state, "db", None) is not None:
+ return await _run(db)
async with db:
- rows, _ = await db.list_findings(campaign_id, severity=severity,
- validated=True, false_positive=False)
- return redact_finding_response_rows(rows)
+ return await _run(db)
+ except HTTPException:
+ raise
except Exception as e:
logger.warning("dashboard_api_error", error=str(e)[:200])
raise HTTPException(status_code=500, detail="Internal server error") # noqa: B904
@@ -600,13 +650,20 @@ async def api_findings(campaign_id: str, severity: str | None = None,
@dashboard_app.get("/api/campaigns/{campaign_id}/hosts")
async def api_hosts(campaign_id: str,
- _auth: None = Depends(_require_dashboard_auth)) -> list[dict[str, Any]]:
+ actor: "_DashActor" = Depends(_require_dashboard_auth)) -> list[dict[str, Any]]:
try:
db = _get_db()
- if getattr(dashboard_app.state, "db", None) is not None:
+
+ async def _run(db: Any) -> list[dict[str, Any]]:
+ await _authorize_campaign(db, campaign_id, actor)
return await db.get_hosts(campaign_id)
+
+ if getattr(dashboard_app.state, "db", None) is not None:
+ return await _run(db)
async with db:
- return await db.get_hosts(campaign_id)
+ return await _run(db)
+ except HTTPException:
+ raise
except Exception as e:
logger.warning("dashboard_api_error", error=str(e)[:200])
raise HTTPException(status_code=500, detail="Internal server error") # noqa: B904
@@ -614,12 +671,13 @@ async def api_hosts(campaign_id: str,
@dashboard_app.get("/api/campaigns/{campaign_id}/summary")
async def api_summary(campaign_id: str,
- _auth: None = Depends(_require_dashboard_auth)) -> dict[str, Any]:
+ actor: "_DashActor" = Depends(_require_dashboard_auth)) -> dict[str, Any]:
try:
db = _get_db()
use_shared = getattr(dashboard_app.state, "db", None) is not None
async def _fetch(db: "AresDatabase") -> dict[str, Any]: # noqa: F821
+ await _authorize_campaign(db, campaign_id, actor)
summary = await db.campaign_summary(campaign_id)
findings, _ = await db.list_findings(campaign_id,
validated=True, false_positive=False)
@@ -641,13 +699,15 @@ async def api_summary(campaign_id: str,
return await _fetch(db)
async with db:
return await _fetch(db)
+ except HTTPException:
+ raise
except Exception as e:
logger.warning("dashboard_api_error", error=str(e)[:200])
raise HTTPException(status_code=500, detail="Internal server error") # noqa: B904
@dashboard_app.get("/api/workers")
-async def api_workers(_auth: None = Depends(_require_dashboard_auth)) -> dict[str, Any]:
+async def api_workers(_actor: "_DashActor" = Depends(_require_dashboard_auth)) -> dict[str, Any]:
# Report whether a distributed worker controller is actually attached rather
# than always returning a 0/0/0/0 queue, which is indistinguishable from a
# healthy, idle controller. A controller wired onto dashboard_app.state is
diff --git a/ares/api/server.py b/ares/api/server.py
index 420e338..8fed513 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -1088,6 +1088,18 @@ async def generic_exception_handler(request: Request, exc: Exception) -> JSONRes
method=request.method,
exc_type=type(exc).__name__,
)
+ # AUDIT run-1 H7: a state-changing handler that raised mid-write can leave the
+ # shared SQLite connection with an open transaction. Roll it back so the next
+ # request is not blocked ("cannot start a transaction within a transaction")
+ # or served partially-committed state. (asyncpg/Postgres pools auto-clean, so
+ # there is no shared `conn` there and this is a no-op.)
+ try:
+ db = getattr(request.app.state, "db", None)
+ conn = getattr(db, "conn", None)
+ if conn is not None and hasattr(conn, "rollback"):
+ await conn.rollback()
+ except Exception as rb_exc: # pragma: no cover - best-effort cleanup
+ logger.warning("db_rollback_after_error_failed", error=str(rb_exc)[:120])
return JSONResponse(
status_code=500,
content={
diff --git a/ares/db/database.py b/ares/db/database.py
index 5348d58..c196197 100644
--- a/ares/db/database.py
+++ b/ares/db/database.py
@@ -2318,10 +2318,20 @@ class AresDatabase:
password_ok = verify_password(password, candidate_hash)
if not user or not password_ok:
return None
- await self.conn.execute(
- "UPDATE users SET last_login=datetime('now') WHERE id=?", (user["id"],)
- )
- await self.conn.commit()
+ # last_login is a non-critical bookkeeping write; a failure here must not
+ # fail the login, and must not leave the shared connection mid-transaction.
+ # (AUDIT run-1 H7)
+ try:
+ await self.conn.execute(
+ "UPDATE users SET last_login=datetime('now') WHERE id=?", (user["id"],)
+ )
+ await self.conn.commit()
+ except Exception as exc:
+ logger.warning("last_login_update_failed", error=str(exc)[:120])
+ try:
+ await self.conn.rollback()
+ except Exception: # pragma: no cover - best-effort cleanup
+ pass
return user
# ── SSO & Organizations ───────────────────────────────────────────────────
diff --git a/mypy-baseline.txt b/mypy-baseline.txt
index 6a3c6c9..389c22b 100644
--- a/mypy-baseline.txt
+++ b/mypy-baseline.txt
@@ -4,7 +4,7 @@ ares/api/server.py|error: Incompatible return value type (got "JSONResponse", ex
ares/api/server.py|error: Incompatible return value type (got "JSONResponse", expected "dict[str, Any]") [return-value]
ares/api/server.py|error: Incompatible types in assignment (expression has type "ApiKeyTicketSource", variable has type "BearerTicketSource | None") [assignment]
ares/api/server.py|error: Invalid index type "str" for "str"; expected type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" [index]
-ares/api/server.py|error: Name "result_rows" already defined on line 4125 [no-redef]
+ares/api/server.py|error: Name "result_rows" already defined on line 4137 [no-redef]
ares/api/server.py|error: Value of type "dict[str, Any] | Any | str | None" is not indexable [index]
ares/cli/mcp_cli_utils.py|error: Unexpected keyword argument "file" for "print" of "Console" [call-arg]
ares/cli/mcp_tui.py|error: Module has no attribute "getch" [attr-defined]
diff --git a/tests/unit/test_cli_reporting_goal_planning.py b/tests/unit/test_cli_reporting_goal_planning.py
index 4ec182e..1453ce4 100644
--- a/tests/unit/test_cli_reporting_goal_planning.py
+++ b/tests/unit/test_cli_reporting_goal_planning.py
@@ -706,6 +706,7 @@ class TestDashboardApp:
}
original = dict(row)
mock_db.list_findings = AsyncMock(return_value=([row], 1))
+ mock_db.get_campaign = AsyncMock(return_value={"id": "c-001", "operator": self._TEST_USERNAME})
mock_db.__aenter__ = AsyncMock(return_value=mock_db)
mock_db.__aexit__ = AsyncMock(return_value=None)
@@ -731,6 +732,7 @@ class TestDashboardApp:
original = dict(row)
mock_db = AsyncMock()
mock_db.list_findings = AsyncMock(return_value=([row], 1))
+ mock_db.get_campaign = AsyncMock(return_value={"id": "c-001", "operator": self._TEST_USERNAME})
mock_db.__aenter__ = AsyncMock(return_value=mock_db)
mock_db.__aexit__ = AsyncMock(return_value=None)
mock_state = MagicMock()
@@ -754,6 +756,7 @@ class TestDashboardApp:
mock_db = AsyncMock()
mock_db.campaign_summary = AsyncMock(return_value={"total": 5, "critical": 1})
mock_db.list_findings = AsyncMock(return_value=([], 0))
+ mock_db.get_campaign = AsyncMock(return_value={"id": "c-001", "operator": self._TEST_USERNAME})
mock_db.__aenter__ = AsyncMock(return_value=mock_db)
mock_db.__aexit__ = AsyncMock(return_value=None)
@@ -765,6 +768,45 @@ class TestDashboardApp:
r = client.get("/api/campaigns/c-001/summary", headers=headers)
assert r.status_code in (200, 500)
+ def test_api_findings_rejects_other_operators_campaign(self, client):
+ """AUDIT run-1 H6: an operator must not read a campaign owned by another
+ operator through the dashboard sub-app (404, not the data)."""
+ mock_db = AsyncMock()
+ mock_db.get_campaign = AsyncMock(return_value={"id": "c-001", "operator": "someone-else"})
+ mock_db.list_findings = AsyncMock(return_value=([{"id": "secret-finding"}], 1))
+ mock_db.__aenter__ = AsyncMock(return_value=mock_db)
+ mock_db.__aexit__ = AsyncMock(return_value=None)
+
+ mock_state = MagicMock()
+ mock_state.db = mock_db
+
+ with self._authenticated_dashboard(mock_db) as headers, \
+ patch("ares.api.dashboard.app.dashboard_app.state", mock_state):
+ r = client.get("/api/campaigns/c-001/findings", headers=headers)
+ assert r.status_code == 404
+ assert "secret-finding" not in r.text
+ mock_db.list_findings.assert_not_awaited()
+
+ def test_api_campaigns_filters_to_owner_for_operator(self, client):
+ """AUDIT run-1 H6: the campaign list only returns the operator's own
+ campaigns (team_leads see all; this actor is an operator)."""
+ mock_db = AsyncMock()
+ mine = {"id": "c-mine", "operator": self._TEST_USERNAME}
+ theirs = {"id": "c-theirs", "operator": "someone-else"}
+ mock_db.list_campaigns = AsyncMock(return_value=([mine, theirs], 2))
+ mock_db.__aenter__ = AsyncMock(return_value=mock_db)
+ mock_db.__aexit__ = AsyncMock(return_value=None)
+
+ mock_state = MagicMock()
+ mock_state.db = mock_db
+
+ with self._authenticated_dashboard(mock_db) as headers, \
+ patch("ares.api.dashboard.app.dashboard_app.state", mock_state):
+ r = client.get("/api/campaigns", headers=headers)
+ assert r.status_code == 200
+ ids = [c["id"] for c in r.json()]
+ assert ids == ["c-mine"]
+
def test_broadcast_finding_sends_to_connections(self):
"""broadcast_finding sends JSON to all active WS connections."""
import asyncio
diff --git a/tests/unit/test_db_rollback_h7.py b/tests/unit/test_db_rollback_h7.py
new file mode 100644
index 0000000..681018b
--- /dev/null
+++ b/tests/unit/test_db_rollback_h7.py
@@ -0,0 +1,38 @@
+"""AUDIT run-1 H7: an unhandled error must not leave the shared SQLite
+connection mid-transaction; the generic exception handler rolls it back."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+
+async def test_generic_exception_handler_rolls_back_shared_connection():
+ from ares.api.server import generic_exception_handler
+
+ conn = MagicMock()
+ conn.rollback = AsyncMock()
+ db = MagicMock()
+ db.conn = conn
+
+ request = MagicMock()
+ request.app.state.db = db
+ request.url.path = "/campaigns"
+ request.method = "POST"
+
+ resp = await generic_exception_handler(request, RuntimeError("boom"))
+ assert resp.status_code == 500
+ conn.rollback.assert_awaited_once()
+
+
+async def test_generic_exception_handler_tolerates_missing_db():
+ from ares.api.server import generic_exception_handler
+
+ request = MagicMock()
+ request.app.state.db = None
+ request.url.path = "/x"
+ request.method = "GET"
+ # Must not raise even when no DB / no conn is available.
+ resp = await generic_exception_handler(request, RuntimeError("boom"))
+ assert resp.status_code == 500