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.

refactor(actions): break the rollback import cycle instead of papering over it (#674)

Beenu Aroraff860394ea81
diff --git a/services/actions/app/clients/factories.py b/services/actions/app/clients/factories.py
new file mode 100644
index 000000000..9c799dc22
--- /dev/null
+++ b/services/actions/app/clients/factories.py
@@ -0,0 +1,183 @@
+"""Credential → vendor-client factories, shared by executors and rollback.
+
+These lived in `executors/endpoint.py`, `identity.py` and `network.py`. That
+put them on the wrong side of a dependency edge: `app.services.rollback` needs
+them to perform a real reverse action, and the executors need
+`reverse_via_rollback_service` from `rollback` so a `rollback()` call actually
+contacts the vendor instead of logging an intent and returning True. The result
+was a cycle that had to be papered over with inline imports inside each
+`rollback()` method, which CodeQL correctly flagged as `py/cyclic-import`.
+
+There is nothing executor-specific about them — each one reads a resolved
+credential bag and returns a configured client, or `None` when the credentials
+are absent so the caller can take its simulation path. Moving them here points
+both sides at a leaf module and lets every import sit at module scope.
+
+The executor modules re-export these names, because `app.services.rollback` and
+`app.services.verification` import them from there and tests monkeypatch e.g.
+`verification._cs_client`. Keeping the old paths working means the refactor
+does not move anyone's patch target.
+"""
+
+from __future__ import annotations
+
+from app.clients.aws_security_groups import AWSSecurityGroupsClient
+from app.clients.azure_entra_client import AzureEntraClient
+from app.clients.cloudflare_client import CloudflareClient
+from app.clients.cortex_xdr_client import CortexXdrClient
+from app.clients.crowdstrike_rtr import CrowdStrikeRTRClient
+from app.clients.defender_client import DefenderClient
+from app.clients.fortigate_client import FortiGateClient
+from app.clients.google_workspace_client import GoogleWorkspaceClient
+from app.clients.okta_client import OktaClient
+from app.clients.panos_client import PanOsClient
+from app.clients.sentinelone_client import SentinelOneClient
+
+
+def _aws_client(params: dict) -> AWSSecurityGroupsClient | None:
+ access_key = params.get("aws_access_key_id")
+ secret_key = params.get("aws_secret_access_key")
+ sg_id = params.get("aws_security_group_id")
+ if not sg_id:
+ return None
+ return AWSSecurityGroupsClient(
+ access_key_id=access_key,
+ secret_access_key=secret_key,
+ region=params.get("aws_region", "us-east-1"),
+ role_arn=params.get("aws_role_arn"),
+ session_name=params.get("aws_session_name", "aisoc-action"),
+ )
+
+
+def _cloudflare_client(params: dict) -> CloudflareClient | None:
+ token = params.get("cf_api_token")
+ if not token:
+ return None
+ return CloudflareClient(api_token=token)
+
+
+def _cortex_client(params: dict) -> CortexXdrClient | None:
+ """Build a Cortex XDR client from request-scoped credentials.
+
+ Returns ``None`` when any field is missing so the executor falls through to
+ the next vendor / simulation.
+ """
+ api_key_id = params.get("cortex_api_key_id")
+ api_key = params.get("cortex_api_key")
+ fqdn = params.get("cortex_fqdn")
+ if not (api_key_id and api_key and fqdn):
+ return None
+ return CortexXdrClient(api_key_id=api_key_id, api_key=api_key, fqdn=fqdn)
+
+
+def _cs_client(params: dict) -> CrowdStrikeRTRClient | None:
+ client_id = params.get("cs_client_id")
+ client_secret = params.get("cs_client_secret")
+ if not (client_id and client_secret):
+ return None
+ return CrowdStrikeRTRClient(
+ client_id=client_id,
+ client_secret=client_secret,
+ base_url=params.get("cs_base_url", "https://api.crowdstrike.com"),
+ )
+
+
+def _entra_client(params: dict) -> AzureEntraClient | None:
+ tenant_id = params.get("azure_tenant_id")
+ client_id = params.get("azure_client_id")
+ client_secret = params.get("azure_client_secret")
+ if not (tenant_id and client_id and client_secret):
+ return None
+ return AzureEntraClient(
+ tenant_id=tenant_id,
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+
+def _fortigate_client(params: dict) -> FortiGateClient | None:
+ host = params.get("fgt_host")
+ token = params.get("fgt_api_token")
+ group = params.get("fgt_address_group")
+ if not (host and token and group):
+ return None
+ return FortiGateClient(
+ host=host,
+ api_token=token,
+ vdom=params.get("fgt_vdom", "root"),
+ verify_tls=bool(params.get("fgt_verify_tls", True)),
+ )
+
+
+def _gws_client(params: dict) -> GoogleWorkspaceClient | None:
+ key = params.get("gws_service_account_key")
+ subject = params.get("gws_subject_email")
+ if not (key and subject):
+ return None
+ return GoogleWorkspaceClient(service_account_key=key, subject_email=subject)
+
+
+def _mde_client(params: dict) -> DefenderClient | None:
+ tenant_id = params.get("mde_tenant_id")
+ client_id = params.get("mde_client_id")
+ client_secret = params.get("mde_client_secret")
+ if not (tenant_id and client_id and client_secret):
+ return None
+ return DefenderClient(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
+
+
+def _okta_client(params: dict) -> OktaClient | None:
+ domain = params.get("okta_domain")
+ api_token = params.get("okta_api_token")
+ if not (domain and api_token):
+ return None
+ return OktaClient(domain=domain, api_token=api_token)
+
+
+def _panos_client(params: dict) -> PanOsClient | None:
+ """Build a PAN-OS client. Returns None if the minimum
+ credentials are missing so the executor can fall through.
+ """
+ host = params.get("panos_host")
+ api_key = params.get("panos_api_key")
+ tag = params.get("panos_tag")
+ if not (host and api_key and tag):
+ return None
+ return PanOsClient(
+ host=host,
+ api_key=api_key,
+ vsys=params.get("panos_vsys", "vsys1"),
+ verify_tls=bool(params.get("panos_verify_tls", True)),
+ )
+
+
+def _s1_client(params: dict) -> SentinelOneClient | None:
+ """Build a SentinelOne client from ``ActionRequest.parameters``.
+
+ Returns ``None`` when either field is missing so the executor
+ can cleanly fall through to the next vendor / simulation. We
+ don't pull the API token out of an env var here — the dispatcher
+ intentionally treats every credential as request-scoped so that
+ multi-tenant deployments can route different tenants to
+ different S1 consoles in the same process.
+ """
+ console_url = params.get("s1_console_url")
+ api_token = params.get("s1_api_token")
+ if not (console_url and api_token):
+ return None
+ return SentinelOneClient(console_url=console_url, api_token=api_token)
+
+
+__all__ = [
+ "_aws_client",
+ "_cloudflare_client",
+ "_cortex_client",
+ "_cs_client",
+ "_entra_client",
+ "_fortigate_client",
+ "_gws_client",
+ "_mde_client",
+ "_okta_client",
+ "_panos_client",
+ "_s1_client",
+]
diff --git a/services/actions/app/executors/endpoint.py b/services/actions/app/executors/endpoint.py
index f3c0cb74e..dbaadb68a 100644
--- a/services/actions/app/executors/endpoint.py
+++ b/services/actions/app/executors/endpoint.py
@@ -34,68 +34,25 @@ from datetime import datetime
import structlog
-from app.clients.cortex_xdr_client import CortexXdrClient
from app.clients.crowdstrike_rtr import CrowdStrikeRTRClient
-from app.clients.defender_client import DefenderClient
-from app.clients.sentinelone_client import SentinelOneClient
+
+# Re-exported from app.clients.factories, which is where these now live so
+# app.services.rollback can import them without creating a cycle back into
+# this module. Imported here because rollback and verification import them
+# from this path, and tests monkeypatch them here.
+from app.clients.factories import ( # noqa: F401
+ _cortex_client,
+ _cs_client,
+ _mde_client,
+ _s1_client,
+)
from app.executors.base import _SIM_FUNNEL_CTA, BaseExecutor
from app.models.action import ActionRequest, ActionResult, ActionStatus, ActionType, BlastRadius
+from app.services.rollback import reverse_via_rollback_service
logger = structlog.get_logger()
-def _cs_client(params: dict) -> CrowdStrikeRTRClient | None:
- client_id = params.get("cs_client_id")
- client_secret = params.get("cs_client_secret")
- if not (client_id and client_secret):
- return None
- return CrowdStrikeRTRClient(
- client_id=client_id,
- client_secret=client_secret,
- base_url=params.get("cs_base_url", "https://api.crowdstrike.com"),
- )
-
-
-def _mde_client(params: dict) -> DefenderClient | None:
- tenant_id = params.get("mde_tenant_id")
- client_id = params.get("mde_client_id")
- client_secret = params.get("mde_client_secret")
- if not (tenant_id and client_id and client_secret):
- return None
- return DefenderClient(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
-
-
-def _s1_client(params: dict) -> SentinelOneClient | None:
- """Build a SentinelOne client from ``ActionRequest.parameters``.
-
- Returns ``None`` when either field is missing so the executor
- can cleanly fall through to the next vendor / simulation. We
- don't pull the API token out of an env var here — the dispatcher
- intentionally treats every credential as request-scoped so that
- multi-tenant deployments can route different tenants to
- different S1 consoles in the same process.
- """
- console_url = params.get("s1_console_url")
- api_token = params.get("s1_api_token")
- if not (console_url and api_token):
- return None
- return SentinelOneClient(console_url=console_url, api_token=api_token)
-
-
-def _cortex_client(params: dict) -> CortexXdrClient | None:
- """Build a Cortex XDR client from request-scoped credentials.
-
- Returns ``None`` when any field is missing so the executor falls through to
- the next vendor / simulation.
- """
- api_key_id = params.get("cortex_api_key_id")
- api_key = params.get("cortex_api_key")
- fqdn = params.get("cortex_fqdn")
- if not (api_key_id and api_key and fqdn):
- return None
- return CortexXdrClient(api_key_id=api_key_id, api_key=api_key, fqdn=fqdn)
-
-
async def _cs_contain_host_by_hostname(cs: CrowdStrikeRTRClient, hostname: str) -> dict:
"""Resolve hostname → device_id, then containment.
@@ -258,11 +215,6 @@ class IsolateHostExecutor(BaseExecutor):
Defender and SentinelOne; it reports `simulated` when credentials are
absent rather than claiming success.
"""
- # Imported inline, not at module scope: app.services.rollback imports
- # the vendor client factories from this module, so a top-level import
- # here would be circular.
- from app.services.rollback import reverse_via_rollback_service # noqa: PLC0415
-
hostname = result.rollback_data.get("hostname")
return await reverse_via_rollback_service(
ActionType.ISOLATE_HOST,
diff --git a/services/actions/app/executors/identity.py b/services/actions/app/executors/identity.py
index fd48afacd..d8c157767 100644
--- a/services/actions/app/executors/identity.py
+++ b/services/actions/app/executors/identity.py
@@ -38,44 +38,22 @@ from datetime import datetime
import structlog
-from app.clients.azure_entra_client import AzureEntraClient
-from app.clients.google_workspace_client import GoogleWorkspaceClient
-from app.clients.okta_client import OktaClient
+# Re-exported from app.clients.factories, which is where these now live so
+# app.services.rollback can import them without creating a cycle back into
+# this module. Imported here because rollback and verification import them
+# from this path, and tests monkeypatch them here.
+from app.clients.factories import ( # noqa: F401
+ _entra_client,
+ _gws_client,
+ _okta_client,
+)
from app.executors.base import _SIM_FUNNEL_CTA, BaseExecutor
from app.models.action import ActionRequest, ActionResult, ActionStatus, ActionType, BlastRadius
+from app.services.rollback import reverse_via_rollback_service
logger = structlog.get_logger()
-def _okta_client(params: dict) -> OktaClient | None:
- domain = params.get("okta_domain")
- api_token = params.get("okta_api_token")
- if not (domain and api_token):
- return None
- return OktaClient(domain=domain, api_token=api_token)
-
-
-def _entra_client(params: dict) -> AzureEntraClient | None:
- tenant_id = params.get("azure_tenant_id")
- client_id = params.get("azure_client_id")
- client_secret = params.get("azure_client_secret")
- if not (tenant_id and client_id and client_secret):
- return None
- return AzureEntraClient(
- tenant_id=tenant_id,
- client_id=client_id,
- client_secret=client_secret,
- )
-
-
-def _gws_client(params: dict) -> GoogleWorkspaceClient | None:
- key = params.get("gws_service_account_key")
- subject = params.get("gws_subject_email")
- if not (key and subject):
- return None
- return GoogleWorkspaceClient(service_account_key=key, subject_email=subject)
-
-
_SIM_NOTE_IDENTITY = (
"Simulation mode — provide okta_domain+okta_api_token, "
"azure_tenant_id+azure_client_id+azure_client_secret, or "
@@ -404,11 +382,6 @@ class SuspendSessionExecutor(BaseExecutor):
async def rollback(self, result: ActionResult) -> bool:
"""Un-suspend the session by actually calling the identity provider."""
- # Imported inline, not at module scope: app.services.rollback imports
- # the vendor client factories from this module, so a top-level import
- # here would be circular.
- from app.services.rollback import reverse_via_rollback_service # noqa: PLC0415
-
user_id = result.rollback_data.get("user_id")
return await reverse_via_rollback_service(
ActionType.SUSPEND_SESSION,
diff --git a/services/actions/app/executors/network.py b/services/actions/app/executors/network.py
index 146f0afee..c5f5c1bd3 100644
--- a/services/actions/app/executors/network.py
+++ b/services/actions/app/executors/network.py
@@ -44,68 +44,23 @@ from datetime import datetime
import structlog
from app.clients.aws_security_groups import AWSSecurityGroupsClient
-from app.clients.cloudflare_client import CloudflareClient
-from app.clients.fortigate_client import FortiGateClient
-from app.clients.panos_client import PanOsClient
+
+# Re-exported from app.clients.factories, which is where these now live so
+# app.services.rollback can import them without creating a cycle back into
+# this module. Imported here because rollback and verification import them
+# from this path, and tests monkeypatch them here.
+from app.clients.factories import ( # noqa: F401
+ _aws_client,
+ _cloudflare_client,
+ _fortigate_client,
+ _panos_client,
+)
from app.executors.base import _SIM_FUNNEL_CTA, BaseExecutor
from app.models.action import ActionRequest, ActionResult, ActionStatus, BlastRadius
logger = structlog.get_logger()
-def _aws_client(params: dict) -> AWSSecurityGroupsClient | None:
- access_key = params.get("aws_access_key_id")
- secret_key = params.get("aws_secret_access_key")
- sg_id = params.get("aws_security_group_id")
- if not sg_id:
- return None
- return AWSSecurityGroupsClient(
- access_key_id=access_key,
- secret_access_key=secret_key,
- region=params.get("aws_region", "us-east-1"),
- role_arn=params.get("aws_role_arn"),
- session_name=params.get("aws_session_name", "aisoc-action"),
- )
-
-
-def _panos_client(params: dict) -> PanOsClient | None:
- """Build a PAN-OS client. Returns None if the minimum
- credentials are missing so the executor can fall through.
- """
- host = params.get("panos_host")
- api_key = params.get("panos_api_key")
- tag = params.get("panos_tag")
- if not (host and api_key and tag):
- return None
- return PanOsClient(
- host=host,
- api_key=api_key,
- vsys=params.get("panos_vsys", "vsys1"),
- verify_tls=bool(params.get("panos_verify_tls", True)),
- )
-
-
-def _fortigate_client(params: dict) -> FortiGateClient | None:
- host = params.get("fgt_host")
- token = params.get("fgt_api_token")
- group = params.get("fgt_address_group")
- if not (host and token and group):
- return None
- return FortiGateClient(
- host=host,
- api_token=token,
- vdom=params.get("fgt_vdom", "root"),
- verify_tls=bool(params.get("fgt_verify_tls", True)),
- )
-
-
-def _cloudflare_client(params: dict) -> CloudflareClient | None:
- token = params.get("cf_api_token")
- if not token:
- return None
- return CloudflareClient(api_token=token)
-
-
class BlockIPExecutor(BaseExecutor):
"""Blocks an IP address at the network perimeter.
diff --git a/services/actions/app/services/rollback.py b/services/actions/app/services/rollback.py
index d1f1544dc..986c6fe32 100644
--- a/services/actions/app/services/rollback.py
+++ b/services/actions/app/services/rollback.py
@@ -35,9 +35,18 @@ from typing import Any
import structlog
-from app.executors.endpoint import _cs_client, _mde_client, _s1_client
-from app.executors.identity import _entra_client, _gws_client, _okta_client
-from app.executors.network import _aws_client, _cloudflare_client, _fortigate_client, _panos_client
+from app.clients.factories import (
+ _aws_client,
+ _cloudflare_client,
+ _cs_client,
+ _entra_client,
+ _fortigate_client,
+ _gws_client,
+ _mde_client,
+ _okta_client,
+ _panos_client,
+ _s1_client,
+)
from app.models.action import ActionType
logger = structlog.get_logger()
diff --git a/services/agents/tests/test_escalation_context_depth.py b/services/agents/tests/test_escalation_context_depth.py
index b533c3d55..631af3a9e 100644
--- a/services/agents/tests/test_escalation_context_depth.py
+++ b/services/agents/tests/test_escalation_context_depth.py
@@ -25,8 +25,10 @@ from __future__ import annotations
import uuid
import pytest
+from app.agents import tool_loop
from app.agents.investigation_agent import _bundle_findings
from app.models.state import AgentStatus, InvestigationState
+from app.workers import fused_alert_consumer as consumer
from app.workers.fused_alert_consumer import FusedAlertTriageWorker
@@ -48,8 +50,6 @@ def _state() -> InvestigationState:
@pytest.mark.asyncio
async def test_escalation_prefetches_the_context_bundle(monkeypatch: pytest.MonkeyPatch):
"""The regression: the automatic path got no pre-fetched context at all."""
- import app.workers.fused_alert_consumer as mod
-
seen: dict[str, object] = {}
async def _prefetch(*, case_id, tenant_id, alert_summary, raw_alert): # noqa: ANN001
@@ -60,8 +60,8 @@ async def test_escalation_prefetches_the_context_bundle(monkeypatch: pytest.Monk
seen["bundle_at_run"] = state.context_bundle
return state
- monkeypatch.setattr(mod, "prefetch_context_bundle_dict", _prefetch)
- monkeypatch.setattr(mod, "run_escalation", _run_escalation)
+ monkeypatch.setattr(consumer, "prefetch_context_bundle_dict", _prefetch)
+ monkeypatch.setattr(consumer, "run_escalation", _run_escalation)
monkeypatch.setenv("AISOC_AGENT_ESCALATION", "1")
state = _state()
@@ -78,8 +78,6 @@ async def test_a_context_failure_never_blocks_the_escalation(
monkeypatch: pytest.MonkeyPatch,
):
"""Context is additive. Losing it must not lose the investigation."""
- import app.workers.fused_alert_consumer as mod
-
ran = False
async def _prefetch(**kwargs): # noqa: ANN003
@@ -90,8 +88,8 @@ async def test_a_context_failure_never_blocks_the_escalation(
ran = True
return state
- monkeypatch.setattr(mod, "prefetch_context_bundle_dict", _prefetch)
- monkeypatch.setattr(mod, "run_escalation", _run_escalation)
+ monkeypatch.setattr(consumer, "prefetch_context_bundle_dict", _prefetch)
+ monkeypatch.setattr(consumer, "run_escalation", _run_escalation)
monkeypatch.setenv("AISOC_AGENT_ESCALATION", "1")
await FusedAlertTriageWorker(bootstrap_servers="localhost:9092")._maybe_escalate(_state())
@@ -175,7 +173,6 @@ async def test_the_tool_loop_routes_through_the_llm_contract(
the highest-risk content in the system, and lost token/cost telemetry for
every tool-calling turn.
"""
- import app.agents.tool_loop as loop
from app.tools.registry import ToolRegistry
called = False
@@ -190,12 +187,12 @@ async def test_the_tool_loop_routes_through_the_llm_contract(
return _Resp()
- monkeypatch.setattr(loop, "safe_ainvoke", _safe)
+ monkeypatch.setattr(tool_loop, "safe_ainvoke", _safe)
class _LLM:
def bind_tools(self, schemas): # noqa: ANN001
return self
- out = await loop.run_with_tools(_LLM(), system="s", user="u", registry=ToolRegistry())
+ out = await tool_loop.run_with_tools(_LLM(), system="s", user="u", registry=ToolRegistry())
assert called, "the loop bypassed safe_ainvoke"
assert out["content"] == "done"
diff --git a/services/agents/tests/test_groundedness_gate.py b/services/agents/tests/test_groundedness_gate.py
index 4407e1bda..d400601e0 100644
--- a/services/agents/tests/test_groundedness_gate.py
+++ b/services/agents/tests/test_groundedness_gate.py
@@ -21,6 +21,7 @@ import uuid
import pytest
from app.models.state import AgentStatus, InvestigationState
+from app.workers import fused_alert_consumer as consumer
from app.workers.fused_alert_consumer import FusedAlertTriageWorker
FALSE_POSITIVE = "false_positive"
@@ -147,12 +148,11 @@ def test_the_floor_is_configurable(monkeypatch: pytest.MonkeyPatch):
def test_a_scoring_failure_never_changes_the_verdict(monkeypatch: pytest.MonkeyPatch):
"""The verdict is the product. A broken scorer must not rewrite it."""
- import app.workers.fused_alert_consumer as mod
def _boom(*a, **k): # noqa: ANN002, ANN003
raise RuntimeError("scorer exploded")
- monkeypatch.setattr(mod, "score_groundedness", _boom)
+ monkeypatch.setattr(consumer, "score_groundedness", _boom)
state = _state(["Traffic to 203.0.113.77 is benign."])
verdict, confidence = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.95)
assert verdict == FALSE_POSITIVE