Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(actions): invoking-identity scoping — principal + least-privilege + route auth + bound approval (Wave 4) (#577)

Beenu Arora312e1d829c53
diff --git a/CHANGELOG.md b/CHANGELOG.md
index edec5ffe7..b247f22d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Invoking-identity scoping for response actions (Wave 4).** An
+ `ActionPrincipal` (user id + tenant + roles + permissions) now rides on every
+ `ActionRequest` (W4.1). The actions service enforces **least-privilege**: an
+ action only runs if its principal holds the permission its blast radius
+ demands (`actions:execute:{low,medium,high}`, higher tiers granting lower;
+ `actions:*` granting all), with tenant binding (W4.2). The mutating action
+ routes require a service bearer token and **fail closed** in production when
+ unconfigured (W4.3). Approvals are **bound**: an approver must hold the
+ action's permission and cannot approve their own request (separation of
+ duties, W4.4). Gated by `test_authz.py` (10 cases).
- **Three detection-authoring modes (Wave 3).** (1) A **Python detection
framework** (`packages/aisoc-detections`): write detections as
`def rule(event) -> bool` + metadata + inline positive/negative `TESTS`,
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 6a67bb4ad..e3d33715d 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -56,10 +56,13 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Detections can be authored in Python (`def rule(event)`) with a fixture gate | README (detection engineering) | `python-detections.yml` (`aisoc_detections.runner` fails a blind rule that misses a positive or a noisy one that fires on a negative; every bundled detection must ship ≥1 positive + ≥1 negative case) + `test_framework.py` (fail-closed evaluate, metadata validation) | GATED | - |
| AI Detection Builder: NL → rule + AUTO-generated fixtures → non-circular eval-gate → governed proposal | README (detection engineering) | `ci.yml` api job (`test_ai_detection_builder.py` — fixtures are DERIVED from the generated rule's own selection, not invented, and genuinely pass the non-circular gate: fires on the positive, quiet on the negative) | GATED | - |
| No-code / simple detection builder compiles to a valid rule | README (detection engineering) | `ci.yml` web type-check + lint (`SimpleRuleBuilder.tsx` `buildSigma` compiles field/operator/value rows to Sigma, dropped into the governed editor) | GATED | - |
+| Response actions run under least-privilege for the invoking identity | README (autonomy + safety) | `actions` job (`test_authz.py` — `authorize_action` denies a principal lacking the action's blast-radius permission; tier hierarchy + wildcards; tenant binding) | GATED | - |
+| Actions-service mutating routes are authenticated (fail-closed in prod) | README (autonomy + safety) | `actions` job (`test_authz.py` — `require_service_auth` returns 401 on a bad/absent bearer token, 503 when unconfigured in production, open only in dev mode) | GATED | - |
+| Approvals are bound to a qualified approver (separation of duties) | README (autonomy + safety) | `actions` job (`test_authz.py` — `authorize_approver` requires the action's permission and rejects the requester approving their own action) | GATED | - |
## Summary
-- GATED: 39
+- GATED: 42
- PARTIAL: 9
- NO GATE: 0 (**every claim is now backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The full Fully-Operational roadmap (Phases A1–E1) is complete. The 7 remaining PARTIAL rows are honest, named deferrals to future phases outside the A–E scope — each states the specific gap and the phase that closes it — not unproven claims.)
diff --git a/services/actions/app/api/router.py b/services/actions/app/api/router.py
index 89ced12dd..c456decdb 100644
--- a/services/actions/app/api/router.py
+++ b/services/actions/app/api/router.py
@@ -9,11 +9,17 @@ from typing import Any
from uuid import UUID
import structlog
-from fastapi import APIRouter, HTTPException, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import HTMLResponse
from app.core.config import get_settings
-from app.models.action import ActionRequest, ActionStatus, ActionType
+from app.models.action import ActionPrincipal, ActionRequest, ActionStatus, ActionType
+from app.security.authz import (
+ ActionAuthzError,
+ authorize_action,
+ authorize_approver,
+ require_service_auth,
+)
from app.security.chatops_token import ChatOpsTokenError, verify_token
from app.services.blast_radius import BlastRadiusGate
from app.services.executor_registry import EXECUTOR_REGISTRY
@@ -33,8 +39,16 @@ _chatops_replied: set[str] = set()
@router.post("/actions", response_model=dict)
-async def submit_action(request: ActionRequest):
+async def submit_action(request: ActionRequest, _auth: None = Depends(require_service_auth)):
"""Submit an action for execution (may require approval)."""
+ # W4.2 — least-privilege: the invoking principal must hold the permission
+ # this action's blast radius demands before it is gated or executed.
+ try:
+ authorize_action(request)
+ except ActionAuthzError as exc:
+ logger.warning("Action authorization denied", action_type=request.action_type, reason=str(exc))
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+
status, blast_radius, reason = gate.evaluate(request)
record = {
@@ -47,6 +61,9 @@ async def submit_action(request: ActionRequest):
"incident_id": str(request.incident_id),
"tenant_id": str(request.tenant_id),
"rationale": request.rationale,
+ # W4.4 — remember who requested it so an approver can't approve their
+ # own action (separation of duties).
+ "requested_by_user_id": request.principal.user_id if request.principal else None,
}
_actions[str(request.id)] = record
@@ -83,14 +100,34 @@ async def submit_action(request: ActionRequest):
@router.post("/actions/{action_id}/approve")
-async def approve_action(action_id: str):
- """Approve a pending action (human-in-the-loop gate)."""
+async def approve_action(
+ action_id: str,
+ approver: ActionPrincipal | None = None,
+ _auth: None = Depends(require_service_auth),
+):
+ """Approve a pending action (human-in-the-loop gate).
+
+ W4.4 — when an approver identity is supplied it is bound: the approver must
+ hold the action's required permission and must not be the requester. When
+ principals are required (``AISOC_ACTIONS_REQUIRE_PRINCIPAL``) an approver is
+ mandatory."""
record = _actions.get(action_id)
if not record:
raise HTTPException(status_code=404, detail="Action not found")
if record["status"] != ActionStatus.AWAITING_APPROVAL:
raise HTTPException(status_code=400, detail=f"Action is not awaiting approval (current: {record['status']})")
+ if approver is None:
+ if get_settings().AISOC_ACTIONS_REQUIRE_PRINCIPAL:
+ raise HTTPException(status_code=403, detail="an approver identity is required")
+ else:
+ try:
+ authorize_approver(record, approver)
+ except ActionAuthzError as exc:
+ logger.warning("Approval denied", action_id=action_id, reason=str(exc))
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ record["approved_by_user_id"] = approver.user_id
+
# Reconstruct request and execute
request = ActionRequest(
id=UUID(action_id),
@@ -115,7 +152,7 @@ async def approve_action(action_id: str):
@router.post("/actions/{action_id}/reject")
-async def reject_action(action_id: str):
+async def reject_action(action_id: str, _auth: None = Depends(require_service_auth)):
"""Reject a pending action."""
record = _actions.get(action_id)
if not record:
diff --git a/services/actions/app/core/config.py b/services/actions/app/core/config.py
index 9f41a88e3..8f94cf477 100644
--- a/services/actions/app/core/config.py
+++ b/services/actions/app/core/config.py
@@ -77,6 +77,24 @@ class ActionsSettings(BaseSettings):
),
)
+ # Wave 4 (W4.3) — bearer token that callers of the mutating action routes
+ # must present. When unset the routes are open only in dev mode; in
+ # production a missing token fails closed (503).
+ AISOC_ACTIONS_SERVICE_TOKEN: str = Field(
+ default="",
+ description="Shared bearer token required on POST /actions + approve/reject. Mounted as a secret in production.",
+ )
+ AISOC_DEV_MODE: bool = Field(
+ default=False,
+ description="Canonical dev-mode flag. When true, unauthenticated action routes are permitted (never set in production).",
+ )
+ # Wave 4 (W4.2) — when true, every action MUST carry an authenticated
+ # principal (system-initiated principal-less calls are rejected).
+ AISOC_ACTIONS_REQUIRE_PRINCIPAL: bool = Field(
+ default=False,
+ description="Require a structured ActionPrincipal on every action request.",
+ )
+
@lru_cache(maxsize=1)
def get_settings() -> ActionsSettings:
diff --git a/services/actions/app/models/action.py b/services/actions/app/models/action.py
index 79bcc1d3e..21e30060a 100644
--- a/services/actions/app/models/action.py
+++ b/services/actions/app/models/action.py
@@ -118,6 +118,36 @@ APPROVAL_REQUIRED_ACTIONS = {
}
+# Wave 4 (W4.2) — least-privilege permission required to EXECUTE each action,
+# derived from its blast radius. A principal must hold this permission (or a
+# broader one — see `authz.has_action_permission`). MINIMAL/LOW → :low,
+# MEDIUM → :medium, HIGH/CRITICAL → :high.
+def _perm_for_blast(blast: BlastRadius) -> str:
+ if blast in (BlastRadius.HIGH, BlastRadius.CRITICAL):
+ return "actions:execute:high"
+ if blast == BlastRadius.MEDIUM:
+ return "actions:execute:medium"
+ return "actions:execute:low"
+
+
+ACTION_REQUIRED_PERMISSION: dict[ActionType, str] = {action: _perm_for_blast(blast) for action, blast in ACTION_BLAST_RADIUS.items()}
+
+
+class ActionPrincipal(BaseModel):
+ """The authenticated identity on whose behalf an action runs (W4.1).
+
+ Propagated from the API's authenticated user into the actions service so
+ execution + approval can be scoped to that user's real permissions —
+ replacing the free-text ``requested_by`` string as the authorization basis.
+ """
+
+ user_id: str
+ tenant_id: UUID | None = None
+ email: str | None = None
+ roles: list[str] = Field(default_factory=list)
+ permissions: list[str] = Field(default_factory=list)
+
+
class ActionRequest(BaseModel):
"""Request to execute an action."""
@@ -128,6 +158,9 @@ class ActionRequest(BaseModel):
target: str
parameters: dict[str, Any] = Field(default_factory=dict)
requested_by: str = "system"
+ # W4.1 — structured invoking identity. Optional for back-compat with the
+ # legacy `requested_by` string + system-initiated calls.
+ principal: ActionPrincipal | None = None
rationale: str = ""
auto_rollback: bool = False
rollback_after_seconds: int | None = None
diff --git a/services/actions/app/security/authz.py b/services/actions/app/security/authz.py
new file mode 100644
index 000000000..fcc264574
--- /dev/null
+++ b/services/actions/app/security/authz.py
@@ -0,0 +1,122 @@
+"""Invoking-identity authorization for the actions service (Wave 4).
+
+Three guarantees layered on top of the blast-radius gate:
+
+* **W4.2 least-privilege** — an action only runs if its invoking principal
+ holds the permission its blast radius demands (``actions:execute:{low,medium,
+ high}``, with higher tiers granting lower and ``actions:*`` granting all).
+* **W4.3 authenticated routes** — the mutating routes require a service bearer
+ token; a missing token fails closed in production.
+* **W4.4 bound approval** — an approver must hold the action's permission AND
+ must not be the requester (separation of duties).
+"""
+
+from __future__ import annotations
+
+import hmac
+from typing import Any
+
+from fastapi import Header, HTTPException, status
+
+from app.core.config import get_settings
+from app.models.action import (
+ ACTION_REQUIRED_PERMISSION,
+ ActionPrincipal,
+ ActionRequest,
+ ActionType,
+)
+
+# Ordered execution tiers — a higher tier grants every lower one.
+_TIER_RANK: dict[str, int] = {
+ "actions:execute:low": 1,
+ "actions:execute:medium": 2,
+ "actions:execute:high": 3,
+}
+
+
+class ActionAuthzError(Exception):
+ """Raised when a principal is not authorized for an action / approval."""
+
+
+def has_action_permission(permissions: list[str], required: str) -> bool:
+ """True if ``permissions`` satisfies ``required`` (exact, wildcard, or a
+ higher execution tier)."""
+ if not permissions:
+ return False
+ perms = set(permissions)
+ if "*" in perms or "actions:*" in perms or "actions:execute:*" in perms:
+ return True
+ if required in perms:
+ return True
+ req_rank = _TIER_RANK.get(required, 0)
+ if req_rank:
+ return any(_TIER_RANK.get(p, 0) >= req_rank for p in perms)
+ return False
+
+
+def _required_permission(action_type: ActionType) -> str:
+ # Unknown/newly-added action types default to the strictest tier.
+ return ACTION_REQUIRED_PERMISSION.get(action_type, "actions:execute:high")
+
+
+def authorize_action(request: ActionRequest, *, require_principal: bool | None = None) -> None:
+ """Enforce least-privilege for an action's invoking principal (W4.2).
+
+ Raises :class:`ActionAuthzError` on denial. A principal-less request is
+ allowed only when principals aren't required (legacy / system path)."""
+ if require_principal is None:
+ require_principal = get_settings().AISOC_ACTIONS_REQUIRE_PRINCIPAL
+
+ principal = request.principal
+ if principal is None:
+ if require_principal:
+ raise ActionAuthzError("no authenticated principal on action request")
+ return
+
+ if principal.tenant_id is not None and principal.tenant_id != request.tenant_id:
+ raise ActionAuthzError("principal tenant does not match the action's tenant")
+
+ required = _required_permission(request.action_type)
+ if not has_action_permission(principal.permissions, required):
+ raise ActionAuthzError(f"principal {principal.user_id} lacks '{required}' required for {request.action_type.value}")
+
+
+def authorize_approver(
+ record: dict[str, Any],
+ approver: ActionPrincipal,
+ *,
+ separation_of_duties: bool = True,
+) -> None:
+ """Enforce that an approver may approve this action (W4.4).
+
+ The approver must hold the action's required permission and — under
+ separation of duties — must not be the principal who requested it."""
+ action_type = ActionType(record["action_type"])
+ required = _required_permission(action_type)
+ if not has_action_permission(approver.permissions, required):
+ raise ActionAuthzError(f"approver {approver.user_id} lacks '{required}' to approve {action_type.value}")
+
+ requester = record.get("requested_by_user_id")
+ if separation_of_duties and requester and str(requester) == str(approver.user_id):
+ raise ActionAuthzError("approver cannot be the requester (separation of duties)")
+
+
+async def require_service_auth(authorization: str | None = Header(default=None)) -> None:
+ """FastAPI dependency: verify the service bearer token on mutating routes
+ (W4.3). Fails closed in production when no token is configured."""
+ settings = get_settings()
+ token = settings.AISOC_ACTIONS_SERVICE_TOKEN.strip()
+ if not token:
+ if settings.AISOC_DEV_MODE:
+ return
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="actions service auth is not configured",
+ )
+ expected = f"Bearer {token}"
+ if not authorization or not hmac.compare_digest(authorization, expected):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="invalid or missing service token",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
diff --git a/services/actions/tests/test_authz.py b/services/actions/tests/test_authz.py
new file mode 100644
index 000000000..613fbccc9
--- /dev/null
+++ b/services/actions/tests/test_authz.py
@@ -0,0 +1,131 @@
+"""Wave 4 — invoking-identity authorization (W4.2 least-privilege, W4.3 route
+auth, W4.4 bound approval / separation of duties)."""
+
+from __future__ import annotations
+
+from uuid import uuid4
+
+import pytest
+from app.core.config import get_settings
+from app.models.action import ActionPrincipal, ActionRequest, ActionType
+from app.security.authz import (
+ ActionAuthzError,
+ authorize_action,
+ authorize_approver,
+ has_action_permission,
+)
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_TENANT = uuid4()
+
+
+def _principal(perms, *, tenant=None, uid="u1"):
+ return ActionPrincipal(user_id=uid, tenant_id=tenant, permissions=perms)
+
+
+def _request(action_type, principal=None, tenant=None):
+ return ActionRequest(
+ incident_id=uuid4(),
+ tenant_id=tenant or _TENANT,
+ action_type=action_type,
+ target="host-1",
+ principal=principal,
+ )
+
+
+# ── W4.2 permission model ──────────────────────────────────────────────────
+
+
+def test_permission_tiers_and_wildcards():
+ assert has_action_permission(["actions:execute:high"], "actions:execute:low")
+ assert has_action_permission(["actions:execute:medium"], "actions:execute:medium")
+ assert not has_action_permission(["actions:execute:low"], "actions:execute:high")
+ assert has_action_permission(["actions:*"], "actions:execute:high")
+ assert has_action_permission(["*"], "actions:execute:medium")
+ assert not has_action_permission([], "actions:execute:low")
+
+
+def test_authorize_action_allows_with_sufficient_permission():
+ req = _request(ActionType.ISOLATE_HOST, _principal(["actions:execute:high"], tenant=_TENANT))
+ authorize_action(req, require_principal=True) # no raise
+
+
+def test_authorize_action_denies_insufficient_permission():
+ req = _request(ActionType.ISOLATE_HOST, _principal(["actions:execute:low"]))
+ with pytest.raises(ActionAuthzError):
+ authorize_action(req, require_principal=True)
+
+
+def test_authorize_action_denies_tenant_mismatch():
+ req = _request(ActionType.NOTIFY_SLACK, _principal(["actions:*"], tenant=uuid4()))
+ with pytest.raises(ActionAuthzError):
+ authorize_action(req, require_principal=True)
+
+
+def test_authorize_action_principal_optional_unless_required():
+ req = _request(ActionType.ISOLATE_HOST, principal=None)
+ authorize_action(req, require_principal=False) # legacy/system path: allowed
+ with pytest.raises(ActionAuthzError):
+ authorize_action(req, require_principal=True)
+
+
+# ── W4.4 bound approval / separation of duties ─────────────────────────────
+
+
+def test_approver_must_hold_permission():
+ record = {"action_type": ActionType.ISOLATE_HOST.value, "requested_by_user_id": "requester"}
+ with pytest.raises(ActionAuthzError):
+ authorize_approver(record, _principal(["actions:execute:low"], uid="approver"))
+ authorize_approver(record, _principal(["actions:execute:high"], uid="approver")) # ok
+
+
+def test_approver_cannot_be_requester():
+ record = {"action_type": ActionType.ISOLATE_HOST.value, "requested_by_user_id": "same-user"}
+ with pytest.raises(ActionAuthzError):
+ authorize_approver(record, _principal(["actions:execute:high"], uid="same-user"))
+
+
+# ── W4.3 route auth ────────────────────────────────────────────────────────
+
+
+def _client(monkeypatch, **env):
+ for key in ("AISOC_ACTIONS_SERVICE_TOKEN", "AISOC_DEV_MODE", "AISOC_ACTIONS_REQUIRE_PRINCIPAL"):
+ monkeypatch.delenv(key, raising=False)
+ for key, value in env.items():
+ monkeypatch.setenv(key, value)
+ get_settings.cache_clear()
+ from app.api.router import router
+
+ app = FastAPI()
+ app.include_router(router)
+ return TestClient(app)
+
+
+_BODY = {
+ "incident_id": str(uuid4()),
+ "tenant_id": str(_TENANT),
+ "action_type": "isolate_host", # approval-required → no auto-execution
+ "target": "host-1",
+}
+
+
+def test_route_requires_token_when_configured(monkeypatch):
+ client = _client(monkeypatch, AISOC_ACTIONS_SERVICE_TOKEN="s3cr3t", AISOC_DEV_MODE="false")
+ assert client.post("/actions", json=_BODY).status_code == 401
+ ok = client.post("/actions", json=_BODY, headers={"Authorization": "Bearer s3cr3t"})
+ assert ok.status_code != 401
+
+
+def test_route_open_in_dev_without_token(monkeypatch):
+ client = _client(monkeypatch, AISOC_DEV_MODE="true")
+ assert client.post("/actions", json=_BODY).status_code == 200
+
+
+def test_route_fails_closed_in_prod_without_token(monkeypatch):
+ client = _client(monkeypatch, AISOC_DEV_MODE="false")
+ assert client.post("/actions", json=_BODY).status_code == 503
+
+
+def teardown_module(_module):
+ get_settings.cache_clear()