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
feat(phase-B2): credential resolver + autonomy-governed live dispatch (#453)
Beenu Arora3bead98f2f5a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b2046681d..3b61c3779 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Phase B2 — connector credentials now reach the SOAR executors, and the autonomy policy governs every real execution.** Two wiring gaps closed. (1) Executors read vendor-prefixed parameter keys (`cs_client_id`, `okta_domain`, `splunk_url` …) but connectors store schema field names (`client_id`, `domain`, `base_url` …) — nothing translated, so even fully-configured credentials never reached an executor and every action fell back to simulation. New `services/actions/app/services/credential_resolver.py` pins the per-vendor translation (15 vendors, connector-id aliases like `aws_security_hub`→`aws_security_groups`, `azure_defender`→`defender`; unknown fields dropped, never blindly forwarded), and `LiveActionRequest.auth_config` lets callers pass connector-style creds that the dispatcher resolves at the boundary. (2) The Phase 9a `autonomy_safety.decide()` policy existed but was never called on the live path (the 9b gap) — now every dispatch whose capability maps to an `ActionType` is governed **before** the executor is invoked: above-tier ⇒ downgraded to a dry-run preview; with dry-run disabled ⇒ `PENDING_APPROVAL` (executor never invoked); tier L0 ⇒ `BLOCKED`; explicit dry-run honoured unchanged; governance verdict attached to the result for the audit trail. Deployment tier via `AISOC_MATURITY_TIER` (default L1 — copilot). Also registers ten previously-missing vendor adapters (SentinelOne isolate, Entra/GWS disable-user, PAN-OS/FortiGate/Cloudflare block-ip, Jira/ServiceNow/PagerDuty create-ticket, Slack notify) so the agent can plan against them (19→29 builtins). 29 new/updated tests; full actions suite 224 passed at 64% coverage. Claim-to-gate matrix +1 GATED (21 GATED / 10 PARTIAL / 1 NO GATE).- **Phase B1 — the agent now auto-triages every alert off the stream (copilot default).** The core autonomy gap: investigations were manual/API-only — nothing consumed `aisoc.alerts.fused`, so "an agent that triages every alert" wasn't true out of the box. New `services/agents/app/workers/fused_alert_consumer.py` (`FusedAlertTriageWorker`) subscribes to the fused-alert topic and auto-triages each alert. **Copilot / dry-run is the default**: triage is read-only — it classifies (verdict + calibrated confidence), records the reasoning to the Investigation Ledger (best-effort), and **never dispatches a response** (proposed actions carry `requires_approval=True`; `response_dispatched` is always `False`). Tier selection is cost- and determinism-aware: cost-governor `DEDUPLICATED` reuses the cached verdict (a flood of identical alerts costs one triage), `CIRCUIT_OPEN`/`AISOC_DETERMINISTIC`/no-LLM-key falls to deterministic heuristic triage (`run_triage` — the air-gapped/CI default), otherwise LLM auto-triage with a deterministic fallback on failure. Wired into the agents lifespan (off unless `KAFKA_BOOTSTRAP_SERVERS` is set) + compose (`depends_on: kafka`). 9 unit tests (`test_fused_alert_worker.py`, added to the CI agents gate; the job now also installs `langgraph`). Claim-to-gate matrix adds a GATED row "Agent auto-triages every alert" (20 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A4 — the behavioral (UEBA) model now feeds alert scoring in production (the three-model story is real).** `services/ueba` continuously scored every entity and emitted `ueba.anomalies`, but fusion never consumed them — so the Semantic-graph / Behavioral-UEBA / Knowledge-LLM story was only two models live. New `services/fusion/app/services/ueba_signal.py`: the fusion consumer subscribes to `ueba.anomalies` and caches the latest per-`(tenant, entity_type, entity_id)` anomaly in Redis with a TTL (behavioral signal is time-decaying); during `FusionEngine.process`, an alert looks up the highest anomaly across its own entities (username→user, hostname→device, src/dst IP→ip) and `apply_ueba_boost` raises the alert's confidence (risk-scaled, label recomputed) and anomaly score, recording an explainable `ueba_anomaly` factor. Fail-soft throughout (Redis miss/outage or malformed message ⇒ no boost, no raise). 10 fusion unit tests; full fusion suite 122 passed at 64% coverage. Claim-to-gate matrix adds a GATED row "Three-model AI: behavioral (UEBA) model feeds alert scoring" (19 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A3 — the default cold-boot stack is complete ("just works").** A plain `docker compose up` previously started the core services but left the connector runtime behind a `connectors` profile and graph-at-ingest OFF, so a fresh install wasn't the full spine. Now `docker-compose.yml` ships the connector runtime in the default profile (it idles harmlessly with no configured instances) and enables graph-at-ingest by default on `ingest-worker` (`AISOC_GRAPH_ENABLED=true` + Neo4j env + `depends_on`; the writer soft-fails if Neo4j is unreachable, so it never blocks ingest). `integration.yml` gains a Phase A3 gate asserting the default boot ships the connectors service **and** ingest enabled the graph writer **and** the Neo4j graph has nodes after the spine flowed — so combined with A1 (lake) and A2 (detection), a cold `up` is proven end-to-end: ingest → OCSF normalize → Kafka → ClickHouse lake + entity graph + detection engine → fused alert row. Claim-to-gate matrix: "`pnpm aisoc:demo` boots the real stack" PARTIAL → GATED (18 GATED / 10 PARTIAL / 1 NO GATE).diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 21aa0b993..73a8801cc 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -39,10 +39,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Detection rules fire on the live event stream (not just CI fixtures) | README L170 (detection engine) | `integration.yml :: spine` (Phase A2 — posts an event matching the native `aws-root-account-login` rule, asserts the fusion `DetectionEngine` produces the alert) + `validate-detections.yml` (exported-ruleset drift `--check`) + fusion `test_detection_engine.py` / `test_detection_matcher_parity.py` | GATED | - || Three-model AI: behavioral (UEBA) model feeds alert scoring in production | README (multi-model) | `ci.yml` fusion job (`test_ueba_signal.py` — the `ueba.anomalies` stream warms a per-entity cache that boosts fuse-time confidence + anomaly score; wired in `fusion_engine.process`) | GATED | - || Agent auto-triages every alert (not manual/API-only) | README (autonomous triage) | `ci.yml` agents job (`test_fused_alert_worker.py` — `FusedAlertTriageWorker` consumes `aisoc.alerts.fused`, auto-triages each alert copilot/read-only with cost-governor dedup + circuit-breaker, degrades to deterministic triage without an LLM key, never dispatches a response) | GATED | - |+| Connector credentials reach the SOAR executors (not simulation-only) + autonomy policy governs every real execution | README (SOAR / response) | `ci.yml` actions job (`test_credential_resolver.py` — per-vendor auth_config→executor-param translation pinned; `test_governed_dispatch.py` — Phase 9a `decide()` wired into live dispatch: above-tier ⇒ dry-run preview, dry-run-disabled ⇒ queued approval, L0 ⇒ blocked, executor never invoked when queued/blocked) | GATED | - |## Summary-- GATED: 20+- GATED: 21- PARTIAL: 10- NO GATE: 1 (progressively closed through Phases 2–11 and A1–A4: insecure-defaults, secret/IaC scanning, signed releases, cross-store isolation, DAC candidate-rule + imported-count honesty, connector live-test, OpenAPI breaking-change, ClickHouse lake population (A1), live-stream detection (A2), default cold-boot stack (A3), and the behavioral-model fusion (A4). The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c/E1, which needs a budgeted live-agent run)diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.pyindex 00386c85e..03c13398f 100644--- a/services/actions/app/live_actions/builtins.py+++ b/services/actions/app/live_actions/builtins.py@@ -58,6 +58,10 @@ from app.executors.network import (BlockDomainExecutor,BlockIPExecutor,)+from app.executors.notification import (+ CreateTicketExecutor,+ NotifySlackExecutor,+)from app.executors.siem import (BlockIOCExecutor,CreateNotableEventExecutor,@@ -424,6 +428,120 @@ class DefenderBlockIOC(_LegacyExecutorAdapter):_credential_keys = _DEFENDER_IOC_KEYS+# ---------------------------------------------------------------------------+# Phase B2 — previously-unregistered vendor adapters.+#+# The legacy executors already speak these vendors (they pick the client at+# call time from which credential block is present), but the live-action+# registry had no (vendor, capability) entry for them — so the agent layer+# could never plan against SentinelOne / Entra / GWS / PAN-OS / FortiGate /+# Cloudflare / Jira / ServiceNow / PagerDuty / Slack. Registering them here+# (with the exact credential keys their client builders read) completes the+# discovery surface; the credential_resolver maps connector auth_config onto+# these keys.+# ---------------------------------------------------------------------------+++class SentinelOneIsolateHost(_LegacyExecutorAdapter):+ vendor_id = "sentinelone"+ capability = "isolate_host"+ description = "Disconnect an endpoint from the network on SentinelOne."+ requires_credentials = True+ _legacy_executor = IsolateHostExecutor()+ _legacy_action_type = ActionType.ISOLATE_HOST+ _credential_keys = ("s1_console_url", "s1_api_token")+++class EntraDisableUser(_LegacyExecutorAdapter):+ vendor_id = "azure_entra"+ capability = "disable_user"+ description = "Disable a user account in Microsoft Entra ID."+ requires_credentials = True+ _legacy_executor = DisableUserExecutor()+ _legacy_action_type = ActionType.DISABLE_USER+ _credential_keys = ("azure_tenant_id", "azure_client_id", "azure_client_secret")+++class GoogleWorkspaceDisableUser(_LegacyExecutorAdapter):+ vendor_id = "google_workspace"+ capability = "disable_user"+ description = "Suspend a user account in Google Workspace."+ requires_credentials = True+ _legacy_executor = DisableUserExecutor()+ _legacy_action_type = ActionType.DISABLE_USER+ _credential_keys = ("gws_service_account_key", "gws_subject_email")+++class PanOsBlockIP(_LegacyExecutorAdapter):+ vendor_id = "panos"+ capability = "block_ip"+ description = "Block an IP on a Palo Alto NGFW via a dynamic address group tag."+ requires_credentials = True+ _legacy_executor = BlockIPExecutor()+ _legacy_action_type = ActionType.BLOCK_IP+ _credential_keys = ("panos_host", "panos_api_key", "panos_tag")+++class FortiGateBlockIP(_LegacyExecutorAdapter):+ vendor_id = "fortigate"+ capability = "block_ip"+ description = "Block an IP on a FortiGate firewall via an address group."+ requires_credentials = True+ _legacy_executor = BlockIPExecutor()+ _legacy_action_type = ActionType.BLOCK_IP+ _credential_keys = ("fgt_host", "fgt_api_token", "fgt_address_group")+++class CloudflareBlockIP(_LegacyExecutorAdapter):+ vendor_id = "cloudflare"+ capability = "block_ip"+ description = "Block an IP at the Cloudflare edge (zone firewall access rule)."+ requires_credentials = True+ _legacy_executor = BlockIPExecutor()+ _legacy_action_type = ActionType.BLOCK_IP+ _credential_keys = ("cf_api_token", "cf_zone_id")+++class JiraCreateTicket(_LegacyExecutorAdapter):+ vendor_id = "jira"+ capability = "create_ticket"+ description = "Create a Jira issue for the incident."+ requires_credentials = True+ _legacy_executor = CreateTicketExecutor()+ _legacy_action_type = ActionType.CREATE_TICKET+ _credential_keys = ("jira_base_url", "jira_email", "jira_api_token")+++class ServiceNowCreateTicket(_LegacyExecutorAdapter):+ vendor_id = "servicenow"+ capability = "create_ticket"+ description = "Create a ServiceNow incident record."+ requires_credentials = True+ _legacy_executor = CreateTicketExecutor()+ _legacy_action_type = ActionType.CREATE_TICKET+ _credential_keys = ("snow_instance_url", "snow_username", "snow_password")+++class PagerDutyCreateTicket(_LegacyExecutorAdapter):+ vendor_id = "pagerduty"+ capability = "create_ticket"+ description = "Trigger a PagerDuty incident (Events API v2)."+ requires_credentials = True+ _legacy_executor = CreateTicketExecutor()+ _legacy_action_type = ActionType.CREATE_TICKET+ _credential_keys = ("pd_routing_key",)+++class SlackNotify(_LegacyExecutorAdapter):+ vendor_id = "slack"+ capability = "notify"+ description = "Post an incident notification to a Slack channel."+ requires_credentials = True+ _legacy_executor = NotifySlackExecutor()+ _legacy_action_type = ActionType.NOTIFY_SLACK+ _credential_keys = ("webhook_url",)++# ---------------------------------------------------------------------------# Registration entry point# ---------------------------------------------------------------------------@@ -453,6 +571,17 @@ _BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (SplunkSyncDetectionRule,ElasticUpdateWatcher,DefenderBlockIOC,+ # Phase B2 — previously-unregistered vendors+ SentinelOneIsolateHost,+ EntraDisableUser,+ GoogleWorkspaceDisableUser,+ PanOsBlockIP,+ FortiGateBlockIP,+ CloudflareBlockIP,+ JiraCreateTicket,+ ServiceNowCreateTicket,+ PagerDutyCreateTicket,+ SlackNotify,)diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.pyindex 9dd4e7786..a29175056 100644--- a/services/actions/app/live_actions/dispatcher.py+++ b/services/actions/app/live_actions/dispatcher.py@@ -2,8 +2,8 @@Dispatch live-action requests to registered executors.The dispatcher is the single entry point used by the REST router and by-internal callers (agent loop, playbook engine). It enforces three-invariants that individual executors should not have to think about:+internal callers (agent loop, playbook engine). It enforces these invariants+so individual executors never have to think about them:1. **Unknown (vendor, capability) returns FAILED, not 500.** Callersget a structured :class:`LiveActionResult` so the agent loop can@@ -13,17 +13,97 @@ invariants that individual executors should not have to think about:3. **Structured logs include request_id, vendor, capability, dry_runand outcome.** This is what feeds the audit trail and the costdashboard.+ 4. **Phase B2 — the autonomy-safety policy governs every real execution.**+ Any request whose capability maps to an :class:`ActionType` runs through+ ``autonomy_safety.decide()`` before the executor is invoked (this closes+ the Phase 9b wiring gap). Copilot is the default: below-tier actions are+ downgraded to a dry-run preview, HIGH/CRITICAL blast queues for a human,+ and tier L0 blocks outright. The gate never *upgrades* a request — an+ explicit ``dry_run=True`` stays a dry-run whatever the tier says.+ 5. **Phase B2 — connector-style credentials are translated at the boundary.**+ A request carrying ``auth_config`` (connector schema field names) has it+ resolved into the executor's vendor-prefixed params via+ ``credential_resolver.resolve_params`` — so configured connector+ credentials actually reach the executor instead of falling back to+ simulation mode."""from __future__ import annotations+import os+from uuid import uuid4+import structlog+from app.models.action import ActionRequest, ActionType+from app.services.autonomy_safety import AutonomyDecision, AutonomyMode, decide+from app.services.credential_resolver import resolve_params+from app.services.maturity import MaturityTier+from . import registryfrom .models import LiveActionRequest, LiveActionResult, LiveActionStatuslogger = structlog.get_logger(__name__)+_TIER_ENV = "AISOC_MATURITY_TIER"+++def configured_tier() -> MaturityTier:+ """Deployment-wide autonomy tier. Conservative default: L1 (notify).++ Accepts ``L2`` / ``L2_CONTAIN`` / ``2``. Per-tenant tier scoping arrives+ with the autonomy-scoping UI (Phase C3); until then one conservative+ deployment default keeps copilot the out-of-the-box posture.+ """+ raw = os.environ.get(_TIER_ENV, "").strip().upper()+ if not raw:+ return MaturityTier.L1_NOTIFY+ for tier in MaturityTier:+ if raw in {tier.name, tier.name.split("_")[0], str(tier.value)}:+ return tier+ logger.warning("live_action.bad_tier_env", value=raw)+ return MaturityTier.L1_NOTIFY+++def _action_type_for(request: LiveActionRequest, executor: object) -> ActionType | None:+ """Map a live capability onto the legacy ActionType vocabulary."""+ legacy = getattr(executor, "_legacy_action_type", None)+ if isinstance(legacy, ActionType):+ return legacy+ try:+ return ActionType(request.capability)+ except ValueError:+ return None+++def _govern(request: LiveActionRequest, action_type: ActionType) -> AutonomyDecision:+ action_request = ActionRequest(+ incident_id=request.case_id or uuid4(),+ tenant_id=request.tenant_id or uuid4(),+ action_type=action_type,+ target=request.target,+ parameters=request.params,+ requested_by=request.requested_by,+ )+ return decide(action_request, tier=configured_tier())+++def _not_executed(request: LiveActionRequest, status: LiveActionStatus, decision: AutonomyDecision) -> LiveActionResult:+ return LiveActionResult(+ request_id=request.request_id,+ status=status,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary=f"{request.capability} on {request.target or 'target'}: {status.value} by autonomy policy — {decision.reason}",+ details={+ "autonomy_mode": decision.mode.value,+ "blast_radius": decision.blast_radius.value,+ "tier": decision.tier.name,+ "rollback": decision.rollback.value,+ "reason": decision.reason,+ },+ )+async def dispatch(request: LiveActionRequest) -> LiveActionResult:"""Run ``request`` through the registered executor and return a result.@@ -40,6 +120,11 @@ async def dispatch(request: LiveActionRequest) -> LiveActionResult:dry_run=request.dry_run,)+ # Phase B2 — translate connector-style credentials into executor params.+ if request.auth_config:+ resolved = resolve_params(request.vendor_id, request.auth_config, extra=request.params)+ request = request.model_copy(update={"params": resolved, "auth_config": None})+executor = registry.get_executor(request.vendor_id, request.capability)if executor is None:log.warning("live_action.unknown")@@ -54,6 +139,24 @@ async def dispatch(request: LiveActionRequest) -> LiveActionResult:details={"available_vendors_for_capability": available},)+ # Phase B2 — autonomy-safety gate (Phase 9a decide(), wired = Phase 9b).+ # An explicit dry_run request is already the safest mode — no downgrade+ # possible — so governance applies to would-be real executions only.+ decision: AutonomyDecision | None = None+ action_type = _action_type_for(request, executor)+ if action_type is not None and not request.dry_run:+ decision = _govern(request, action_type)+ log = log.bind(autonomy_mode=decision.mode.value, blast=decision.blast_radius.value)+ if decision.mode is AutonomyMode.BLOCKED:+ log.warning("live_action.blocked_by_policy", reason=decision.reason)+ return _not_executed(request, LiveActionStatus.BLOCKED, decision)+ if decision.mode is AutonomyMode.QUEUED_APPROVAL:+ log.info("live_action.queued_for_approval", reason=decision.reason)+ return _not_executed(request, LiveActionStatus.PENDING_APPROVAL, decision)+ if decision.mode is AutonomyMode.DRY_RUN:+ log.info("live_action.downgraded_to_dry_run", reason=decision.reason)+ request = request.model_copy(update={"dry_run": True})+log = log.bind(executor=type(executor).__name__)log.info("live_action.dispatch")@@ -82,6 +185,14 @@ async def dispatch(request: LiveActionRequest) -> LiveActionResult:if result.capability != request.capability:result = result.model_copy(update={"capability": request.capability})+ # Surface the governance verdict on the result for the audit trail.+ if decision is not None:+ details = dict(result.details)+ details.setdefault("autonomy_mode", decision.mode.value)+ details.setdefault("blast_radius", decision.blast_radius.value)+ details.setdefault("autonomy_reason", decision.reason)+ result = result.model_copy(update={"details": details})+log.info("live_action.completed",status=result.status.value,diff --git a/services/actions/app/live_actions/models.py b/services/actions/app/live_actions/models.pyindex 78b5d178b..f6e4bdc2e 100644--- a/services/actions/app/live_actions/models.py+++ b/services/actions/app/live_actions/models.py@@ -64,6 +64,11 @@ class LiveActionStatus(str, Enum):SUCCEEDED = "succeeded"FAILED = "failed"SIMULATED = "simulated" # No credentials → safe simulation path.+ # Phase B2 — the autonomy-safety gate (Phase 9a `decide()`) is wired into+ # dispatch. These two states mean the executor was intentionally NOT+ # invoked: the tier/blast policy blocked it outright, or it needs a human.+ BLOCKED = "blocked"+ PENDING_APPROVAL = "pending_approval"class LiveActionRequest(BaseModel):@@ -91,6 +96,13 @@ class LiveActionRequest(BaseModel):vendor_id: strtarget: str = ""params: dict[str, Any] = Field(default_factory=dict)+ # Phase B2 — connector-style credentials (schema field names, e.g.+ # ``client_id`` / ``api_token``). When present, the dispatcher translates+ # them into the executor's vendor-prefixed params via+ # ``app.services.credential_resolver.resolve_params`` — so callers holding+ # a decrypted connector ``auth_config`` don't need to know each executor's+ # parameter vocabulary. Explicit ``params`` keys win on collision.+ auth_config: dict[str, Any] | None = Nonedry_run: bool = False# Provenance — these are filled in by the API layer / agent runner sodiff --git a/services/actions/app/services/credential_resolver.py b/services/actions/app/services/credential_resolver.pynew file mode 100644index 000000000..0f1a8a239--- /dev/null+++ b/services/actions/app/services/credential_resolver.py@@ -0,0 +1,176 @@+"""Map connector credentials onto SOAR executor parameters (Phase B2).++The reality audit's SOAR wiring gap: the response executors read+vendor-prefixed keys from ``ActionRequest.parameters`` (CrowdStrike wants+``cs_client_id``; Okta wants ``okta_domain``; Splunk wants ``splunk_url`` …),+but a tenant configures a connector with *schema* field names (``client_id``,+``domain``, ``base_url`` …). Nothing translated one to the other, so even a+fully-configured connector's credentials never reached the executor and every+action fell back to ``Simulation mode``.++This module is that translation layer. Given a live ``vendor_id``, a connector's+decrypted ``auth_config``, and any per-action operational params (target host,+AWS security-group id, PAN-OS tag …), :func:`resolve_params` produces the+prefixed parameter dict the executor expects.++The map is intentionally explicit (not a heuristic): a wrong credential mapping+is a silent security/reliability bug, so every vendor's field translation is+written out and unit-tested. Connector-id → live-vendor-id aliases handle the+cases where they differ (``aws_security_hub`` connector → ``aws_security_groups``+live vendor; ``azure_defender`` → ``defender``).+"""++from __future__ import annotations++from typing import Any++# Connector ``connector_id`` -> live-actions ``vendor_id`` when they differ.+CONNECTOR_TO_VENDOR: dict[str, str] = {+ "aws_security_hub": "aws_security_groups",+ "aws_guardduty": "aws_security_groups",+ "azure_defender": "defender",+}++# live vendor_id -> {connector auth_config field : executor param key}.+# Only credential/config fields; per-action operational params are merged+# separately in resolve_params (e.g. target host, aws_security_group_id).+VENDOR_CREDENTIAL_MAP: dict[str, dict[str, str]] = {+ "crowdstrike": {+ "client_id": "cs_client_id",+ "client_secret": "cs_client_secret",+ "base_url": "cs_base_url",+ },+ "defender": {+ "tenant_id": "mde_tenant_id",+ "client_id": "mde_client_id",+ "client_secret": "mde_client_secret",+ },+ "sentinelone": {+ "api_token": "s1_api_token",+ "base_url": "s1_console_url",+ },+ "okta": {+ "domain": "okta_domain",+ "api_token": "okta_api_token",+ },+ "azure_entra": {+ "tenant_id": "azure_tenant_id",+ "client_id": "azure_client_id",+ "client_secret": "azure_client_secret",+ },+ "google_workspace": {+ "service_account_json": "gws_service_account_key",+ "admin_email": "gws_subject_email",+ },+ "aws_security_groups": {+ "access_key": "aws_access_key_id",+ "secret_key": "aws_secret_access_key",+ "region": "aws_region",+ "role_arn": "aws_role_arn",+ },+ "panos": {+ "host": "panos_host",+ "api_key": "panos_api_key",+ "tag": "panos_tag",+ },+ "fortigate": {+ "host": "fgt_host",+ "api_token": "fgt_api_token",+ "address_group": "fgt_address_group",+ },+ "cloudflare": {+ "api_token": "cf_api_token",+ "zone_id": "cf_zone_id",+ "account_id": "cf_account_id",+ },+ "splunk": {+ "base_url": "splunk_url",+ "token": "splunk_token",+ "username": "splunk_username",+ "password": "splunk_password",+ "ssl_verify": "splunk_verify_ssl",+ },+ "elastic": {+ "base_url": "elastic_url",+ "api_key": "elastic_api_key",+ "username": "elastic_username",+ "password": "elastic_password",+ "kibana_url": "kibana_url",+ },+ "jira": {+ "base_url": "jira_base_url",+ "email": "jira_email",+ "api_token": "jira_api_token",+ "project_key": "jira_project_key",+ },+ "servicenow": {+ "instance_url": "snow_instance_url",+ "username": "snow_username",+ "password": "snow_password",+ },+ "pagerduty": {+ # The connector stores a REST api_key; the executor needs the Events+ # API v2 routing key. They are different secrets — a tenant that wants+ # live PagerDuty ticketing must supply `routing_key` in auth_config.+ "routing_key": "pd_routing_key",+ },+}+++def canonical_vendor(vendor_or_connector_id: str) -> str:+ """Resolve a connector_id or vendor_id to the live-actions vendor_id."""+ v = (vendor_or_connector_id or "").strip().lower()+ return CONNECTOR_TO_VENDOR.get(v, v)+++def resolve_params(+ vendor_id: str,+ auth_config: dict[str, Any] | None,+ *,+ extra: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Translate connector ``auth_config`` into executor parameters.++ Parameters+ ----------+ vendor_id:+ A live ``vendor_id`` or a connector ``connector_id`` (aliased via+ :data:`CONNECTOR_TO_VENDOR`).+ auth_config:+ The connector's decrypted credential dict (schema field names).+ extra:+ Per-action operational params already in executor-key form (e.g.+ ``aws_security_group_id``, ``panos_tag``, ``jira_project_key``,+ ``target``). Merged on top of the translated credentials; a key here+ overrides a translated one.++ Returns+ -------+ dict+ Executor-ready parameters. Fields not in the vendor map are dropped+ (an unknown credential field is never blindly forwarded), except that+ already-prefixed passthrough keys in ``auth_config`` (those matching an+ executor target key) are preserved so a caller can supply raw params.+ """+ vendor = canonical_vendor(vendor_id)+ mapping = VENDOR_CREDENTIAL_MAP.get(vendor, {})+ out: dict[str, Any] = {}+ target_keys = set(mapping.values())++ for field, value in (auth_config or {}).items():+ if value is None:+ continue+ if field in mapping:+ out[mapping[field]] = value+ elif field in target_keys:+ # Caller already supplied a prefixed key — pass it through.+ out[field] = value++ for key, value in (extra or {}).items():+ if value is not None:+ out[key] = value+ return out+++def known_vendors() -> list[str]:+ return sorted(VENDOR_CREDENTIAL_MAP)diff --git a/services/actions/tests/test_credential_resolver.py b/services/actions/tests/test_credential_resolver.pynew file mode 100644index 000000000..4f7ebcc9c--- /dev/null+++ b/services/actions/tests/test_credential_resolver.py@@ -0,0 +1,97 @@+"""Phase B2 — credential resolver tests.++The executors read vendor-prefixed parameter keys; connectors store schema+field names. These tests pin the translation for every mapped vendor so a+drifted key (which would silently drop the platform back into simulation+mode) fails CI.+"""++from __future__ import annotations++from app.services.credential_resolver import (+ CONNECTOR_TO_VENDOR,+ VENDOR_CREDENTIAL_MAP,+ canonical_vendor,+ resolve_params,+)+++def test_crowdstrike_fields_map_to_cs_prefixed_keys():+ out = resolve_params(+ "crowdstrike",+ {"client_id": "abc", "client_secret": "xyz", "base_url": "https://api.crowdstrike.com"},+ )+ assert out == {+ "cs_client_id": "abc",+ "cs_client_secret": "xyz",+ "cs_base_url": "https://api.crowdstrike.com",+ }+++def test_okta_fields_map():+ out = resolve_params("okta", {"domain": "https://org.okta.com", "api_token": "tok"})+ assert out == {"okta_domain": "https://org.okta.com", "okta_api_token": "tok"}+++def test_splunk_fields_map_including_url_and_ssl():+ out = resolve_params("splunk", {"base_url": "https://splunk:8089", "token": "hec", "ssl_verify": True})+ assert out == {"splunk_url": "https://splunk:8089", "splunk_token": "hec", "splunk_verify_ssl": True}+++def test_aws_connector_id_aliases_to_security_groups_vendor():+ assert canonical_vendor("aws_security_hub") == "aws_security_groups"+ assert canonical_vendor("aws_guardduty") == "aws_security_groups"+ out = resolve_params(+ "aws_security_hub",+ {"access_key": "AKIA...", "secret_key": "s3cr3t", "region": "eu-west-1"},+ extra={"aws_security_group_id": "sg-123"},+ )+ assert out["aws_access_key_id"] == "AKIA..."+ assert out["aws_secret_access_key"] == "s3cr3t"+ assert out["aws_region"] == "eu-west-1"+ # Operational (non-credential) param merged from extra:+ assert out["aws_security_group_id"] == "sg-123"+++def test_azure_defender_aliases_to_defender_mde_keys():+ out = resolve_params("azure_defender", {"tenant_id": "t", "client_id": "c", "client_secret": "s"})+ assert out == {"mde_tenant_id": "t", "mde_client_id": "c", "mde_client_secret": "s"}+++def test_google_workspace_map():+ out = resolve_params("google_workspace", {"service_account_json": "{...}", "admin_email": "[email protected]"})+ assert out == {"gws_service_account_key": "{...}", "gws_subject_email": "[email protected]"}+++def test_unknown_field_is_dropped_not_forwarded():+ out = resolve_params("okta", {"domain": "d", "api_token": "t", "mystery_field": "boom"})+ assert "mystery_field" not in out+++def test_already_prefixed_keys_pass_through():+ out = resolve_params("okta", {"okta_domain": "d", "okta_api_token": "t"})+ assert out == {"okta_domain": "d", "okta_api_token": "t"}+++def test_extra_overrides_translated_value():+ out = resolve_params("okta", {"domain": "old"}, extra={"okta_domain": "new"})+ assert out["okta_domain"] == "new"+++def test_none_values_skipped():+ out = resolve_params("jira", {"base_url": "https://j", "email": None, "api_token": "t"})+ assert out == {"jira_base_url": "https://j", "jira_api_token": "t"}+++def test_every_mapped_vendor_produces_only_executor_keys():+ # Sanity sweep: translated keys must all be prefixed/executor-vocabulary,+ # never raw connector field names (which executors ignore -> simulation).+ for vendor, mapping in VENDOR_CREDENTIAL_MAP.items():+ fake_auth = {field: "v" for field in mapping}+ out = resolve_params(vendor, fake_auth)+ assert set(out) == set(mapping.values()), vendor+++def test_connector_alias_table_targets_exist():+ for alias_target in CONNECTOR_TO_VENDOR.values():+ assert alias_target in VENDOR_CREDENTIAL_MAPdiff --git a/services/actions/tests/test_governed_dispatch.py b/services/actions/tests/test_governed_dispatch.pynew file mode 100644index 000000000..27e31c980--- /dev/null+++ b/services/actions/tests/test_governed_dispatch.py@@ -0,0 +1,213 @@+"""Phase B2 — autonomy-governed dispatch tests.++Proves the Phase 9a `decide()` policy actually governs the live-action path+(the Phase 9b wiring gap): at the default tier a HIGH-blast action queues for+approval instead of executing, below-tier actions are downgraded to dry-run,+L0 blocks outright, explicit dry-run requests are honored unchanged, and+connector-style `auth_config` is translated to executor params at dispatch.+"""++from __future__ import annotations++import asyncio++import pytest+from app.live_actions import registry+from app.live_actions.dispatcher import configured_tier, dispatch+from app.live_actions.executor import LiveActionExecutor+from app.live_actions.models import LiveActionRequest, LiveActionResult, LiveActionStatus+from app.services.maturity import MaturityTier+++class _RecordingExecutor(LiveActionExecutor):+ """Echoes back what it received so tests can inspect params/dry_run."""++ vendor_id = "govtest"+ capability = "isolate_host"+ description = "test"+ requires_credentials = False++ def __init__(self) -> None:+ self.last_request: LiveActionRequest | None = None++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ self.last_request = request+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SIMULATED if request.dry_run else LiveActionStatus.SUCCEEDED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary="ok",+ details={"params_seen": dict(request.params)},+ )+++class _NotifyExecutor(_RecordingExecutor):+ vendor_id = "govtest"+ capability = "notify_slack"+++def recording_executor():+ registry.reset_for_tests()+ ex = _RecordingExecutor()+ registry.register_executor(ex, source="test")+ yield ex+ registry.reset_for_tests()+++def notify_executor():+ registry.reset_for_tests()+ ex = _NotifyExecutor()+ registry.register_executor(ex, source="test")+ yield ex+ registry.reset_for_tests()+++def _run(request: LiveActionRequest) -> LiveActionResult:+ return asyncio.run(dispatch(request))+++# ── tier resolution ───────────────────────────────────────────────────────────+++def test_default_tier_is_l1_notify(monkeypatch):+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)+ assert configured_tier() == MaturityTier.L1_NOTIFY+++def test_tier_env_accepts_name_short_and_number(monkeypatch):+ for raw, expected in [("L3_REMEDIATE", MaturityTier.L3_REMEDIATE), ("L2", MaturityTier.L2_CONTAIN), ("4", MaturityTier.L4_AUTOMATE)]:+ monkeypatch.setenv("AISOC_MATURITY_TIER", raw)+ assert configured_tier() == expected+++# ── governance outcomes ──────────────────────────────────────────────────────+++def test_high_blast_action_downgrades_to_dry_run_at_default_tier(monkeypatch, recording_executor):+ """Copilot default: a HIGH-blast action above the tier allowance becomes a+ dry-run PREVIEW — never a silent real execution."""+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)+ monkeypatch.delenv("AISOC_ACTIONS_DEFAULT_DRY_RUN", raising=False)+ result = _run(LiveActionRequest(capability="isolate_host", vendor_id="govtest", target="srv-1"))+ assert result.status == LiveActionStatus.SIMULATED+ assert recording_executor.last_request is not None+ assert recording_executor.last_request.dry_run is True # downgraded+ assert result.details["autonomy_mode"] == "dry_run"+++def test_high_blast_action_queues_when_dry_run_disabled(monkeypatch, recording_executor):+ """With dry-run disabled, an above-tier action queues for a human instead+ of executing — the executor is never invoked."""+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)+ monkeypatch.setenv("AISOC_ACTIONS_DEFAULT_DRY_RUN", "0")+ result = _run(LiveActionRequest(capability="isolate_host", vendor_id="govtest", target="srv-1"))+ assert result.status == LiveActionStatus.PENDING_APPROVAL+ assert recording_executor.last_request is None # executor NEVER invoked+ assert result.details["autonomy_mode"] == "queued_approval"+++def test_high_blast_queues_even_at_l4_without_whitelist(monkeypatch, recording_executor):+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L4_AUTOMATE")+ monkeypatch.delenv("AISOC_ALLOW_HIGH_BLAST_AUTO", raising=False)+ result = _run(LiveActionRequest(capability="isolate_host", vendor_id="govtest", target="srv-1"))+ assert result.status == LiveActionStatus.PENDING_APPROVAL+ assert recording_executor.last_request is None+++def test_l0_blocks_outright(monkeypatch, recording_executor):+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L0_OBSERVE")+ result = _run(LiveActionRequest(capability="isolate_host", vendor_id="govtest", target="srv-1"))+ assert result.status == LiveActionStatus.BLOCKED+ assert recording_executor.last_request is None+++def test_low_blast_action_executes_at_permitted_tier(monkeypatch, notify_executor):+ # notify_slack is LOW blast — permitted to auto-execute at L1.+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)+ result = _run(LiveActionRequest(capability="notify_slack", vendor_id="govtest", target="#soc"))+ assert result.status == LiveActionStatus.SUCCEEDED+ assert notify_executor.last_request is not None+ assert notify_executor.last_request.dry_run is False+++def test_explicit_dry_run_is_honoured_not_governed(monkeypatch, recording_executor):+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L0_OBSERVE") # would block a real run+ result = _run(LiveActionRequest(capability="isolate_host", vendor_id="govtest", target="srv-1", dry_run=True))+ # An explicit dry-run is already the safest mode; it executes as a preview.+ assert result.status == LiveActionStatus.SIMULATED+ assert recording_executor.last_request is not None+ assert recording_executor.last_request.dry_run is True+++def test_unmapped_capability_is_not_governed(monkeypatch):+ registry.reset_for_tests()+ ex = _RecordingExecutor()+ ex.capability = "echo_probe" # no ActionType mapping+ registry.register_executor(ex, source="test")+ try:+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L0_OBSERVE")+ result = _run(LiveActionRequest(capability="echo_probe", vendor_id="govtest", target="x"))+ assert result.status == LiveActionStatus.SUCCEEDED+ finally:+ registry.reset_for_tests()+++# ── credential translation at the boundary ──────────────────────────────────+++def test_auth_config_is_translated_to_executor_params(monkeypatch, notify_executor):+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)+ # Vendor 'govtest' has no map -> only already-prefixed keys pass through;+ # use okta-style via a registered okta capability instead.+ registry.reset_for_tests()+ ex = _NotifyExecutor()+ ex.vendor_id = "okta"+ ex.capability = "notify_slack"+ registry.register_executor(ex, source="test")+ try:+ result = _run(+ LiveActionRequest(+ capability="notify_slack",+ vendor_id="okta",+ target="[email protected]",+ auth_config={"domain": "https://org.okta.com", "api_token": "tok"},+ params={"note": "hi"},+ )+ )+ assert result.status == LiveActionStatus.SUCCEEDED+ seen = ex.last_request.params+ assert seen["okta_domain"] == "https://org.okta.com"+ assert seen["okta_api_token"] == "tok"+ assert seen["note"] == "hi"+ assert ex.last_request.auth_config is None # consumed at the boundary+ finally:+ registry.reset_for_tests()+++# ── new vendor adapters are registered ───────────────────────────────────────+++def test_phase_b2_vendors_are_registered():+ from app.live_actions.builtins import register_builtin_executors++ registry.reset_for_tests()+ try:+ register_builtin_executors(overwrite=True)+ for vendor, capability in [+ ("sentinelone", "isolate_host"),+ ("azure_entra", "disable_user"),+ ("google_workspace", "disable_user"),+ ("panos", "block_ip"),+ ("fortigate", "block_ip"),+ ("cloudflare", "block_ip"),+ ("jira", "create_ticket"),+ ("servicenow", "create_ticket"),+ ("pagerduty", "create_ticket"),+ ("slack", "notify"),+ ]:+ assert registry.get_executor(vendor, capability) is not None, f"{vendor}/{capability} not registered"+ finally:+ registry.reset_for_tests()diff --git a/services/actions/tests/test_live_action_builtins.py b/services/actions/tests/test_live_action_builtins.pyindex 67bd781b8..533467fbf 100644--- a/services/actions/tests/test_live_action_builtins.py+++ b/services/actions/tests/test_live_action_builtins.py@@ -51,7 +51,9 @@ def test_register_builtin_executors_returns_full_count() -> None:cheap reminder to update docs / discovery snapshots."""count = register_builtin_executors()- assert count == 19+ # 19 original + 10 Phase B2 vendors (SentinelOne/Entra/GWS/PAN-OS/FortiGate/+ # Cloudflare/Jira/ServiceNow/PagerDuty/Slack).+ assert count == 29def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:@@ -89,6 +91,17 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:("splunk", "sync_detection_rule"),("elastic", "update_watcher"),("defender", "block_ioc"),+ # Phase B2 — previously-unregistered vendors+ ("sentinelone", "isolate_host"),+ ("azure_entra", "disable_user"),+ ("google_workspace", "disable_user"),+ ("panos", "block_ip"),+ ("fortigate", "block_ip"),+ ("cloudflare", "block_ip"),+ ("jira", "create_ticket"),+ ("servicenow", "create_ticket"),+ ("pagerduty", "create_ticket"),+ ("slack", "notify"),}assert pairs == expected@@ -119,7 +132,7 @@ def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:register_builtin_executors()# Second call without overwrite would raise — confirm overwrite works.count = register_builtin_executors(overwrite=True)- assert count == 19+ assert count == 29def test_register_builtin_twice_without_overwrite_raises() -> None:diff --git a/services/actions/tests/test_live_action_dispatcher.py b/services/actions/tests/test_live_action_dispatcher.pyindex 8ebd6cd54..80c73ac7b 100644--- a/services/actions/tests/test_live_action_dispatcher.py+++ b/services/actions/tests/test_live_action_dispatcher.py@@ -132,8 +132,11 @@ def _isolate_registry():def test_dispatch_routes_to_registered_executor():+ """Pure mechanics: ``isolate_host`` is HIGH blast, so a real execution is+ governed since Phase B2 — dry_run keeps this test about routing, not+ policy (the governance behaviour has its own suite)."""register_executor(_OkExecutor())- request = LiveActionRequest(capability="isolate_host", vendor_id="stubvendor", target="srv-12")+ request = LiveActionRequest(capability="isolate_host", vendor_id="stubvendor", target="srv-12", dry_run=True)result = asyncio.run(dispatch(request))@@ -194,9 +197,16 @@ def test_dispatch_crashing_executor_is_caught():def test_dispatch_patches_mismatched_request_id():"""Defence in depth: if an executor returns the wrong request_id we- patch it so the audit trail remains correlatable."""+ patch it so the audit trail remains correlatable.++ ``dry_run=True`` keeps this a pure mechanics test: ``disable_user`` is a+ HIGH-blast ActionType, so a would-be real execution is now governed by the+ Phase B2 autonomy gate (queued for approval) and the executor would never+ run — which is exactly what the governance tests assert, but not what THIS+ test is about.+ """register_executor(_LyingExecutor())- request = LiveActionRequest(capability="disable_user", vendor_id="lyingvendor")+ request = LiveActionRequest(capability="disable_user", vendor_id="lyingvendor", dry_run=True)result = asyncio.run(dispatch(request))diff --git a/services/actions/tests/test_live_action_router.py b/services/actions/tests/test_live_action_router.pyindex 3282cd426..04c2e4e20 100644--- a/services/actions/tests/test_live_action_router.py+++ b/services/actions/tests/test_live_action_router.py@@ -161,6 +161,10 @@ def test_by_vendor_endpoint(client: TestClient) -> None:def test_dispatch_succeeds_and_reports_live_mode(client: TestClient) -> None:+ """Since Phase B2 a would-be real ``isolate_host`` (HIGH blast) is governed+ by the autonomy gate: at the default tier it is downgraded to a dry-run+ preview — the executor still runs (echo_target present) but nothing real+ executes, and the governance verdict is on the result."""response = client.post("/api/v1/live-actions/dispatch",json={@@ -172,7 +176,8 @@ def test_dispatch_succeeds_and_reports_live_mode(client: TestClient) -> None:assert response.status_code == 200body = response.json()assert body["mode"] == "live"- assert body["result"]["status"] == "succeeded"+ assert body["result"]["status"] == "simulated"+ assert body["result"]["details"]["autonomy_mode"] == "dry_run"assert body["result"]["vendor_id"] == "stubvendor"assert body["result"]["capability"] == "isolate_host"assert body["result"]["details"]["echo_target"] == "host-77"