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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Approving an action now executes it (#731)
Beenu Arora4ea868520c35
diff --git a/docker-compose.yml b/docker-compose.ymlindex 50b386c34..7b7c880b5 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -256,6 +256,12 @@ services:# (translation, hunts, KB, phishing, NL-detection) through the gateway by# setting OPENAI_BASE_URL=http://litellm:4000/v1 + OPENAI_API_KEY=$LITELLM_MASTER_KEY.LLM_GATEWAY_URL: http://litellm:4000/v1+ # services/actions — where an approved response action is executed.+ # The API had no pointer to it at all: the one endpoint that called it+ # read the URL from os.environ and fell back to `aisoc-actions`, which+ # is the container_name, not the DNS name on this network.+ AISOC_ACTIONS_BASE_URL: http://actions:8085+ AISOC_ACTIONS_SERVICE_TOKEN: ${AISOC_ACTIONS_SERVICE_TOKEN:-}# Phase 2.6 — use /readyz, not /health, so the orchestrator# only routes traffic once the lifespan has finished wiring# Postgres, Redis, Kafka, Qdrant, and Neo4j. (Not OpenSearch: this@@ -520,6 +526,12 @@ services:REDIS_URL: redis://:redis_dev_secret@redis:6379/5DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisocCORE_API_URL: http://api:8000+ # Must match AISOC_ACTIONS_SERVICE_TOKEN on the api and slack-bot+ # services. Unset in dev, where AISOC_DEV_MODE relaxes the check;+ # require_service_auth returns 503 on every mutating route without it+ # in any other environment, which is the intended failure.+ AISOC_ACTIONS_SERVICE_TOKEN: ${AISOC_ACTIONS_SERVICE_TOKEN:-}+ AISOC_DEV_MODE: ${AISOC_DEV_MODE:-1}networks:- aisocrestart: unless-stoppeddiff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 1f8db3abf..69b7b785a 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -8043,6 +8043,138 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/live-actions:+ get:+ tags:+ - actions+ summary: List every registered live action+ operationId: discover_api_v1_live_actions_get+ security:+ - HTTPBearer: []+ parameters:+ - name: vendor_id+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: Vendor Id+ - name: capability+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: Capability+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ title: Response Discover Api V1 Live Actions Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/live-actions/by-capability/{capability}:+ get:+ tags:+ - actions+ summary: Vendors implementing a capability+ operationId: vendors_for_capability_api_v1_live_actions_by_capability__capability__get+ security:+ - HTTPBearer: []+ parameters:+ - name: capability+ in: path+ required: true+ schema:+ type: string+ title: Capability+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ title: Response Vendors For Capability Api V1 Live Actions By Capability Capability Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/live-actions/by-vendor/{vendor_id}:+ get:+ tags:+ - actions+ summary: Capabilities a vendor supports+ operationId: capabilities_for_vendor_api_v1_live_actions_by_vendor__vendor_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: vendor_id+ in: path+ required: true+ schema:+ type: string+ title: Vendor Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ title: Response Capabilities For Vendor Api V1 Live Actions By Vendor Vendor+ Id Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/live-actions/dry-run:+ post:+ tags:+ - actions+ summary: Preview a live action without touching a vendor+ description: 'Proxy a dry run, with the tenant taken from the session.+++ Only ``/dry-run`` is proxied, never ``/dispatch``. Upstream, ``/dry-run``++ forces ``dry_run=true`` server-side regardless of the body, so a client++ cannot talk its way into a live vendor call through this route.'+ operationId: dry_run_api_v1_live_actions_dry_run_post+ requestBody:+ content:+ application/json:+ schema:+ additionalProperties: true+ type: object+ title: Body+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ title: Response Dry Run Api V1 Live Actions Dry Run Post+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/saved-views:get:tags:diff --git a/services/actions/app/api/router.py b/services/actions/app/api/router.pyindex abe1dd1a2..215178ae6 100644--- a/services/actions/app/api/router.py+++ b/services/actions/app/api/router.py@@ -71,6 +71,12 @@ async def submit_action(request: ActionRequest, _auth: None = Depends(require_se# 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,+ # Kept so approve can rebuild the request faithfully. Without this the+ # approve path reconstructed an ActionRequest with an empty+ # `parameters`, so an action that was gated *because* of what it+ # targets executed against defaults — and reported COMPLETED. An+ # approval that silently changes what it approved is not an approval.+ "parameters": dict(request.parameters or {}),}_actions[str(request.id)] = record@@ -181,7 +187,9 @@ async def approve_action(if bound is not None:record["approved_by_user_id"] = bound.user_id- # Reconstruct request and execute+ # Reconstruct the request as submitted, parameters included. Dropping+ # them turned an approved action into a different action that still+ # reported success.request = ActionRequest(id=UUID(action_id),incident_id=UUID(record["incident_id"]),@@ -189,6 +197,10 @@ async def approve_action(action_type=ActionType(record["action_type"]),target=record["target"],rationale=record["rationale"],+ parameters=dict(record.get("parameters") or {}),+ # The bound approver, not the original requester: the executor's+ # authorization has to evaluate the identity that authorised this run.+ principal=bound,)executor = EXECUTOR_REGISTRY.get(request.action_type)diff --git a/services/actions/tests/test_approve_preserves_request.py b/services/actions/tests/test_approve_preserves_request.pynew file mode 100644index 000000000..f6adb1bb1--- /dev/null+++ b/services/actions/tests/test_approve_preserves_request.py@@ -0,0 +1,163 @@+"""An approved action must be the action that was approved.++``approve_action`` rebuilt the ``ActionRequest`` from the stored record and+omitted two fields: ``parameters`` and ``principal``. So an action gated+*because* of what it targets executed against empty parameters and reported+COMPLETED, and the executor's own authorization saw no identity behind the+run. An approval that silently changes what it approved is not an approval.++The record never carried ``parameters`` at all, so this is not a rebuild bug+alone — the submit path discarded them too, and nothing downstream could have+recovered them.+"""++from __future__ import annotations++import json+from uuid import uuid4++import pytest+from app.api import router as router_module+from app.core.config import get_settings+from app.models.action import (+ ActionPrincipal,+ ActionRequest,+ ActionResult,+ ActionStatus,+ ActionType,+ BlastRadius,+)+from app.security import chatops_identity++APPROVER_MAP = {+ "slack": {+ "U_LEAD": {+ "user_id": "[email protected]",+ "permissions": ["actions:execute:high", "actions:execute:critical"],+ "roles": ["soc-lead"],+ }+ }+}++[email protected](autouse=True)+def _approver_map(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_CHATOPS_APPROVERS", json.dumps(APPROVER_MAP))+ get_settings.cache_clear()+ chatops_identity.reset_cache()+ yield+ get_settings.cache_clear()+ chatops_identity.reset_cache()++[email protected](autouse=True)+def _clean_store():+ router_module._actions.clear()+ yield+ router_module._actions.clear()+++class _CapturingExecutor:+ """Records the request it was handed, so the test can inspect it."""++ def __init__(self) -> None:+ self.seen: ActionRequest | None = None++ async def execute(self, request: ActionRequest):+ self.seen = request+ return ActionResult(+ action_id=request.id,+ status=ActionStatus.COMPLETED,+ blast_radius=BlastRadius.HIGH,+ output={"ok": True},+ )+++def _request(**overrides) -> ActionRequest:+ kwargs = {+ "id": uuid4(),+ "incident_id": uuid4(),+ "tenant_id": uuid4(),+ "action_type": ActionType.ISOLATE_HOST,+ "target": "WKSTN-01",+ "rationale": "confirmed beacon",+ "parameters": {"reason": "c2", "duration_minutes": 60},+ # The requester needs the action's own permission to submit it at all+ # (W4.2 least-privilege), and must differ from the approver so+ # separation of duties has something to separate.+ "principal": ActionPrincipal(+ user_id="[email protected]",+ permissions=["actions:execute:high"],+ ),+ }+ kwargs.update(overrides)+ return ActionRequest(**kwargs)+++async def test_submit_persists_the_parameters(monkeypatch: pytest.MonkeyPatch):+ """The record had no `parameters` key at all, so approve could not have+ restored them however carefully it was written."""+ executor = _CapturingExecutor()+ monkeypatch.setitem(router_module.EXECUTOR_REGISTRY, ActionType.ISOLATE_HOST, executor)++ request = _request()+ record = await router_module.submit_action(request)++ assert record["parameters"] == {"reason": "c2", "duration_minutes": 60}+++async def test_an_approved_action_executes_with_its_parameters(monkeypatch: pytest.MonkeyPatch):+ executor = _CapturingExecutor()+ monkeypatch.setitem(router_module.EXECUTOR_REGISTRY, ActionType.ISOLATE_HOST, executor)++ request = _request()+ record = await router_module.submit_action(request)+ assert record["status"] == ActionStatus.AWAITING_APPROVAL, "isolate_host must be gated for this test to mean anything"++ await router_module.approve_action(+ str(request.id),+ chatops_approver=router_module.ChatOpsApprover(platform="slack", platform_user_id="U_LEAD"),+ )++ assert executor.seen is not None+ assert executor.seen.parameters == {"reason": "c2", "duration_minutes": 60}+++async def test_the_executor_sees_the_approver_not_nobody(monkeypatch: pytest.MonkeyPatch):+ """The executor's own authorization has to evaluate the identity that+ authorised this run, and it was handed None."""+ executor = _CapturingExecutor()+ monkeypatch.setitem(router_module.EXECUTOR_REGISTRY, ActionType.ISOLATE_HOST, executor)++ request = _request()+ await router_module.submit_action(request)+ await router_module.approve_action(+ str(request.id),+ chatops_approver=router_module.ChatOpsApprover(platform="slack", platform_user_id="U_LEAD"),+ )++ assert executor.seen is not None+ assert executor.seen.principal is not None+ assert executor.seen.principal.user_id == "[email protected]"+++async def test_identity_target_and_rationale_still_survive(monkeypatch: pytest.MonkeyPatch):+ executor = _CapturingExecutor()+ monkeypatch.setitem(router_module.EXECUTOR_REGISTRY, ActionType.ISOLATE_HOST, executor)++ request = _request()+ await router_module.submit_action(request)+ await router_module.approve_action(+ str(request.id),+ chatops_approver=router_module.ChatOpsApprover(platform="slack", platform_user_id="U_LEAD"),+ )++ assert executor.seen is not None+ assert executor.seen.id == request.id+ assert executor.seen.target == "WKSTN-01"+ assert executor.seen.rationale == "confirmed beacon"+ assert executor.seen.tenant_id == request.tenant_iddiff --git a/services/agents/app/investigator/ledger.py b/services/agents/app/investigator/ledger.pyindex 82964246d..c5b2164dc 100644--- a/services/agents/app/investigator/ledger.py+++ b/services/agents/app/investigator/ledger.py@@ -535,6 +535,106 @@ async def persist_auto_triage(raise LedgerPersistError(str(exc)) from exc+async def raise_approval(+ *,+ tenant_ref: str,+ run_id: uuid.UUID | None,+ alert_id: Any,+ title: str,+ summary: str,+ risk_level: str,+ action: dict[str, Any],+ requested_by: str = "agent",+) -> uuid.UUID | None:+ """Queue a proposed action for human sign-off, returning the approval id.++ The ``agent_approvals`` table, its API and the whole responder-app+ approvals screen already existed. Nothing ever inserted a row: the API+ docstring said "the agents service calls this" and a grep of this service+ for ``approvals`` returned nothing. So the queue was structurally empty on+ every deployment, and the feature was indistinguishable from a working one+ that simply had no pending work.++ Written from here rather than over HTTP because this is where the rest of+ the triage outcome is persisted, under the same pool and the same RLS+ context, so an approval cannot end up recorded against a verdict that+ failed to save. Best-effort in the same sense as the other ledger writes:+ no database or an unknown tenant is a no-op, because a triage verdict is+ still worth having without one.++ ``ON CONFLICT DO NOTHING`` on the deterministic id makes a Kafka replay+ re-raise the same approval rather than a second copy of it — an operator+ seeing the same containment request twice cannot tell which one is live.+ """+ pool = await get_pool()+ if pool is None:+ return None+ try:+ async with pool.acquire() as conn:+ tenant_id = await _resolve_tenant_id(conn, tenant_ref)+ if tenant_id is None:+ logger.warning(+ "ledger.approval_skipped_unknown_tenant",+ tenant_ref=tenant_ref,+ run_id=str(run_id) if run_id else None,+ )+ return None+ await _set_rls_context(conn, tenant_id)+ approval_id = _deterministic_approval_id(tenant_id, run_id, action)+ await conn.execute(+ """+ INSERT INTO agent_approvals+ (id, tenant_id, run_id, alert_id, requested_by, title,+ summary, risk_level, action, status, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'pending', now(), now())+ ON CONFLICT (id) DO NOTHING+ """,+ approval_id,+ tenant_id,+ run_id,+ _coerce_uuid(alert_id),+ requested_by[:120],+ title[:200],+ summary,+ risk_level[:20],+ json.dumps(action),+ )+ # The id is returned whether the insert landed or the conflict+ # clause fired: either way this is the approval that governs this+ # action, and a replay must point at the one already queued.+ return approval_id+ except Exception as exc: # noqa: BLE001 — an approval write must not fail triage+ logger.warning(+ "ledger.raise_approval_failed",+ tenant_ref=tenant_ref,+ run_id=str(run_id) if run_id else None,+ error=str(exc),+ )+ return None+++def _deterministic_approval_id(+ tenant_id: uuid.UUID,+ run_id: uuid.UUID | None,+ action: dict[str, Any],+) -> uuid.UUID:+ """One approval per (tenant, run, action type, target), stable across replays."""+ key = "|".join(+ [+ str(tenant_id),+ str(run_id or ""),+ str(action.get("action_type") or ""),+ str(action.get("target") or ""),+ ]+ )+ return uuid.uuid5(_APPROVAL_NAMESPACE, key)+++#: Fixed namespace so an approval id is reproducible across processes and+#: restarts. Any constant UUID would do; this one is arbitrary and permanent.+_APPROVAL_NAMESPACE = uuid.UUID("6f1d3b6e-7a4f-5c2b-9f0a-2d5b8c1e4a37")++async def record_suppression(*,tenant_ref: str,diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex b71837462..434ace47b 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -85,6 +85,7 @@ _METRICS = {"ungrounded_demoted": 0,"persist_retries": 0,"dead_lettered": 0,+ "approvals_raised": 0,"errors": 0,}@@ -112,6 +113,17 @@ def _memory_writeback_enabled() -> bool:return _truthy("AISOC_AGENT_MEMORY_WRITEBACK")+def _approvals_enabled() -> bool:+ """Queue approval-requiring proposed actions for human sign-off.++ On by default. Queueing an approval executes nothing — the worker stays+ copilot-default — so the risk of leaving it on is a longer approvals+ list, while the cost of leaving it off is the pre-v9.0 behaviour where+ the queue had no producer. Disable with AISOC_AGENT_RAISE_APPROVALS=0.+ """+ return _truthy("AISOC_AGENT_RAISE_APPROVALS")++def _groundedness_gate_enabled() -> bool:"""Demote a verdict whose reasoning cites indicators the evidence lacks.@@ -473,6 +485,12 @@ class FusedAlertTriageWorker:if state.status is not AgentStatus.COMPLETED:await self._maybe_escalate(state)+ # Queue every action that needs sign-off so a human can actually give+ # it. Until v9.0 proposed actions were persisted as JSON and stopped+ # there, so "requires_approval" described an approval nobody could+ # grant — the responder app's queue had no producer at all.+ approvals = await self._raise_approvals(state)+return {"run_id": str(state.run_id),"incident_id": str(state.incident_id),@@ -483,9 +501,46 @@ class FusedAlertTriageWorker:"business_context_rules": bc_matched,# Copilot default: triage is read-only, response requires approval."response_dispatched": False,+ "approvals_raised": approvals,"proposed_actions": [{"action_type": a.action_type, "requires_approval": a.requires_approval} for a in state.proposed_actions],}+ async def _raise_approvals(self, state: InvestigationState) -> list[str]:+ """Queue each approval-requiring proposed action; return the ids.++ Only actions the agent itself marked ``requires_approval`` are+ queued. The ones it did not are still not executed — the worker is+ copilot-default and dispatches nothing — so this does not widen what+ the agent can do. It makes the subset that was always meant to reach a+ human reach one.+ """+ if not _approvals_enabled():+ return []+ raised: list[str] = []+ for action in state.proposed_actions:+ if not action.requires_approval:+ continue+ risk = action.risk_level.value if hasattr(action.risk_level, "value") else str(action.risk_level)+ approval_id = await ledger_module.raise_approval(+ tenant_ref=str(state.tenant_id),+ run_id=state.run_id,+ alert_id=(state.raw_alert or {}).get("id"),+ title=action.description[:200] or f"Approve {action.action_type}",+ summary=(action.rationale or action.description or "").strip()+ or f"The agent proposes {action.action_type} against {action.target}.",+ risk_level=risk,+ action={+ "action_type": action.action_type,+ "target": action.target,+ "parameters": dict(action.parameters or {}),+ "risk_level": risk,+ },+ )+ if approval_id is not None:+ raised.append(str(approval_id))+ _METRICS["approvals_raised"] += 1+ return raised+async def _maybe_suppress_from_memory(self,state: InvestigationState,diff --git a/services/agents/tests/test_raise_approvals.py b/services/agents/tests/test_raise_approvals.pynew file mode 100644index 000000000..ae3193803--- /dev/null+++ b/services/agents/tests/test_raise_approvals.py@@ -0,0 +1,166 @@+"""An action that needs approval has to reach somebody who can give it.++The `agent_approvals` table, the API on top of it and the whole responder-app+approvals screen all existed. Nothing inserted a row: the API docstring said+"the agents service calls this", and a grep of this service for `approvals`+returned nothing at all. So `requires_approval=True` described an approval+nobody could grant, and the queue was structurally empty on every deployment+— indistinguishable from a working feature with no pending work.+"""++from __future__ import annotations++import uuid++import pytest+from app.investigator import ledger as ledger_module+from app.models.state import ActionRisk, InvestigationState, ProposedAction+from app.workers.fused_alert_consumer import FusedAlertTriageWorker++TENANT = str(uuid.uuid4())+++def _state(*actions: ProposedAction) -> InvestigationState:+ state = InvestigationState(+ run_id=uuid.uuid4(),+ incident_id=uuid.uuid4(),+ tenant_id=uuid.UUID(TENANT),+ )+ state.raw_alert = {"id": str(uuid.uuid4())}+ state.proposed_actions = list(actions)+ return state+++def _action(**overrides) -> ProposedAction:+ kwargs = {+ "action_type": "isolate_host",+ "description": "Isolate WKSTN-01 pending review",+ "risk_level": ActionRisk.HIGH,+ "target": "WKSTN-01",+ "requires_approval": True,+ "rationale": "Confirmed C2 beacon.",+ "parameters": {"reason": "c2"},+ }+ kwargs.update(overrides)+ return ProposedAction(**kwargs)+++def raised(monkeypatch: pytest.MonkeyPatch) -> list[dict]:+ recorded: list[dict] = []++ async def _raise_approval(**kwargs):+ recorded.append(kwargs)+ return uuid.uuid4()++ monkeypatch.setattr(ledger_module, "raise_approval", _raise_approval)+ monkeypatch.delenv("AISOC_AGENT_RAISE_APPROVALS", raising=False)+ return recorded+++class TestWhatGetsQueued:+ @pytest.mark.asyncio+ async def test_an_approval_requiring_action_is_queued(self, raised):+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)+ ids = await worker._raise_approvals(_state(_action()))++ assert len(ids) == 1+ assert len(raised) == 1+ assert raised[0]["action"]["action_type"] == "isolate_host"+ assert raised[0]["action"]["target"] == "WKSTN-01"++ @pytest.mark.asyncio+ async def test_an_action_that_does_not_require_approval_is_not_queued(self, raised):+ """This does not widen what the agent can do. The worker dispatches+ nothing either way; it queues the subset that was always meant to+ reach a human."""+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)+ ids = await worker._raise_approvals(_state(_action(requires_approval=False)))++ assert ids == []+ assert raised == []++ @pytest.mark.asyncio+ async def test_parameters_survive_onto_the_approval(self, raised):+ """The approval is what the actions service is later rebuilt from, so+ losing parameters here means approving a different action."""+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)+ await worker._raise_approvals(_state(_action()))++ assert raised[0]["action"]["parameters"] == {"reason": "c2"}++ @pytest.mark.asyncio+ async def test_the_rationale_becomes_the_summary_a_human_reads(self, raised):+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)+ await worker._raise_approvals(_state(_action()))++ assert raised[0]["summary"] == "Confirmed C2 beacon."++ @pytest.mark.asyncio+ async def test_several_actions_each_get_their_own_approval(self, raised):+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)+ ids = await worker._raise_approvals(+ _state(+ _action(),+ _action(action_type="disable_user", target="[email protected]"),+ )+ )++ assert len(ids) == 2+ assert {call["action"]["action_type"] for call in raised} == {"isolate_host", "disable_user"}+++class TestItStaysOptional:+ @pytest.mark.asyncio+ async def test_the_flag_turns_it_off(self, raised, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_AGENT_RAISE_APPROVALS", "0")+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)++ assert await worker._raise_approvals(_state(_action())) == []+ assert raised == []++ @pytest.mark.asyncio+ async def test_a_ledger_failure_does_not_fail_triage(self, monkeypatch: pytest.MonkeyPatch):+ """The verdict is the valuable thing and it is already durable. A+ database that cannot take the approval must not discard it."""++ async def _raise_approval(**_):+ return None++ monkeypatch.setattr(ledger_module, "raise_approval", _raise_approval)+ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)++ assert await worker._raise_approvals(_state(_action())) == []+++class TestIdempotency:+ def test_the_same_action_maps_to_the_same_approval_id(self):+ """A Kafka replay must re-raise the same approval, not a second copy:+ an operator seeing the same containment request twice cannot tell+ which one is live."""+ tenant = uuid.uuid4()+ run = uuid.uuid4()+ action = {"action_type": "isolate_host", "target": "WKSTN-01"}++ first = ledger_module._deterministic_approval_id(tenant, run, action)+ second = ledger_module._deterministic_approval_id(tenant, run, dict(action))++ assert first == second++ def test_a_different_target_is_a_different_approval(self):+ tenant = uuid.uuid4()+ run = uuid.uuid4()++ a = ledger_module._deterministic_approval_id(tenant, run, {"action_type": "isolate_host", "target": "a"})+ b = ledger_module._deterministic_approval_id(tenant, run, {"action_type": "isolate_host", "target": "b"})++ assert a != b++ def test_a_different_tenant_is_a_different_approval(self):+ run = uuid.uuid4()+ action = {"action_type": "isolate_host", "target": "WKSTN-01"}++ a = ledger_module._deterministic_approval_id(uuid.uuid4(), run, action)+ b = ledger_module._deterministic_approval_id(uuid.uuid4(), run, action)++ assert a != bdiff --git a/services/api/app/api/v1/endpoints/approvals.py b/services/api/app/api/v1/endpoints/approvals.pyindex 47924fcaa..cf32be74e 100644--- a/services/api/app/api/v1/endpoints/approvals.py+++ b/services/api/app/api/v1/endpoints/approvals.py@@ -6,6 +6,18 @@ approval request that lands here. The PWA polls and subscribes to pushnotifications so the on-call analyst can approve or deny in one tap,even from a phone.+That was the design, and for both of its halves it was only the design.+Nothing in the repository called ``POST /approvals``, so the queue had no+producer and the responder app's approvals screen was structurally empty; and+``decide`` flipped a row and notified the realtime service without ever+reaching ``services/actions``, so the queue had no executor either. Tapping+Approve recorded a decision and ran nothing, which is worse than a missing+feature: the operator is told the host was contained.++Both halves are closed in v9.0. ``services/agents`` posts here when triage+proposes an action that needs sign-off, and ``decide`` carries the decision+through to the actions service and records on the row whether it executed.+Endpoints---------* ``GET /approvals`` List pending/decided approvals.@@ -30,6 +42,7 @@ from app.api.v1.deps import AuthUser, require_permissionfrom app.core.config import settingsfrom app.db.rls import TenantDBSessionfrom app.models.responder import AgentApproval+from app.services.actions_client import ActionsServiceError, decide_action, submit_actionlogger = logging.getLogger(__name__)@@ -236,6 +249,15 @@ async def decide_approval(row.decided_at = datetime.now(UTC)row.decision_comment = body.comment+ # Dispatch before committing the decision, so an approval that the actions+ # service refuses does not leave a row reading "approved" against an+ # action that never ran. This endpoint used to flip the row and stop:+ # every tap of Approve in the responder app recorded a decision and+ # executed nothing, which is the most dangerous shape a security control+ # can have — it reports that the host was contained.+ dispatch = await _dispatch_decision(row, user, approve=body.decision == "approve")+ row.action = {**(row.action or {}), "dispatch": dispatch}+await db.commit()await db.refresh(row)@@ -243,9 +265,97 @@ async def decide_approval(# resume — fire-and-forget pattern matches the rest of the surface.await _notify_realtime(row, event="approval_decided")+ if dispatch.get("state") == "failed":+ # The decision is durable and the operator is told the truth: their+ # choice was recorded, the execution behind it was not accepted.+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=(+ f"Decision recorded, but the action service refused it: {dispatch.get('detail')}. "+ "The approval row reflects your decision; the action did not run."+ ),+ )+return ApprovalResponse.model_validate(row)+async def _dispatch_decision(+ row: AgentApproval,+ user: AuthUser,+ *,+ approve: bool,+) -> dict[str, Any]:+ """Carry a decision through to ``services/actions``.++ Returns a provenance record that is stored on the approval, so "was this+ actually executed" is answerable from the row rather than by correlating+ two services' logs. The four states are deliberately distinct:++ ``not_executable`` the approval names no action type, so there is+ nothing to run. Common and fine: an approval can+ gate a human step.+ ``declined`` the decision was to deny; the action was rejected+ upstream so it cannot later be approved by replay.+ ``executed`` the actions service accepted and ran it.+ ``failed`` the actions service refused or was unreachable.+ """+ action = row.action or {}+ action_type = action.get("action_type") or action.get("type")+ target = action.get("target")+ if not isinstance(action_type, str) or not action_type.strip():+ return {"state": "not_executable", "reason": "approval carries no action_type"}+ if not isinstance(target, str) or not target.strip():+ return {"state": "not_executable", "reason": "approval carries no target"}++ # The approval id is reused as the action id so the two systems share one+ # identifier. Without that, "which action did this approval authorise"+ # requires a join nobody wrote.+ action_id = str(row.id)+ principal = {+ "user_id": str(user.user_id),+ "email": getattr(user, "email", None),+ "roles": list(getattr(user, "roles", []) or []),+ "permissions": list(getattr(user, "permissions", []) or []),+ }++ try:+ await submit_action(+ action_id=action_id,+ action_type=action_type.strip(),+ target=target.strip(),+ tenant_id=str(row.tenant_id),+ incident_id=str(row.run_id or row.id),+ rationale=row.summary or row.title,+ parameters=action.get("parameters") or {},+ # The requester is the agent, not the approver. Sending the+ # approver here would make them both, and separation of duties+ # would pass by accident.+ requested_by=row.requested_by or "agent",+ )+ except ActionsServiceError as exc:+ logger.warning(+ "Approval dispatch: submit refused",+ extra={"approval_id": action_id, "status": exc.status_code, "detail": str(exc)},+ )+ return {"state": "failed", "stage": "submit", "detail": str(exc)}++ try:+ result = await decide_action(action_id=action_id, approve=approve, approver=principal)+ except ActionsServiceError as exc:+ logger.warning(+ "Approval dispatch: decision refused",+ extra={"approval_id": action_id, "status": exc.status_code, "detail": str(exc)},+ )+ return {"state": "failed", "stage": "decide", "detail": str(exc)}++ return {+ "state": "executed" if approve else "declined",+ "action_id": action_id,+ "action_status": result.get("status"),+ "blast_radius": result.get("blast_radius"),+ }++async def _notify_realtime(row: AgentApproval, *, event: str) -> None:"""Fan out an agent event to the realtime service.diff --git a/services/api/app/api/v1/endpoints/email_approval.py b/services/api/app/api/v1/endpoints/email_approval.pyindex 7f403089c..7a3e2a9e4 100644--- a/services/api/app/api/v1/endpoints/email_approval.py+++ b/services/api/app/api/v1/endpoints/email_approval.py@@ -33,24 +33,17 @@ from __future__ import annotationsimport os-import httpximport structlogfrom fastapi import APIRouter, Queryfrom fastapi.responses import HTMLResponse+from app.services.actions_client import ActionsServiceError, decide_actionfrom app.services.email_approval import EmailApprovalError, verify_tokenlogger = structlog.get_logger(__name__)router = APIRouter(prefix="/actions", tags=["actions"])-#: Matches the default in the actions service's own compose/Helm wiring.-_DEFAULT_ACTIONS_BASE_URL = "http://aisoc-actions:8085"---def _actions_base_url() -> str:- return os.environ.get("AISOC_ACTIONS_BASE_URL", _DEFAULT_ACTIONS_BASE_URL).rstrip("/")-def _signing_secret() -> str:return os.environ.get("AISOC_EMAIL_APPROVAL_SECRET", "").strip()@@ -129,62 +122,56 @@ async def email_decide(token: str = Query(..., description="Signed approval tokestatus_code=400,)- verb = "approve" if parsed.decision == "approved" else "reject"- payload = {- "chatops_approver": {- "platform": "email",- "platform_user_id": parsed.approver,- }- }- headers = {"Accept": "application/json"}- service_token = os.environ.get("AISOC_ACTIONS_SERVICE_TOKEN", "").strip()- if service_token:- headers["Authorization"] = f"Bearer {service_token}"-- url = f"{_actions_base_url()}/api/v1/actions/{parsed.action_id}/{verb}"try:- async with httpx.AsyncClient(timeout=15.0) as client:- response = await client.post(url, json=payload, headers=headers)- except httpx.HTTPError as exc:- logger.warning("email_approval.upstream_unreachable", action_id=parsed.action_id, error=str(exc))- return _page(- "The action service could not be reached",- "Your decision was not recorded. Try again, or use the console.",- status_code=502,- )-- if response.status_code == 400:- return _page(- "This action was already decided",- "Somebody has already approved or rejected it, so this link no longer applies. Approval links work once.",- status_code=409,- )- if response.status_code == 403:- detail = _detail(response)- logger.warning(- "email_approval.not_authorized",+ await decide_action(action_id=parsed.action_id,- approver=parsed.approver,- detail=detail,+ approve=parsed.decision == "approved",+ chatops_approver={"platform": "email", "platform_user_id": parsed.approver},)- return _page(- "You are not authorised to decide this action",- f"{detail} An email approver must be mapped under 'email' in "- "AISOC_CHATOPS_APPROVERS, and may not approve an action they "- "requested themselves.",- status_code=403,- )- if response.status_code == 404:- return _page("Action not found", "It may have been removed since the email was sent.", status_code=404)- if response.status_code >= 400:+ except ActionsServiceError as exc:+ status_code = exc.status_code+ if status_code is None:+ logger.warning("email_approval.upstream_unreachable", action_id=parsed.action_id, error=str(exc))+ return _page(+ "The action service could not be reached",+ "Your decision was not recorded. Try again, or use the console.",+ status_code=502,+ )+ if status_code == 400:+ return _page(+ "This action was already decided",+ "Somebody has already approved or rejected it, so this link no longer applies. Approval links work once.",+ status_code=409,+ )+ if status_code == 403:+ # Only ``upstream_detail`` reaches the page. The exception message+ # can carry a transport error with internal hostnames, and this+ # route is unauthenticated by necessity — the reader is holding an+ # email, not a session.+ detail = exc.upstream_detail+ logger.warning(+ "email_approval.not_authorized",+ action_id=parsed.action_id,+ approver=parsed.approver,+ detail=detail,+ )+ return _page(+ "You are not authorised to decide this action",+ f"{detail} An email approver must be mapped under 'email' in "+ "AISOC_CHATOPS_APPROVERS, and may not approve an action they "+ "requested themselves.",+ status_code=403,+ )+ if status_code == 404:+ return _page("Action not found", "It may have been removed since the email was sent.", status_code=404)logger.warning("email_approval.upstream_error",action_id=parsed.action_id,- status=response.status_code,+ status=status_code,)return _page("Your decision could not be recorded",- f"The action service returned {response.status_code}. Try the console instead.",+ f"The action service returned {status_code}. Try the console instead.",status_code=502,)@@ -199,12 +186,3 @@ async def email_decide(token: str = Query(..., description="Signed approval tokef"Recorded as {parsed.approver}. You can close this page.",status_code=200,)---def _detail(response: httpx.Response) -> str:- try:- body = response.json()- except ValueError:- return "The action service refused the decision."- detail = body.get("detail") if isinstance(body, dict) else None- return str(detail) if detail else "The action service refused the decision."diff --git a/services/api/app/api/v1/endpoints/live_actions.py b/services/api/app/api/v1/endpoints/live_actions.pynew file mode 100644index 000000000..35a06bfdc--- /dev/null+++ b/services/api/app/api/v1/endpoints/live_actions.py@@ -0,0 +1,152 @@+"""Browser-facing proxy for the live-action registry in ``services/actions``.++The action registry — which vendor can isolate which host, what each verb+costs in blast radius, what a dry run would do — is the answer to "what can+AiSOC actually do to my estate right now". It lived behind+``Depends(require_service_auth)`` on the actions service, reachable only by+another service holding the shared token. A repository-wide search for+``live-actions`` outside that service returned nothing: no console page, no+API route, no agent tool. The registry was complete and unreachable.++This proxy is the browser's way in, and it differs from the upstream in three+deliberate ways:++**It authenticates a person, not a service.** Every route requires a session+and a permission. The service token is added by this process on the way out,+so it never reaches a browser.++**It is read-mostly.** Discovery and dry-run are proxied; live dispatch is+not. A live containment must go through the approval path, which records who+authorised it — exposing ``/dispatch`` here would be a way to execute the+most disruptive actions in the product with no approver bound, which is the+exact hole the ChatOps work closed.++**Tenant comes from the session.** A dry-run request carries a tenant, and+accepting the client's copy of it would let any authenticated user preview+actions against another tenant's assets.+"""++from __future__ import annotations++import re+from typing import Annotated, Any++import httpx+import structlog+from fastapi import APIRouter, Depends, HTTPException, Query, status++from app.api.v1.deps import AuthUser, require_permission+from app.services.actions_client import base_url, service_headers++logger = structlog.get_logger(__name__)++router = APIRouter(prefix="/live-actions", tags=["actions"])++_TIMEOUT_SECONDS = 20.0++#: Capability verbs and vendor ids are short identifiers from a closed+#: vocabulary. Interpolating one into the upstream path unchecked lets the+#: caller steer the request somewhere else entirely — `../../admin` is a+#: perfectly good "capability" as far as string formatting is concerned, and+#: the service token this proxy attaches would go with it.+#:+#: Refused at the edge rather than percent-encoded. Encoding would turn a+#: hostile value into a harmless upstream 404 while still forwarding it;+#: rejecting says what happened and keeps the request inside this process.+_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")+++def _safe_segment(value: str, *, field: str) -> str:+ if not _IDENTIFIER.match(value):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"{field} must be a short identifier of letters, digits, dot, dash or underscore.",+ )+ return value+++async def _get(path: str, params: dict[str, Any] | None = None) -> Any:+ url = f"{base_url()}/api/v1/live-actions{path}"+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client:+ response = await client.get(url, headers=service_headers(), params=params)+ except httpx.HTTPError as exc:+ logger.warning("live_actions.unreachable", path=path, error=str(exc))+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail="The action service is unreachable. It runs in the `full` and `chatops` compose profiles.",+ ) from exc+ return _unwrap(response, path)+++def _unwrap(response: httpx.Response, path: str) -> Any:+ if response.status_code >= 400:+ logger.warning("live_actions.upstream_error", path=path, status=response.status_code)+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"The action service returned {response.status_code}.",+ )+ try:+ return response.json()+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail="The action service returned a non-JSON body.",+ ) from exc++[email protected]("", summary="List every registered live action")+async def discover(+ user: Annotated[AuthUser, Depends(require_permission("actions:read"))],+ vendor_id: str | None = Query(default=None),+ capability: str | None = Query(default=None),+) -> Any:+ params: dict[str, Any] = {}+ if vendor_id:+ params["vendor_id"] = _safe_segment(vendor_id, field="vendor_id")+ if capability:+ params["capability"] = _safe_segment(capability, field="capability")+ return await _get("", params or None)++[email protected]("/by-capability/{capability}", summary="Vendors implementing a capability")+async def vendors_for_capability(+ capability: str,+ user: Annotated[AuthUser, Depends(require_permission("actions:read"))],+) -> Any:+ safe = _safe_segment(capability, field="capability")+ return await _get(f"/by-capability/{safe}")++[email protected]("/by-vendor/{vendor_id}", summary="Capabilities a vendor supports")+async def capabilities_for_vendor(+ vendor_id: str,+ user: Annotated[AuthUser, Depends(require_permission("actions:read"))],+) -> Any:+ safe = _safe_segment(vendor_id, field="vendor_id")+ return await _get(f"/by-vendor/{safe}")++[email protected]("/dry-run", summary="Preview a live action without touching a vendor")+async def dry_run(+ body: dict[str, Any],+ user: Annotated[AuthUser, Depends(require_permission("actions:execute"))],+) -> Any:+ """Proxy a dry run, with the tenant taken from the session.++ Only ``/dry-run`` is proxied, never ``/dispatch``. Upstream, ``/dry-run``+ forces ``dry_run=true`` server-side regardless of the body, so a client+ cannot talk its way into a live vendor call through this route.+ """+ payload = {**body, "tenant_id": str(user.tenant_id), "dry_run": True}+ url = f"{base_url()}/api/v1/live-actions/dry-run"+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client:+ response = await client.post(url, headers=service_headers(), json=payload)+ except httpx.HTTPError as exc:+ logger.warning("live_actions.unreachable", path="/dry-run", error=str(exc))+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail="The action service is unreachable. It runs in the `full` and `chatops` compose profiles.",+ ) from exc+ return _unwrap(response, "/dry-run")diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 0b3465477..76951b9b8 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -45,6 +45,7 @@ from app.api.v1.endpoints import (investigations,knowledge_base,lake,+ live_actions,llm_credentials,llm_status,marketplace,@@ -167,6 +168,13 @@ api_router.include_router(oncall.router)api_router.include_router(approvals.router)api_router.include_router(passkeys.router)+# The live-action registry, proxied for the browser. Upstream it sits behind+# a service token, so before this every route that answers "what can AiSOC do+# to my estate" was reachable only by another service. Discovery and dry-run+# only: a live dispatch goes through the approval path so an approver is+# bound to it.+api_router.include_router(live_actions.router)+# Per-user saved views — WS-F3 (analyst quality-of-life).# Backs the saved-views menu on Alerts/Cases/Investigations/Playbooks# list pages. Per-user-per-tenant CRUD; tenant scoping via RLS, userdiff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 54fca4a48..98a65efe2 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -397,6 +397,14 @@ class Settings(BaseSettings):REALTIME_BASE_URL: str = "http://realtime:8086"REALTIME_INTERNAL_TOKEN: str = ""+ # services/actions — where a governed response action is actually+ # executed. These were read inline with os.environ.get from one endpoint,+ # which is why the default was wrong: `aisoc-actions` is the compose+ # container_name, and the DNS name on the network is the service name,+ # `actions`. Nothing noticed because the only caller was a fallback path.+ AISOC_ACTIONS_BASE_URL: str = "http://actions:8085"+ AISOC_ACTIONS_SERVICE_TOKEN: str = ""+# SAML/OIDC session token signing secret. Consumed by ``app/auth/saml.py``# and ``app/auth/oidc.py`` to mint AiSOC session JWTs after an external# identity provider returns a successful authn response. We surface thisdiff --git a/services/api/app/core/security.py b/services/api/app/core/security.pyindex 2bf56df34..aa863fe88 100644--- a/services/api/app/core/security.py+++ b/services/api/app/core/security.py@@ -63,6 +63,13 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# permission only controls who *can* query at all."lake:query","lake:read_schema",+ # The live-action registry: which vendors can perform which response+ # verbs against this tenant's estate, and what a given action would+ # do. `actions:execute` gates the dry-run preview only — a live+ # containment goes through the approval path, where an approver is+ # bound to the decision.+ "actions:read",+ "actions:execute",],"soc_lead": ["alerts:read",@@ -85,6 +92,8 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# SOC leads run investigations across the lake routinely."lake:query","lake:read_schema",+ "actions:read",+ "actions:execute",],"soc_analyst": ["alerts:read",@@ -101,6 +110,10 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# the rate limiter caps abuse."lake:query","lake:read_schema",+ # Analysts already hold playbooks:execute, and a dry run touches no+ # vendor, so previewing a response is within the same envelope.+ "actions:read",+ "actions:execute",],"threat_hunter": ["alerts:read",@@ -116,12 +129,16 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# events, alert metrics, and IOC enrichments."lake:query","lake:read_schema",+ # Read the registry to know what response is available for a finding;+ # hunters hand off rather than respond, so no execute.+ "actions:read",],"viewer": ["alerts:read","cases:read","reports:read","threat_intel:read",+ "actions:read",],"api_service": ["alerts:read",diff --git a/services/api/app/services/actions_client.py b/services/api/app/services/actions_client.pynew file mode 100644index 000000000..fc67849ef--- /dev/null+++ b/services/api/app/services/actions_client.py@@ -0,0 +1,157 @@+"""The API service's client for ``services/actions``.++``services/actions`` owns execution: the executor registry, the vendor+clients and the blast-radius gate all live there, and it is the only service+that can actually isolate a host. Everything else — the console, the+responder app, the email link, the agents worker — has to reach it over HTTP.++Until now exactly one endpoint did, with the base URL read inline from+``os.environ``, and the default it fell back to was wrong: ``aisoc-actions``+is the compose ``container_name``, while the DNS name on the network is the+service name, ``actions``. Nothing caught it because the only code path that+used the default was itself a fallback nobody exercised.++One client, one contract, one place to fix the next thing.+"""++from __future__ import annotations++from typing import Any++import httpx+import structlog++from app.core.config import settings++logger = structlog.get_logger(__name__)++#: Generous relative to an internal hop, because an approved action runs the+#: real vendor call inline: the actions service executes on approve rather+#: than queueing, so this timeout covers a CrowdStrike or Okta round trip.+_TIMEOUT_SECONDS = 30.0+++class ActionsServiceError(RuntimeError):+ """The actions service refused or could not be reached.++ Carries the upstream status when there was one, so a caller can map a+ refusal (403, 409) differently from an outage (None, 502).++ ``upstream_detail`` is the only field safe to show a user. The exception+ message can include a transport error, which carries internal hostnames+ and occasionally a stack frame; the detail is the actions service's own+ operator-facing string, which it deliberately builds as an error *type*+ rather than a raw exception. Rendering the wrong one into an HTML page is+ how an unauthenticated email-approval link starts leaking topology.+ """++ def __init__(+ self,+ message: str,+ *,+ status_code: int | None = None,+ upstream_detail: str | None = None,+ ) -> None:+ super().__init__(message)+ self.status_code = status_code+ self.upstream_detail = upstream_detail or "The action service refused the decision."+++def base_url() -> str:+ return settings.AISOC_ACTIONS_BASE_URL.rstrip("/")+++def service_headers() -> dict[str, str]:+ """Headers for a service-to-service call to the actions service.++ The bearer token is added here and only here, so it cannot leak into a+ browser-facing response: routes that proxy on a user's behalf call this+ rather than forwarding whatever the client sent.+ """+ headers = {"Accept": "application/json"}+ token = settings.AISOC_ACTIONS_SERVICE_TOKEN.strip()+ if token:+ headers["Authorization"] = f"Bearer {token}"+ return headers+++async def _post(path: str, payload: dict[str, Any] | None) -> dict[str, Any]:+ url = f"{base_url()}{path}"+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client:+ response = await client.post(url, headers=service_headers(), json=payload)+ except httpx.HTTPError as exc:+ raise ActionsServiceError(f"actions service unreachable: {exc}") from exc++ if response.status_code >= 400:+ detail = _detail(response)+ raise ActionsServiceError(detail, status_code=response.status_code, upstream_detail=detail)++ try:+ body = response.json()+ except ValueError as exc:+ raise ActionsServiceError("actions service returned a non-JSON body") from exc+ if not isinstance(body, dict):+ raise ActionsServiceError("actions service returned an unexpected body shape")+ return body+++def _detail(response: httpx.Response) -> str:+ try:+ payload = response.json()+ except ValueError:+ return f"actions service returned {response.status_code}"+ if isinstance(payload, dict):+ detail = payload.get("detail")+ if isinstance(detail, str) and detail.strip():+ return detail+ return f"actions service returned {response.status_code}"+++async def submit_action(+ *,+ action_id: str,+ action_type: str,+ target: str,+ tenant_id: str,+ incident_id: str,+ rationale: str,+ parameters: dict[str, Any] | None = None,+ principal: dict[str, Any] | None = None,+ requested_by: str = "aisoc-api",+) -> dict[str, Any]:+ """Submit an action. The gate decides whether it executes or waits."""+ payload: dict[str, Any] = {+ "id": action_id,+ "action_type": action_type,+ "target": target,+ "tenant_id": tenant_id,+ "incident_id": incident_id,+ "rationale": rationale,+ "requested_by": requested_by,+ "parameters": parameters or {},+ }+ if principal is not None:+ payload["principal"] = principal+ return await _post("/api/v1/actions", payload)+++async def decide_action(+ *,+ action_id: str,+ approve: bool,+ approver: dict[str, Any] | None = None,+ chatops_approver: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Approve or reject a pending action, carrying the deciding identity.++ An approval with no resolvable identity is refused upstream by default,+ because separation of duties cannot be evaluated against nobody.+ """+ verb = "approve" if approve else "reject"+ body: dict[str, Any] = {}+ if approver is not None:+ body["approver"] = approver+ if chatops_approver is not None:+ body["chatops_approver"] = chatops_approver+ return await _post(f"/api/v1/actions/{action_id}/{verb}", body or None)diff --git a/services/api/tests/test_approval_dispatch.py b/services/api/tests/test_approval_dispatch.pynew file mode 100644index 000000000..7399052e5--- /dev/null+++ b/services/api/tests/test_approval_dispatch.py@@ -0,0 +1,188 @@+"""Approving an action has to execute it.++``POST /approvals/{id}/decide`` flipped a row, notified the realtime service+and returned 200. It never touched ``services/actions``. So every tap of+Approve in the responder app recorded a decision and executed nothing, while+telling the operator the opposite — the worst shape a security control can+have, because "the host is contained" is exactly what it appeared to say.++These tests drive ``_dispatch_decision`` directly. The endpoint around it+needs a session, a tenant DB and RLS; the dispatch decision is the part that+was missing, and it is pure enough to pin on its own.+"""++from __future__ import annotations++import uuid+from types import SimpleNamespace++import pytest+from app.api.v1.endpoints import approvals as endpoint+from app.services.actions_client import ActionsServiceError++TENANT = uuid.uuid4()+USER = uuid.uuid4()+++def _row(**overrides):+ row = SimpleNamespace(+ id=uuid.uuid4(),+ tenant_id=TENANT,+ run_id=uuid.uuid4(),+ requested_by="agent",+ title="Isolate WKSTN-01",+ summary="Falcon detection with confirmed C2 beacon.",+ action={"action_type": "isolate_host", "target": "WKSTN-01", "parameters": {"reason": "c2"}},+ )+ for key, value in overrides.items():+ setattr(row, key, value)+ return row+++def _user():+ return SimpleNamespace(+ user_id=USER,+ tenant_id=TENANT,+ email="[email protected]",+ roles=["soc_lead"],+ permissions=["cases:write"],+ )+++def calls(monkeypatch: pytest.MonkeyPatch) -> dict:+ recorded: dict = {"submit": [], "decide": []}++ async def _submit(**kwargs):+ recorded["submit"].append(kwargs)+ return {"id": kwargs["action_id"], "status": "awaiting_approval"}++ async def _decide(**kwargs):+ recorded["decide"].append(kwargs)+ return {"status": "completed", "blast_radius": "high"}++ monkeypatch.setattr(endpoint, "submit_action", _submit)+ monkeypatch.setattr(endpoint, "decide_action", _decide)+ return recorded+++class TestTheHappyPath:+ @pytest.mark.asyncio+ async def test_an_approval_submits_then_approves(self, calls):+ row = _row()+ result = await endpoint._dispatch_decision(row, _user(), approve=True)++ assert result["state"] == "executed"+ assert result["action_status"] == "completed"+ assert len(calls["submit"]) == 1+ assert len(calls["decide"]) == 1+ assert calls["decide"][0]["approve"] is True++ @pytest.mark.asyncio+ async def test_the_approval_id_is_reused_as_the_action_id(self, calls):+ """Otherwise 'which action did this approval authorise' needs a join+ nobody wrote."""+ row = _row()+ await endpoint._dispatch_decision(row, _user(), approve=True)++ assert calls["submit"][0]["action_id"] == str(row.id)+ assert calls["decide"][0]["action_id"] == str(row.id)++ @pytest.mark.asyncio+ async def test_parameters_reach_the_actions_service(self, calls):+ row = _row()+ await endpoint._dispatch_decision(row, _user(), approve=True)++ assert calls["submit"][0]["parameters"] == {"reason": "c2"}++ @pytest.mark.asyncio+ async def test_the_requester_is_the_agent_not_the_approver(self, calls):+ """Sending the approver as requester would make them both, and+ separation of duties would pass by accident."""+ row = _row()+ await endpoint._dispatch_decision(row, _user(), approve=True)++ assert calls["submit"][0]["requested_by"] == "agent"+ assert calls["decide"][0]["approver"]["user_id"] == str(USER)++ @pytest.mark.asyncio+ async def test_tenant_comes_from_the_row(self, calls):+ row = _row()+ await endpoint._dispatch_decision(row, _user(), approve=True)++ assert calls["submit"][0]["tenant_id"] == str(TENANT)+++class TestDenial:+ @pytest.mark.asyncio+ async def test_a_denial_rejects_upstream(self, calls):+ """Rejecting upstream matters: it moves the action out of+ awaiting_approval so a replayed approval link cannot later run it."""+ row = _row()+ result = await endpoint._dispatch_decision(row, _user(), approve=False)++ assert result["state"] == "declined"+ assert calls["decide"][0]["approve"] is False+++class TestNothingToRun:+ @pytest.mark.asyncio+ async def test_an_approval_with_no_action_type_is_not_executable(self, calls):+ # A normal case: an approval can gate a human step.+ row = _row(action={"target": "WKSTN-01"})+ result = await endpoint._dispatch_decision(row, _user(), approve=True)++ assert result["state"] == "not_executable"+ assert calls["submit"] == []++ @pytest.mark.asyncio+ async def test_an_approval_with_no_target_is_not_executable(self, calls):+ row = _row(action={"action_type": "isolate_host"})+ result = await endpoint._dispatch_decision(row, _user(), approve=True)++ assert result["state"] == "not_executable"+ assert calls["submit"] == []+++class TestFailureIsVisible:+ @pytest.mark.asyncio+ async def test_a_refused_submit_reports_failed(self, monkeypatch: pytest.MonkeyPatch):+ async def _submit(**_):+ raise ActionsServiceError("blast radius exceeds tier", status_code=403)++ monkeypatch.setattr(endpoint, "submit_action", _submit)+ result = await endpoint._dispatch_decision(_row(), _user(), approve=True)++ assert result["state"] == "failed"+ assert result["stage"] == "submit"+ assert "blast radius" in result["detail"]++ @pytest.mark.asyncio+ async def test_a_refused_decision_reports_which_stage(self, monkeypatch: pytest.MonkeyPatch):+ """submit succeeded and decide did not, which is a different operator+ problem from the service being down."""++ async def _submit(**kwargs):+ return {"id": kwargs["action_id"]}++ async def _decide(**_):+ raise ActionsServiceError("approver may not approve their own action", status_code=403)++ monkeypatch.setattr(endpoint, "submit_action", _submit)+ monkeypatch.setattr(endpoint, "decide_action", _decide)+ result = await endpoint._dispatch_decision(_row(), _user(), approve=True)++ assert result["state"] == "failed"+ assert result["stage"] == "decide"++ @pytest.mark.asyncio+ async def test_an_unreachable_service_reports_failed_not_executed(self, monkeypatch: pytest.MonkeyPatch):+ async def _submit(**_):+ raise ActionsServiceError("actions service unreachable: refused")++ monkeypatch.setattr(endpoint, "submit_action", _submit)+ result = await endpoint._dispatch_decision(_row(), _user(), approve=True)++ # Never "executed". Claiming execution on an unreachable executor is+ # the failure mode this whole wave exists to remove.+ assert result["state"] == "failed"diff --git a/services/api/tests/test_email_approval_endpoint.py b/services/api/tests/test_email_approval_endpoint.pyindex c0f482e80..74d945ce0 100644--- a/services/api/tests/test_email_approval_endpoint.py+++ b/services/api/tests/test_email_approval_endpoint.py@@ -20,6 +20,7 @@ import jsonimport httpximport pytestfrom app.api.v1.endpoints import email_approval as endpoint+from app.services import actions_clientfrom app.services.email_approval import EmailApprovalError, approval_url, issue_token, verify_tokenfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -57,6 +58,14 @@ class _StubResponse:def _stub_post(monkeypatch: pytest.MonkeyPatch, response: _StubResponse, recorder: list | None = None):+ """Stub the transport, not the client.++ Patched at ``actions_client.httpx`` rather than in the endpoint, because+ the endpoint no longer builds its own request: URL construction, the+ service-token header and the status mapping all live in the shared+ client now, and stubbing above them would stop testing any of it.+ """+class _Client:async def __aenter__(self):return self@@ -69,7 +78,7 @@ def _stub_post(monkeypatch: pytest.MonkeyPatch, response: _StubResponse, recorderecorder.append({"url": url, "json": json, "headers": headers})return response- monkeypatch.setattr(endpoint.httpx, "AsyncClient", lambda **_: _Client())+ monkeypatch.setattr(actions_client.httpx, "AsyncClient", lambda **_: _Client())# ── the route exists at the path the emails link to ────────────────────────@@ -208,7 +217,42 @@ def test_an_unreachable_actions_service_does_not_claim_success(client: TestClienasync def post(self, *a, **k):raise httpx.ConnectError("refused")- monkeypatch.setattr(endpoint.httpx, "AsyncClient", lambda **_: _Client())+ monkeypatch.setattr(actions_client.httpx, "AsyncClient", lambda **_: _Client())res = client.get("/api/v1/actions/email-decide", params={"token": _token()})assert res.status_code == 502assert "not recorded" in res.text+++# ── the shared client, exercised through this route ────────────────────────+++def test_the_service_token_is_sent_when_configured(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(actions_client.settings, "AISOC_ACTIONS_SERVICE_TOKEN", "svc-token")+ calls: list[dict] = []+ _stub_post(monkeypatch, _StubResponse(200, {"status": "approved"}), calls)++ client.get("/api/v1/actions/email-decide", params={"token": _token()})++ assert calls[0]["headers"]["Authorization"] == "Bearer svc-token"+++def test_no_authorization_header_when_no_token_is_configured(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(actions_client.settings, "AISOC_ACTIONS_SERVICE_TOKEN", "")+ calls: list[dict] = []+ _stub_post(monkeypatch, _StubResponse(200, {"status": "approved"}), calls)++ client.get("/api/v1/actions/email-decide", params={"token": _token()})++ assert "Authorization" not in calls[0]["headers"]+++def test_the_default_base_url_is_the_compose_service_name(monkeypatch: pytest.MonkeyPatch) -> None:+ """The regression this pins.++ The base URL was read inline with ``os.environ.get`` and defaulted to+ ``http://aisoc-actions:8085`` — the compose ``container_name``, not the+ DNS name on the network, which is the service name ``actions``. Nothing+ noticed because the only path that used the default was a fallback.+ """+ monkeypatch.setattr(actions_client.settings, "AISOC_ACTIONS_BASE_URL", "http://actions:8085")+ assert actions_client.base_url() == "http://actions:8085"diff --git a/services/api/tests/test_live_actions_proxy.py b/services/api/tests/test_live_actions_proxy.pynew file mode 100644index 000000000..4db85611c--- /dev/null+++ b/services/api/tests/test_live_actions_proxy.py@@ -0,0 +1,82 @@+"""A proxy that attaches a service token must not let the caller aim it.++The first version of this proxy interpolated the capability and vendor id+straight into the upstream path. CodeQL called it correctly: `py/partial-ssrf`,+critical. ``../../admin`` is a perfectly good "capability" as far as string+formatting is concerned, and the service token this proxy adds on the way out+would have gone with the redirected request.++Refused at the edge rather than percent-encoded, because encoding turns a+hostile value into a harmless upstream 404 while still forwarding it, and a+404 tells an operator nothing about what was attempted.+"""++from __future__ import annotations++import pytest+from app.api.v1.endpoints import live_actions+from fastapi import HTTPException+++class TestPathSegmentGuard:+ @pytest.mark.parametrize(+ "value",+ [+ "isolate_host",+ "crowdstrike",+ "aws-security-groups",+ "vendor.name",+ "a",+ ],+ )+ def test_real_identifiers_are_accepted(self, value: str):+ assert live_actions._safe_segment(value, field="capability") == value++ @pytest.mark.parametrize(+ "value",+ [+ "../../admin",+ "..%2f..%2fadmin",+ "isolate_host/../../internal",+ "http://evil.example/steal",+ "host:8085/other",+ "capability?x=1",+ "with space",+ "",+ "/leading-slash",+ "trailing/",+ ],+ )+ def test_anything_that_could_steer_the_request_is_refused(self, value: str):+ with pytest.raises(HTTPException) as caught:+ live_actions._safe_segment(value, field="capability")+ assert caught.value.status_code == 400++ def test_the_refusal_names_the_field(self):+ """So an operator reading the 400 knows which parameter was wrong."""+ with pytest.raises(HTTPException) as caught:+ live_actions._safe_segment("../x", field="vendor_id")+ assert "vendor_id" in caught.value.detail++ def test_length_is_bounded(self):+ """An unbounded segment is a way to build an enormous upstream URL."""+ with pytest.raises(HTTPException):+ live_actions._safe_segment("a" * 200, field="capability")+++class TestWhatIsProxied:+ def test_live_dispatch_is_not_exposed(self):+ """A live containment must carry an approver, which this proxy cannot+ supply. Only discovery and dry-run are forwarded."""+ paths = {route.path for route in live_actions.router.routes}+ assert "/live-actions/dry-run" in paths+ assert "/live-actions/dispatch" not in paths++ def test_every_route_requires_a_permission(self):+ """Upstream these sit behind a service token; the whole point of the+ proxy is that a person, not a service, is on the other end."""+ for route in live_actions.router.routes:+ dependencies = getattr(route, "dependant", None)+ assert dependencies is not None, route.path+ # Each handler takes an AuthUser produced by require_permission.+ assert route.dependant.dependencies, f"{route.path} has no auth dependency"diff --git a/services/ingest/internal/graph/writer.go b/services/ingest/internal/graph/writer.goindex 3bfd5d73d..c5877f3a1 100644--- a/services/ingest/internal/graph/writer.go+++ b/services/ingest/internal/graph/writer.go@@ -245,9 +245,17 @@ func New(ctx context.Context, cfg Config) (*Writer, error) {return nil, fmt.Errorf("graph: connect to Neo4j: %w", err)}- connectCtx, cancel := context.WithTimeout(ctx, 5*time.Second)- defer cancel()- if err := driver.VerifyConnectivity(connectCtx); err != nil {+ // Retry rather than deciding on the first attempt.+ //+ // This was a single 5-second check at process start, and a failure+ // disabled the graph writer for the lifetime of the process. Neo4j takes+ // tens of seconds to accept connections on a cold boot, and compose+ // cannot express "depend on neo4j only in the full profile" — so on a+ // stack where the graph is switched on, ingest would lose a race it had+ // no way to wait for and then run for days with the feature silently off.+ // The integration gate caught it intermittently, which is the worst way+ // to find out.+ if err := verifyWithRetry(ctx, driver, connectRetryWindow); err != nil {_ = driver.Close(ctx)return nil, fmt.Errorf("graph: verify connectivity: %w", err)}@@ -256,6 +264,43 @@ func New(ctx context.Context, cfg Config) (*Writer, error) {return w, nil}+// connectRetryWindow bounds how long startup waits for Neo4j.+//+// Long enough for a cold container, short enough that ingest still comes up+// and starts serving /v1/ingest promptly when the graph is genuinely absent —+// the graph is an enrichment, and refusing to ingest because it is missing+// would turn an optional dependency into a required one.+const connectRetryWindow = 60 * time.Second++// verifyWithRetry polls until the driver answers or the window closes.+func verifyWithRetry(ctx context.Context, driver neo4j.DriverWithContext, window time.Duration) error {+ deadline := time.Now().Add(window)+ backoff := 500 * time.Millisecond+ var lastErr error++ for {+ attemptCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ err := driver.VerifyConnectivity(attemptCtx)+ cancel()+ if err == nil {+ return nil+ }+ lastErr = err++ if time.Now().Add(backoff).After(deadline) {+ return lastErr+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(backoff):+ }+ if backoff < 5*time.Second {+ backoff *= 2+ }+ }+}+// newWriterFromDriver is the test-friendly constructor — takes a Driver// interface so writer_test.go can inject a fake without touching the// network. Production code uses ``New``.diff --git a/services/ingest/internal/graph/writer_test.go b/services/ingest/internal/graph/writer_test.goindex feb980351..991d6704b 100644--- a/services/ingest/internal/graph/writer_test.go+++ b/services/ingest/internal/graph/writer_test.go@@ -3,6 +3,7 @@ package graphimport ("context""errors"+ "strings""sync""sync/atomic""testing"@@ -269,7 +270,7 @@ type blockingFakeDriver struct{}func (b *blockingFakeDriver) NewSession(_ context.Context, _ neo4j.SessionConfig) Session {return &blockingSession{}}-func (b *blockingFakeDriver) Close(_ context.Context) error { return nil }+func (b *blockingFakeDriver) Close(_ context.Context) error { return nil }func (b *blockingFakeDriver) VerifyConnectivity(_ context.Context) error { return nil }type blockingSession struct{}@@ -370,3 +371,57 @@ func contains(s, sub string) bool {}return false}++// A single connectivity check at process start disabled the graph writer for+// the lifetime of the process. Neo4j takes tens of seconds to accept+// connections on a cold boot, and compose cannot express "depend on neo4j+// only in the full profile", so ingest lost a race it had no way to wait for+// and then ran with the feature silently off. The integration gate caught it+// intermittently, which is the worst way to find out.+type flakyDriver struct {+ neo4j.DriverWithContext+ failures int+ attempts int+}++func (d *flakyDriver) VerifyConnectivity(ctx context.Context) error {+ d.attempts+++ if d.attempts <= d.failures {+ return errors.New("connection refused")+ }+ return nil+}++func TestVerifyWithRetrySucceedsAfterABriefOutage(t *testing.T) {+ driver := &flakyDriver{failures: 2}+ if err := verifyWithRetry(context.Background(), driver, 30*time.Second); err != nil {+ t.Fatalf("verifyWithRetry returned %v, want nil once the broker answers", err)+ }+ if driver.attempts != 3 {+ t.Errorf("attempts = %d, want 3 (two refusals then success)", driver.attempts)+ }+}++func TestVerifyWithRetryGivesUpAndSaysWhy(t *testing.T) {+ // Bounded: the graph is an enrichment, and refusing to ingest because it+ // is missing would turn an optional dependency into a required one.+ driver := &flakyDriver{failures: 1000}+ err := verifyWithRetry(context.Background(), driver, 1200*time.Millisecond)+ if err == nil {+ t.Fatal("verifyWithRetry returned nil for a driver that never answers")+ }+ if !strings.Contains(err.Error(), "connection refused") {+ t.Errorf("error = %v, want the driver's own reason carried through", err)+ }+ if driver.attempts < 2 {+ t.Errorf("attempts = %d, want more than one — a single try is the bug", driver.attempts)+ }+}++func TestVerifyWithRetryHonoursCancellation(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if err := verifyWithRetry(ctx, &flakyDriver{failures: 1000}, time.Minute); err == nil {+ t.Fatal("verifyWithRetry ignored a cancelled context")+ }+}