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.

fix(lint): ruff format — reformat 76 Python files for CI compliance

Beenu Arora97d11b54dc83
diff --git a/services/actions/app/api/router.py b/services/actions/app/api/router.py
index a51848dd1..0a50e7a34 100644
--- a/services/actions/app/api/router.py
+++ b/services/actions/app/api/router.py
@@ -160,8 +160,8 @@ def _chatops_response_html(headline: str, body: str, *, ok: bool = True) -> str:
"""
color = "#0a7" if ok else "#a33"
return (
- "<!doctype html><html lang=\"en\"><head>"
- "<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
+ '<!doctype html><html lang="en"><head>'
+ '<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
"<title>AiSOC verification</title>"
"<style>"
"body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;"
@@ -173,7 +173,7 @@ def _chatops_response_html(headline: str, body: str, *, ok: bool = True) -> str:
"h1{margin:0 0 12px 0;font-size:18px;display:flex;align-items:center}"
"p{margin:0;color:#9ca3af;line-height:1.5}"
"</style></head><body>"
- f"<div class=\"card\"><h1><span class=\"dot\"></span>{headline}</h1><p>{body}</p></div>"
+ f'<div class="card"><h1><span class="dot"></span>{headline}</h1><p>{body}</p></div>'
"</body></html>"
)
@@ -201,10 +201,7 @@ async def chatops_callback(token: str = Query(..., min_length=8)):
reason = str(exc)
logger.info("ChatOps callback rejected", reason=reason)
message = {
- "expired": (
- "This verification link has expired. If you still need to respond, "
- "contact your security team."
- ),
+ "expired": ("This verification link has expired. If you still need to respond, contact your security team."),
"invalid_signature": "This verification link is invalid.",
}.get(reason, "This verification link is invalid.")
return HTMLResponse(
@@ -232,10 +229,7 @@ async def chatops_callback(token: str = Query(..., min_length=8)):
await post_timeline_event(
case_id=claims.case_id,
event_type="chatops.verify.responded",
- content=(
- f"User {claims.user_ref or 'unknown'} responded "
- f"'{claims.choice}' to the ChatOps verification prompt."
- ),
+ content=(f"User {claims.user_ref or 'unknown'} responded '{claims.choice}' to the ChatOps verification prompt."),
metadata={
"action_id": action_id_str,
"tenant_id": str(claims.tenant_id),
diff --git a/services/actions/app/core/config.py b/services/actions/app/core/config.py
index 3ce66272b..9f41a88e3 100644
--- a/services/actions/app/core/config.py
+++ b/services/actions/app/core/config.py
@@ -62,10 +62,7 @@ class ActionsSettings(BaseSettings):
AISOC_CHATOPS_RESPONSE_SECRET: str = Field(
default="",
- description=(
- "HMAC secret used to sign ChatOps response tokens so we can verify a "
- "callback genuinely came from a message we sent."
- ),
+ description=("HMAC secret used to sign ChatOps response tokens so we can verify a callback genuinely came from a message we sent."),
)
AISOC_CHATOPS_TIMEOUT_SECONDS: int = Field(
@@ -76,8 +73,7 @@ class ActionsSettings(BaseSettings):
AISOC_ACTIONS_PUBLIC_URL: str = Field(
default="http://localhost:8003",
description=(
- "Externally-reachable base URL of services/actions. Used to build "
- "the callback links embedded in ChatOps verification messages."
+ "Externally-reachable base URL of services/actions. Used to build the callback links embedded in ChatOps verification messages."
),
)
diff --git a/services/actions/app/security/credential_vault.py b/services/actions/app/security/credential_vault.py
index 80b894aea..c26b2f2fa 100644
--- a/services/actions/app/security/credential_vault.py
+++ b/services/actions/app/security/credential_vault.py
@@ -69,13 +69,12 @@ class CredentialVault:
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
if not value.startswith(_CIPHER_PREFIX):
return value
- token = value[len(_CIPHER_PREFIX):].encode("ascii")
+ token = value[len(_CIPHER_PREFIX) :].encode("ascii")
try:
return self._fernet.decrypt(token).decode("utf-8")
except InvalidToken as exc:
raise CredentialVaultError(
- "ciphertext failed integrity check — likely AISOC_CREDENTIAL_KEY mismatch "
- "between API and actions services"
+ "ciphertext failed integrity check — likely AISOC_CREDENTIAL_KEY mismatch between API and actions services"
) from exc
def encrypt_dict(self, payload: Mapping[str, Any], *, secret_keys: set[str] | None = None) -> dict[str, Any]:
diff --git a/services/actions/app/services/maturity.py b/services/actions/app/services/maturity.py
index 8de165aa0..e2d9e22e0 100644
--- a/services/actions/app/services/maturity.py
+++ b/services/actions/app/services/maturity.py
@@ -132,8 +132,7 @@ def evaluate_gate(request: ActionRequest, config: TenantMaturityConfig) -> GateD
maturity_tier=int(tier),
decision="queued_approval",
rationale=(
- f"HIGH blast-radius action at L4 requires whitelist entry. "
- f"No matching whitelist entry found for '{action_key}'."
+ f"HIGH blast-radius action at L4 requires whitelist entry. No matching whitelist entry found for '{action_key}'."
),
)
overrides_applied.append(f"whitelist:{whitelist_match}")
@@ -159,16 +158,12 @@ def evaluate_gate(request: ActionRequest, config: TenantMaturityConfig) -> GateD
blast_radius=blast.value,
maturity_tier=int(tier),
decision="queued_approval",
- rationale=(
- f"Tier {tier.label}: '{blast.value}' blast-radius requires human approval."
- ),
+ rationale=(f"Tier {tier.label}: '{blast.value}' blast-radius requires human approval."),
overrides_applied=overrides_applied,
)
-def _check_whitelist(
- request: ActionRequest, whitelist: list[dict[str, Any]]
-) -> str | None:
+def _check_whitelist(request: ActionRequest, whitelist: list[dict[str, Any]]) -> str | None:
"""
Return the whitelist entry id/key if the action matches a whitelist entry,
or None if no match.
diff --git a/services/actions/app/services/timeline_client.py b/services/actions/app/services/timeline_client.py
index e8b421315..52588d46c 100644
--- a/services/actions/app/services/timeline_client.py
+++ b/services/actions/app/services/timeline_client.py
@@ -48,9 +48,7 @@ async def post_timeline_event(
settings = get_settings()
base = settings.AISOC_API_BASE_URL.rstrip("/")
if not settings.AISOC_API_SERVICE_TOKEN:
- raise TimelineClientError(
- "AISOC_API_SERVICE_TOKEN is not configured; cannot write ChatOps responses to the case timeline"
- )
+ raise TimelineClientError("AISOC_API_SERVICE_TOKEN is not configured; cannot write ChatOps responses to the case timeline")
url = f"{base}/api/v1/cases/{case_id}/timeline"
payload = {
@@ -74,8 +72,6 @@ async def post_timeline_event(
status_code=resp.status_code,
body=resp.text[:500],
)
- raise TimelineClientError(
- f"timeline write failed: HTTP {resp.status_code} — {resp.text[:200]}"
- )
+ raise TimelineClientError(f"timeline write failed: HTTP {resp.status_code} — {resp.text[:200]}")
return resp.json()
diff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.py
index 433e621ba..92ef7607f 100644
--- a/services/agents/app/api/copilot.py
+++ b/services/agents/app/api/copilot.py
@@ -40,9 +40,7 @@ class CopilotMessage(BaseModel):
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
role: str # "user" | "assistant"
content: str
- timestamp: str = Field(
- default_factory=lambda: datetime.now(UTC).isoformat()
- )
+ timestamp: str = Field(default_factory=lambda: datetime.now(UTC).isoformat())
class CopilotChatRequest(BaseModel):
diff --git a/services/agents/app/api/hunt_search.py b/services/agents/app/api/hunt_search.py
index 327c1dde0..6fcf856a0 100644
--- a/services/agents/app/api/hunt_search.py
+++ b/services/agents/app/api/hunt_search.py
@@ -158,9 +158,7 @@ async def hunt_search(query: HuntQuery) -> HuntResponse:
@router.get("/saved")
async def list_saved_searches() -> dict[str, list[dict[str, Any]]]:
"""Return all saved searches."""
- return {
- "searches": [s.model_dump() for s in _SAVED_SEARCHES.values()]
- }
+ return {"searches": [s.model_dump() for s in _SAVED_SEARCHES.values()]}
@router.post("/saved", response_model=SavedSearch, status_code=201)
diff --git a/services/agents/app/api/hunts.py b/services/agents/app/api/hunts.py
index cbd2da322..c75dd4c3b 100644
--- a/services/agents/app/api/hunts.py
+++ b/services/agents/app/api/hunts.py
@@ -97,9 +97,7 @@ async def run_hunt(hunt_id: str) -> dict[str, Any]:
sched = hunt_scheduler.get_scheduler()
out = await sched.run_one(hunt_id)
if not out.get("ok"):
- raise HTTPException(
- status_code=404, detail=out.get("error", "hunt run failed")
- )
+ raise HTTPException(status_code=404, detail=out.get("error", "hunt run failed"))
return out
@@ -121,6 +119,4 @@ async def list_findings(
status: str | None = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
) -> list[dict[str, Any]]:
- return await hunt_store.list_recent_findings(
- hunt_id=hunt_id, status=status, limit=limit
- )
+ return await hunt_store.list_recent_findings(hunt_id=hunt_id, status=status, limit=limit)
diff --git a/services/agents/app/hunt/engine.py b/services/agents/app/hunt/engine.py
index 83914cbe3..36d765023 100644
--- a/services/agents/app/hunt/engine.py
+++ b/services/agents/app/hunt/engine.py
@@ -213,11 +213,7 @@ class HuntEngine:
) -> HuntFindingDraft:
primary_entity = _pick_primary_entity(event)
log_source = _pick_log_source(event, hunt)
- title = (
- f"{hunt.name} matched {primary_entity}"
- if primary_entity
- else hunt.name
- )
+ title = f"{hunt.name} matched {primary_entity}" if primary_entity else hunt.name
summary = hunt.hypothesis.question.strip() or hunt.description.strip() or hunt.name
return HuntFindingDraft(
hunt_id=hunt.id,
diff --git a/services/agents/app/hunt/scheduler.py b/services/agents/app/hunt/scheduler.py
index 24f350771..9b2499858 100644
--- a/services/agents/app/hunt/scheduler.py
+++ b/services/agents/app/hunt/scheduler.py
@@ -126,15 +126,11 @@ class HuntScheduler:
try:
await self._run_hunt(hunt, events)
except Exception as exc: # noqa: BLE001
- logger.warning(
- "hunt.scheduler.run_failed", hunt_id=hunt.id, error=str(exc)
- )
+ logger.warning("hunt.scheduler.run_failed", hunt_id=hunt.id, error=str(exc))
finally:
self._last_run[hunt.id] = now
- async def _run_hunt(
- self, hunt: HuntDefinition, events: list[dict[str, Any]]
- ) -> None:
+ async def _run_hunt(self, hunt: HuntDefinition, events: list[dict[str, Any]]) -> None:
result = self._engine.run(hunt, events)
await record_run(
hunt,
diff --git a/services/agents/app/hunt/store.py b/services/agents/app/hunt/store.py
index 9fb8d40eb..3e0fe951b 100644
--- a/services/agents/app/hunt/store.py
+++ b/services/agents/app/hunt/store.py
@@ -26,9 +26,7 @@ _POOL: asyncpg.Pool | None = None
def _normalise_dsn(url: str) -> str:
- return url.replace("postgresql+asyncpg://", "postgresql://").replace(
- "postgres+asyncpg://", "postgresql://"
- )
+ return url.replace("postgresql+asyncpg://", "postgresql://").replace("postgres+asyncpg://", "postgresql://")
async def _get_pool() -> asyncpg.Pool | None:
@@ -101,9 +99,7 @@ async def sync_catalog(
async with pool.acquire() as conn:
tenant_id = await _resolve_tenant_id(conn, tenant_ref)
if tenant_id is None:
- logger.debug(
- "hunt.store.catalog.skip", reason="unknown_tenant", tenant_ref=tenant_ref
- )
+ logger.debug("hunt.store.catalog.skip", reason="unknown_tenant", tenant_ref=tenant_ref)
return 0
await _set_rls_context(conn, tenant_id)
@@ -187,9 +183,7 @@ async def record_run(
async with pool.acquire() as conn:
tenant_id = await _resolve_tenant_id(conn, tenant_ref)
if tenant_id is None:
- logger.debug(
- "hunt.store.run.skip", reason="unknown_tenant", tenant_ref=tenant_ref
- )
+ logger.debug("hunt.store.run.skip", reason="unknown_tenant", tenant_ref=tenant_ref)
return None
await _set_rls_context(conn, tenant_id)
@@ -276,9 +270,7 @@ async def _insert_finding(
# ---------------------------------------------------------------------------
-async def list_recent_runs(
- *, tenant_ref: str = "default", limit: int = 50
-) -> list[dict[str, Any]]:
+async def list_recent_runs(*, tenant_ref: str = "default", limit: int = 50) -> list[dict[str, Any]]:
pool = await _get_pool()
if pool is None:
return []
@@ -337,7 +329,7 @@ async def list_recent_findings(
primary_entity, primary_log_source, match_score,
mitre_techniques, status, created_at
FROM hunt_findings
- WHERE {' AND '.join(clauses)}
+ WHERE {" AND ".join(clauses)}
ORDER BY created_at DESC
LIMIT ${len(params)}
"""
diff --git a/services/agents/tests/test_adversary_eval.py b/services/agents/tests/test_adversary_eval.py
index abfe84262..7032b06df 100644
--- a/services/agents/tests/test_adversary_eval.py
+++ b/services/agents/tests/test_adversary_eval.py
@@ -98,8 +98,7 @@ class AdversaryEvalResult:
def _load_adversary_dataset() -> list[dict[str, Any]]:
if not _ADVERSARY_PATH.exists():
raise FileNotFoundError(
- f"Adversary dataset missing at {_ADVERSARY_PATH}. "
- "Generate with: python3 scripts/generate_adversary_incidents.py"
+ f"Adversary dataset missing at {_ADVERSARY_PATH}. Generate with: python3 scripts/generate_adversary_incidents.py"
)
return json.loads(_ADVERSARY_PATH.read_text())
@@ -160,8 +159,7 @@ class TestAdversaryEval(unittest.TestCase):
def test_dataset_present(self) -> None:
self.assertTrue(
_ADVERSARY_PATH.exists(),
- f"Adversary dataset missing at {_ADVERSARY_PATH}. "
- "Run scripts/generate_adversary_incidents.py to (re)generate it.",
+ f"Adversary dataset missing at {_ADVERSARY_PATH}. Run scripts/generate_adversary_incidents.py to (re)generate it.",
)
# The mutated set must mirror the base set 1:1 so per-template
# diffs are meaningful.
@@ -183,16 +181,12 @@ class TestAdversaryEval(unittest.TestCase):
"""
mutated = _load_adversary_dataset()
unchanged = sum(
- 1
- for inc in mutated
- if inc["title"] == inc.get("original_title")
- and inc["description"] == inc.get("original_description")
+ 1 for inc in mutated if inc["title"] == inc.get("original_title") and inc["description"] == inc.get("original_description")
)
self.assertLess(
unchanged,
(len(mutated) * 35) // 100,
- f"{unchanged}/{len(mutated)} incidents unchanged — "
- "mutation grammar may have regressed.",
+ f"{unchanged}/{len(mutated)} incidents unchanged — mutation grammar may have regressed.",
)
def test_overall_graceful_degradation(self) -> None:
@@ -208,8 +202,7 @@ class TestAdversaryEval(unittest.TestCase):
result.accuracy,
_OVERALL_FLOOR,
f"Adversary catch rate {result.accuracy:.1%} below "
- f"graceful-degradation floor of {_OVERALL_FLOOR:.0%}.\n"
- + json.dumps(result.to_summary(), indent=2)[:4000],
+ f"graceful-degradation floor of {_OVERALL_FLOOR:.0%}.\n" + json.dumps(result.to_summary(), indent=2)[:4000],
)
def test_light_bucket_still_caught(self) -> None:
@@ -248,8 +241,7 @@ class TestAdversaryEval(unittest.TestCase):
self.assertGreater(
result.bucket_counts["heavy"],
result.total // 4,
- f"Heavy bucket only {result.bucket_counts['heavy']}/{result.total} "
- "— mutation distribution may have drifted.",
+ f"Heavy bucket only {result.bucket_counts['heavy']}/{result.total} — mutation distribution may have drifted.",
)
self.assertGreater(
result.bucket_counts["light"],
diff --git a/services/agents/tests/test_hunt_corpus.py b/services/agents/tests/test_hunt_corpus.py
index b8473480f..2fa8a07b7 100644
--- a/services/agents/tests/test_hunt_corpus.py
+++ b/services/agents/tests/test_hunt_corpus.py
@@ -50,18 +50,14 @@ def _load_hunt_corpus() -> list[HuntDefinition]:
hunts = corpus.list()
if not hunts:
raise FileNotFoundError(
- f"No hunt YAMLs found under {corpus.directory}. "
- "Add at least one hunt to `hunts/` before the gate can grade them."
+ f"No hunt YAMLs found under {corpus.directory}. Add at least one hunt to `hunts/` before the gate can grade them."
)
return hunts
def _load_hunt_telemetry() -> list[dict[str, Any]]:
if not _HUNT_TELEMETRY_PATH.exists():
- raise FileNotFoundError(
- f"Missing {_HUNT_TELEMETRY_PATH}. "
- "Add positive and negative scenarios for each hunt before merging."
- )
+ raise FileNotFoundError(f"Missing {_HUNT_TELEMETRY_PATH}. Add positive and negative scenarios for each hunt before merging.")
events: list[dict[str, Any]] = []
with _HUNT_TELEMETRY_PATH.open() as f:
for line_no, raw in enumerate(f, 1):
@@ -71,9 +67,7 @@ def _load_hunt_telemetry() -> list[dict[str, Any]]:
try:
events.append(json.loads(line))
except json.JSONDecodeError as exc:
- raise AssertionError(
- f"{_HUNT_TELEMETRY_PATH.name}:{line_no} is not valid JSON: {exc}"
- ) from exc
+ raise AssertionError(f"{_HUNT_TELEMETRY_PATH.name}:{line_no} is not valid JSON: {exc}") from exc
return events
@@ -115,8 +109,7 @@ class TestHuntCorpusEval(unittest.TestCase):
with self.subTest(hunt=hunt.id):
self.assertTrue(
hunt.expected.positive_incident_id,
- f"hunt {hunt.id} is missing expected.positive_incident_id; "
- "every hunt YAML must declare a positive synthetic scenario.",
+ f"hunt {hunt.id} is missing expected.positive_incident_id; every hunt YAML must declare a positive synthetic scenario.",
)
def test_positive_scenarios_fire(self) -> None:
@@ -130,8 +123,7 @@ class TestHuntCorpusEval(unittest.TestCase):
with self.subTest(hunt=hunt.id, scenario=pos_id):
self.assertTrue(
pos_events,
- f"hunt {hunt.id} declares positive_incident_id={pos_id} "
- f"but no matching events exist in {_HUNT_TELEMETRY_PATH.name}.",
+ f"hunt {hunt.id} declares positive_incident_id={pos_id} but no matching events exist in {_HUNT_TELEMETRY_PATH.name}.",
)
result = self.engine.run(hunt, pos_events)
threshold = hunt.expected.min_match_score
@@ -142,10 +134,7 @@ class TestHuntCorpusEval(unittest.TestCase):
f"best score {result.match_score:.2f} < {threshold:.2f}"
)
if misses:
- self.fail(
- "Positive-scenario miss — these hunts did not fire on their "
- "declared synthetic incident:\n" + "\n".join(misses)
- )
+ self.fail("Positive-scenario miss — these hunts did not fire on their declared synthetic incident:\n" + "\n".join(misses))
def test_negative_scenarios_do_not_fire(self) -> None:
"""Hunt MUST NOT fire on its declared negative incident (false positive guard)."""
@@ -158,8 +147,7 @@ class TestHuntCorpusEval(unittest.TestCase):
with self.subTest(hunt=hunt.id, scenario=neg_id):
self.assertTrue(
neg_events,
- f"hunt {hunt.id} declares negative_incident_id={neg_id} "
- f"but no matching events exist in {_HUNT_TELEMETRY_PATH.name}.",
+ f"hunt {hunt.id} declares negative_incident_id={neg_id} but no matching events exist in {_HUNT_TELEMETRY_PATH.name}.",
)
result = self.engine.run(hunt, neg_events)
if result.findings:
@@ -169,10 +157,7 @@ class TestHuntCorpusEval(unittest.TestCase):
f"{result.match_score:.2f})"
)
if false_positives:
- self.fail(
- "False-positive regression — these hunts fired on their "
- "declared negative scenario:\n" + "\n".join(false_positives)
- )
+ self.fail("False-positive regression — these hunts fired on their declared negative scenario:\n" + "\n".join(false_positives))
def test_every_hunt_telemetry_event_is_owned(self) -> None:
"""Every INC-HUNT-* event must be referenced by at least one hunt YAML.
@@ -187,13 +172,7 @@ class TestHuntCorpusEval(unittest.TestCase):
if hunt.expected.negative_incident_id:
owned[hunt.expected.negative_incident_id].add(hunt.id)
- orphans = sorted(
- {
- e["incident_id"]
- for e in self.events
- if e["incident_id"] not in owned
- }
- )
+ orphans = sorted({e["incident_id"] for e in self.events if e["incident_id"] not in owned})
self.assertFalse(
orphans,
"These hunt-telemetry incident_ids are not referenced by any hunt "
@@ -258,25 +237,29 @@ def evaluate_hunt_corpus() -> HuntCorpusEvalResult:
positives_expected += 1
pos_events = _events_for_incident(events, pos_id)
if not pos_events:
- misses.append({
- "hunt_id": hunt.id,
- "scenario": pos_id,
- "reason": "no_matching_events",
- })
+ misses.append(
+ {
+ "hunt_id": hunt.id,
+ "scenario": pos_id,
+ "reason": "no_matching_events",
+ }
+ )
else:
result = engine.run(hunt, pos_events)
threshold = hunt.expected.min_match_score
if result.findings and result.match_score >= threshold:
positives_caught += 1
else:
- misses.append({
- "hunt_id": hunt.id,
- "scenario": pos_id,
- "events_scanned": result.events_scanned,
- "findings": len(result.findings),
- "match_score": round(result.match_score, 4),
- "threshold": threshold,
- })
+ misses.append(
+ {
+ "hunt_id": hunt.id,
+ "scenario": pos_id,
+ "events_scanned": result.events_scanned,
+ "findings": len(result.findings),
+ "match_score": round(result.match_score, 4),
+ "threshold": threshold,
+ }
+ )
neg_id = hunt.expected.negative_incident_id
if neg_id:
@@ -287,16 +270,16 @@ def evaluate_hunt_corpus() -> HuntCorpusEvalResult:
result = engine.run(hunt, neg_events)
if result.findings:
false_positive_count += 1
- false_positives.append({
- "hunt_id": hunt.id,
- "scenario": neg_id,
- "findings": len(result.findings),
- "match_score": round(result.match_score, 4),
- })
+ false_positives.append(
+ {
+ "hunt_id": hunt.id,
+ "scenario": neg_id,
+ "findings": len(result.findings),
+ "match_score": round(result.match_score, 4),
+ }
+ )
- orphans = sorted(
- {e["incident_id"] for e in events if e["incident_id"] not in owned}
- )
+ orphans = sorted({e["incident_id"] for e in events if e["incident_id"] not in owned})
return HuntCorpusEvalResult(
hunts_total=len(hunts),
diff --git a/services/agents/tests/test_investigation_completeness.py b/services/agents/tests/test_investigation_completeness.py
index e6f11353e..3efb86711 100644
--- a/services/agents/tests/test_investigation_completeness.py
+++ b/services/agents/tests/test_investigation_completeness.py
@@ -285,8 +285,7 @@ class TestInvestigationCompleteness(unittest.TestCase):
self.assertGreaterEqual(
summary["template_macro_mean"],
0.80,
- "Per-template completeness below 0.80.\n"
- f"Failing templates: {summary['failing_templates']}",
+ f"Per-template completeness below 0.80.\nFailing templates: {summary['failing_templates']}",
)
diff --git a/services/agents/tests/test_mitre_accuracy.py b/services/agents/tests/test_mitre_accuracy.py
index 1e040ffad..e1ee1cb73 100644
--- a/services/agents/tests/test_mitre_accuracy.py
+++ b/services/agents/tests/test_mitre_accuracy.py
@@ -383,9 +383,7 @@ class MitreAccuracyResult:
)
templates.sort(key=lambda t: (t["accuracy"], -t["cases"]))
- macro = (
- sum(t["accuracy"] for t in templates) / len(templates) if templates else 0.0
- )
+ macro = sum(t["accuracy"] for t in templates) / len(templates) if templates else 0.0
failing = [t for t in templates if t["accuracy"] < 0.80]
return {
"templates": templates,
@@ -565,8 +563,7 @@ class TestMitreAccuracy(unittest.TestCase):
self.assertGreaterEqual(
summary["template_macro_accuracy"],
0.80,
- "Per-template MITRE accuracy below 80%.\n"
- f"Failing templates: {summary['failing_templates']}",
+ f"Per-template MITRE accuracy below 80%.\nFailing templates: {summary['failing_templates']}",
)
def test_each_incident_has_template_id(self) -> None:
@@ -597,8 +594,7 @@ class TestMitreAccuracy(unittest.TestCase):
self.assertLessEqual(
worst[1],
max(4, int(len(SYNTHETIC_INCIDENTS_DATA) * 0.05)),
- f"Template '{worst[0]}' appears {worst[1]} times "
- f"(>{int(len(SYNTHETIC_INCIDENTS_DATA) * 0.05)} = 5% of dataset).",
+ f"Template '{worst[0]}' appears {worst[1]} times (>{int(len(SYNTHETIC_INCIDENTS_DATA) * 0.05)} = 5% of dataset).",
)
diff --git a/services/agents/tests/test_response_quality.py b/services/agents/tests/test_response_quality.py
index b0f5cc9d4..2c31f494f 100644
--- a/services/agents/tests/test_response_quality.py
+++ b/services/agents/tests/test_response_quality.py
@@ -497,8 +497,7 @@ class TestResponseQuality(unittest.TestCase):
self.assertGreaterEqual(
summary["template_macro_score"],
0.75,
- "Per-template response-quality below 0.75.\n"
- f"Failing templates: {summary['failing_templates']}",
+ f"Per-template response-quality below 0.75.\nFailing templates: {summary['failing_templates']}",
)
diff --git a/services/agents/tests/test_synthetic_telemetry.py b/services/agents/tests/test_synthetic_telemetry.py
index 60b7e1640..cb8fd20b1 100644
--- a/services/agents/tests/test_synthetic_telemetry.py
+++ b/services/agents/tests/test_synthetic_telemetry.py
@@ -53,18 +53,14 @@ _TELEMETRY_PATH = _TESTS_DIR / "eval_data" / "synthetic_telemetry.jsonl"
def _load_incidents() -> list[dict[str, Any]]:
if not _INCIDENTS_PATH.exists():
- raise FileNotFoundError(
- f"Missing {_INCIDENTS_PATH}. Run `python3 scripts/generate_eval_incidents.py`."
- )
+ raise FileNotFoundError(f"Missing {_INCIDENTS_PATH}. Run `python3 scripts/generate_eval_incidents.py`.")
with _INCIDENTS_PATH.open() as f:
return json.load(f)
def _load_telemetry() -> list[dict[str, Any]]:
if not _TELEMETRY_PATH.exists():
- raise FileNotFoundError(
- f"Missing {_TELEMETRY_PATH}. Run `python3 scripts/generate_eval_incidents.py`."
- )
+ raise FileNotFoundError(f"Missing {_TELEMETRY_PATH}. Run `python3 scripts/generate_eval_incidents.py`.")
events: list[dict[str, Any]] = []
with _TELEMETRY_PATH.open() as f:
for i, line in enumerate(f, start=1):
@@ -74,9 +70,7 @@ def _load_telemetry() -> list[dict[str, Any]]:
try:
events.append(json.loads(line))
except json.JSONDecodeError as exc: # pragma: no cover
- raise AssertionError(
- f"{_TELEMETRY_PATH.name}: line {i} is not valid JSON ({exc})"
- ) from exc
+ raise AssertionError(f"{_TELEMETRY_PATH.name}: line {i} is not valid JSON ({exc})") from exc
return events
@@ -213,8 +207,7 @@ class TestSyntheticTelemetrySchema(unittest.TestCase):
self.assertEqual(
missing,
[],
- "synthetic_telemetry.jsonl is missing events for the following "
- f"advertised sources: {missing}",
+ f"synthetic_telemetry.jsonl is missing events for the following advertised sources: {missing}",
)
def test_per_source_required_fields(self) -> None:
@@ -233,8 +226,7 @@ class TestSyntheticTelemetrySchema(unittest.TestCase):
self.assertEqual(
bad,
[],
- f"{len(bad)} events missing per-source required fields "
- f"(sample: {bad[:3]}). See REQUIRED_FIELDS_BY_SOURCE.",
+ f"{len(bad)} events missing per-source required fields (sample: {bad[:3]}). See REQUIRED_FIELDS_BY_SOURCE.",
)
def test_no_unresolved_placeholders(self) -> None:
@@ -249,8 +241,7 @@ class TestSyntheticTelemetrySchema(unittest.TestCase):
self.assertEqual(
bad,
[],
- f"{len(bad)} events still contain unresolved placeholders "
- f"(sample: {bad[:3]}).",
+ f"{len(bad)} events still contain unresolved placeholders (sample: {bad[:3]}).",
)
def test_template_telemetry_is_not_concentrated(self) -> None:
@@ -267,8 +258,7 @@ class TestSyntheticTelemetrySchema(unittest.TestCase):
self.assertLessEqual(
share,
0.05,
- f"Template '{top_template}' accounts for {share:.1%} of telemetry — "
- "dataset has skewed; rebalance the templates.",
+ f"Template '{top_template}' accounts for {share:.1%} of telemetry — dataset has skewed; rebalance the templates.",
)
def test_telemetry_template_ids_match_incident_template_ids(self) -> None:
@@ -286,8 +276,7 @@ class TestSyntheticTelemetrySchema(unittest.TestCase):
self.assertEqual(
bad,
[],
- f"{len(bad)} events disagree with the incident dataset on template_id "
- f"(sample: {bad[:3]}).",
+ f"{len(bad)} events disagree with the incident dataset on template_id (sample: {bad[:3]}).",
)
diff --git a/services/api/app/api/v1/endpoints/connectors.py b/services/api/app/api/v1/endpoints/connectors.py
index 23eac195d..9c93740c6 100644
--- a/services/api/app/api/v1/endpoints/connectors.py
+++ b/services/api/app/api/v1/endpoints/connectors.py
@@ -304,11 +304,7 @@ async def list_connectors(
db: DBSession,
) -> list[ConnectorResponse]:
"""List all connector instances for the caller's tenant."""
- result = await db.execute(
- select(Connector)
- .where(Connector.tenant_id == current_user.tenant_id)
- .order_by(Connector.created_at)
- )
+ result = await db.execute(select(Connector).where(Connector.tenant_id == current_user.tenant_id).order_by(Connector.created_at))
connectors = result.scalars().all()
return [ConnectorResponse.model_validate(c) for c in connectors]
diff --git a/services/api/app/api/v1/endpoints/detection_proposals.py b/services/api/app/api/v1/endpoints/detection_proposals.py
index e5daf4dd2..dca677f79 100644
--- a/services/api/app/api/v1/endpoints/detection_proposals.py
+++ b/services/api/app/api/v1/endpoints/detection_proposals.py
@@ -98,8 +98,7 @@ class EvalAttachRequest(BaseModel):
eval_report: dict[str, Any] = Field(
...,
description=(
- "Full JSON output of `python3 scripts/run_evals.py --baseline ... "
- "--max-regression-pp ...` for the candidate ruleset."
+ "Full JSON output of `python3 scripts/run_evals.py --baseline ... --max-regression-pp ...` for the candidate ruleset."
),
)
max_regression_pp: float = Field(
@@ -185,9 +184,7 @@ def _evaluate_eval_report(
if cmp.get("available"):
regressed = bool(cmp.get("regressed"))
drop_pp = float(cmp.get("mitre_drop_pp", 0.0))
- baseline = float(
- cmp.get("deltas", {}).get("mitre_accuracy", {}).get("baseline", baseline_score or candidate_score)
- )
+ baseline = float(cmp.get("deltas", {}).get("mitre_accuracy", {}).get("baseline", baseline_score or candidate_score))
else:
baseline = baseline_score if baseline_score is not None else candidate_score
drop_pp = round(max(0.0, (baseline - candidate_score) * 100), 4)
@@ -235,10 +232,7 @@ async def list_proposals(
if proposal_status:
filters.append(DetectionRuleProposal.status == proposal_status)
result = await db.execute(
- select(DetectionRuleProposal)
- .where(and_(*filters))
- .order_by(DetectionRuleProposal.created_at.desc())
- .limit(limit)
+ select(DetectionRuleProposal).where(and_(*filters)).order_by(DetectionRuleProposal.created_at.desc()).limit(limit)
)
return [ProposalResponse.model_validate(p) for p in result.scalars().all()]
@@ -289,11 +283,7 @@ async def list_baselines(
]
if suite:
filters.append(DetectionEvalBaseline.suite == suite)
- result = await db.execute(
- select(DetectionEvalBaseline)
- .where(and_(*filters))
- .order_by(DetectionEvalBaseline.created_at.desc())
- )
+ result = await db.execute(select(DetectionEvalBaseline).where(and_(*filters)).order_by(DetectionEvalBaseline.created_at.desc()))
return [BaselineResponse.model_validate(b) for b in result.scalars().all()]
diff --git a/services/api/app/api/v1/endpoints/federated.py b/services/api/app/api/v1/endpoints/federated.py
index aa367b818..7902fd79f 100644
--- a/services/api/app/api/v1/endpoints/federated.py
+++ b/services/api/app/api/v1/endpoints/federated.py
@@ -207,10 +207,7 @@ async def _fetch_target_connectors(
if missing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
- detail=(
- "connector_ids not found, not enabled, or not federated-capable: "
- + ", ".join(missing)
- ),
+ detail=("connector_ids not found, not enabled, or not federated-capable: " + ", ".join(missing)),
)
return rows
@@ -436,9 +433,7 @@ async def federated_search(
detail="query must include free_text or at least one indicator",
)
- targets = await _fetch_target_connectors(
- db, current_user.tenant_id, request.connector_ids
- )
+ targets = await _fetch_target_connectors(db, current_user.tenant_id, request.connector_ids)
if not targets:
# No federated-capable connectors configured: don't 404, return
# an empty merged result with empty sources[]. Lets the caller
@@ -464,10 +459,7 @@ async def federated_search(
)
fan_out = await asyncio.gather(
- *(
- _query_one_backend(connector, query_payload, timeout)
- for connector in targets
- ),
+ *(_query_one_backend(connector, query_payload, timeout) for connector in targets),
return_exceptions=False,
)
diff --git a/services/api/app/api/v1/endpoints/insider_threat.py b/services/api/app/api/v1/endpoints/insider_threat.py
index 75ef061da..0766228b4 100644
--- a/services/api/app/api/v1/endpoints/insider_threat.py
+++ b/services/api/app/api/v1/endpoints/insider_threat.py
@@ -217,9 +217,7 @@ async def list_peer_groups(
current_user: User = Depends(get_current_user),
) -> list[InsiderPeerGroup]:
result = await db.execute(
- select(InsiderPeerGroup)
- .where(InsiderPeerGroup.tenant_id == current_user.tenant_id)
- .order_by(InsiderPeerGroup.name)
+ select(InsiderPeerGroup).where(InsiderPeerGroup.tenant_id == current_user.tenant_id).order_by(InsiderPeerGroup.name)
)
return list(result.scalars().all())
diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.py
index 3cac02914..7d39b7396 100644
--- a/services/api/app/api/v1/endpoints/metrics.py
+++ b/services/api/app/api/v1/endpoints/metrics.py
@@ -74,34 +74,12 @@ async def get_dashboard_metrics(
week_start = now - timedelta(days=7)
# ── Alert counts ──────────────────────────────────────────────────────────
- total_q = await db.scalar(
- select(func.count()).where(Alert.tenant_id == tenant_id)
- )
- new_q = await db.scalar(
- select(func.count()).where(
- and_(Alert.tenant_id == tenant_id, Alert.status == "new")
- )
- )
- critical_q = await db.scalar(
- select(func.count()).where(
- and_(Alert.tenant_id == tenant_id, Alert.severity == "critical")
- )
- )
- high_q = await db.scalar(
- select(func.count()).where(
- and_(Alert.tenant_id == tenant_id, Alert.severity == "high")
- )
- )
- medium_q = await db.scalar(
- select(func.count()).where(
- and_(Alert.tenant_id == tenant_id, Alert.severity == "medium")
- )
- )
- low_q = await db.scalar(
- select(func.count()).where(
- and_(Alert.tenant_id == tenant_id, Alert.severity == "low")
- )
- )
+ total_q = await db.scalar(select(func.count()).where(Alert.tenant_id == tenant_id))
+ new_q = await db.scalar(select(func.count()).where(and_(Alert.tenant_id == tenant_id, Alert.status == "new")))
+ critical_q = await db.scalar(select(func.count()).where(and_(Alert.tenant_id == tenant_id, Alert.severity == "critical")))
+ high_q = await db.scalar(select(func.count()).where(and_(Alert.tenant_id == tenant_id, Alert.severity == "high")))
+ medium_q = await db.scalar(select(func.count()).where(and_(Alert.tenant_id == tenant_id, Alert.severity == "medium")))
+ low_q = await db.scalar(select(func.count()).where(and_(Alert.tenant_id == tenant_id, Alert.severity == "low")))
resolved_today_q = await db.scalar(
select(func.count()).where(
and_(
@@ -124,16 +102,8 @@ async def get_dashboard_metrics(
)
# ── Case counts ───────────────────────────────────────────────────────────
- open_cases_q = await db.scalar(
- select(func.count()).where(
- and_(Case.tenant_id == tenant_id, Case.status == "open")
- )
- )
- in_progress_q = await db.scalar(
- select(func.count()).where(
- and_(Case.tenant_id == tenant_id, Case.status == "in_progress")
- )
- )
+ open_cases_q = await db.scalar(select(func.count()).where(and_(Case.tenant_id == tenant_id, Case.status == "open")))
+ in_progress_q = await db.scalar(select(func.count()).where(and_(Case.tenant_id == tenant_id, Case.status == "in_progress")))
resolved_week_q = await db.scalar(
select(func.count()).where(
and_(
@@ -152,26 +122,16 @@ async def get_dashboard_metrics(
# ── Sources (connectors) ──────────────────────────────────────────────────
connectors_rows = (
- await db.execute(
- select(Connector.name, Connector.connector_type, Connector.health_status).where(
- Connector.tenant_id == tenant_id
- )
- )
+ await db.execute(select(Connector.name, Connector.connector_type, Connector.health_status).where(Connector.tenant_id == tenant_id))
).all()
# Count alerts per connector_type
source_counts_rows = (
await db.execute(
- select(Alert.connector_type, func.count().label("cnt"))
- .where(Alert.tenant_id == tenant_id)
- .group_by(Alert.connector_type)
+ select(Alert.connector_type, func.count().label("cnt")).where(Alert.tenant_id == tenant_id).group_by(Alert.connector_type)
)
).all()
- source_count_map: dict[str, int] = {
- row.connector_type: row.cnt
- for row in source_counts_rows
- if row.connector_type
- }
+ source_count_map: dict[str, int] = {row.connector_type: row.cnt for row in source_counts_rows if row.connector_type}
sources: list[SourceStat] = []
seen: set[str] = set()
@@ -234,9 +194,7 @@ async def get_dashboard_metrics(
]
# ── Threats by source ─────────────────────────────────────────────────────
- threats_by_source = [
- SourceThreat(source=k, count=v) for k, v in source_count_map.items()
- ]
+ threats_by_source = [SourceThreat(source=k, count=v) for k, v in source_count_map.items()]
return DashboardMetrics(
alerts=alert_metrics,
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index 0792dce22..b71d1dc62 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -91,9 +91,7 @@ async def list_child_tenants(
current_user: User = Depends(get_current_user),
) -> list[Tenant]:
"""Return all child tenants of the current parent tenant."""
- result = await db.execute(
- select(Tenant).where(Tenant.parent_tenant_id == current_user.tenant_id)
- )
+ result = await db.execute(select(Tenant).where(Tenant.parent_tenant_id == current_user.tenant_id))
return list(result.scalars().all())
@@ -220,9 +218,7 @@ async def list_metrics(
) -> list[MSSPTenantMetrics]:
"""Return the latest metrics snapshot for every child tenant."""
# Get child tenant ids
- children_result = await db.execute(
- select(Tenant.id).where(Tenant.parent_tenant_id == current_user.tenant_id)
- )
+ children_result = await db.execute(select(Tenant.id).where(Tenant.parent_tenant_id == current_user.tenant_id))
child_ids = list(children_result.scalars().all())
if not child_ids:
return []
@@ -242,8 +238,7 @@ async def list_metrics(
result = await db.execute(
select(MSSPTenantMetrics).join(
subq,
- (MSSPTenantMetrics.tenant_id == subq.c.tenant_id)
- & (MSSPTenantMetrics.snapshot_at == subq.c.snapshot_at),
+ (MSSPTenantMetrics.tenant_id == subq.c.tenant_id) & (MSSPTenantMetrics.snapshot_at == subq.c.snapshot_at),
)
)
return list(result.scalars().all())
diff --git a/services/api/app/api/v1/endpoints/remediation.py b/services/api/app/api/v1/endpoints/remediation.py
index f23d58b20..af428bcbc 100644
--- a/services/api/app/api/v1/endpoints/remediation.py
+++ b/services/api/app/api/v1/endpoints/remediation.py
@@ -84,9 +84,7 @@ async def get_maturity_config(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> RemediationMaturity:
- result = await db.execute(
- select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id)
- )
+ result = await db.execute(select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id))
config = result.scalar_one_or_none()
if not config:
config = RemediationMaturity(
@@ -105,9 +103,7 @@ async def update_maturity_config(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> RemediationMaturity:
- result = await db.execute(
- select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id)
- )
+ result = await db.execute(select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id))
config = result.scalar_one_or_none()
if not config:
config = RemediationMaturity(tenant_id=current_user.tenant_id)
@@ -153,9 +149,7 @@ async def list_whitelist(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> list[RemediationWhitelist]:
- result = await db.execute(
- select(RemediationWhitelist).where(RemediationWhitelist.tenant_id == current_user.tenant_id)
- )
+ result = await db.execute(select(RemediationWhitelist).where(RemediationWhitelist.tenant_id == current_user.tenant_id))
return list(result.scalars().all())
diff --git a/services/api/app/api/v1/endpoints/reports.py b/services/api/app/api/v1/endpoints/reports.py
index 0dac0bdbe..4fd8fb33d 100644
--- a/services/api/app/api/v1/endpoints/reports.py
+++ b/services/api/app/api/v1/endpoints/reports.py
@@ -87,9 +87,7 @@ async def list_templates(
current_user: User = Depends(get_current_user),
) -> list[ReportTemplate]:
result = await db.execute(
- select(ReportTemplate)
- .where(ReportTemplate.tenant_id == current_user.tenant_id)
- .order_by(ReportTemplate.name)
+ select(ReportTemplate).where(ReportTemplate.tenant_id == current_user.tenant_id).order_by(ReportTemplate.name)
)
return list(result.scalars().all())
diff --git a/services/api/app/api/v1/endpoints/threat_intel.py b/services/api/app/api/v1/endpoints/threat_intel.py
index b576cdca5..6943c072b 100644
--- a/services/api/app/api/v1/endpoints/threat_intel.py
+++ b/services/api/app/api/v1/endpoints/threat_intel.py
@@ -208,9 +208,7 @@ async def list_feeds(
current_user: User = Depends(get_current_user),
) -> list[ThreatIntelFeed]:
result = await db.execute(
- select(ThreatIntelFeed)
- .where(ThreatIntelFeed.tenant_id == current_user.tenant_id)
- .order_by(ThreatIntelFeed.name)
+ select(ThreatIntelFeed).where(ThreatIntelFeed.tenant_id == current_user.tenant_id).order_by(ThreatIntelFeed.name)
)
return list(result.scalars().all())
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 4c45fc0c1..4d241a277 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -209,30 +209,30 @@ class Settings(BaseSettings):
# individual flags via env vars (e.g. ``AISOC_FEATURE_RBA=false``).
# ------------------------------------------------------------------
# Wave 1 — close 2026 table-stakes
- AISOC_FEATURE_RBA: bool = True # Risk-Based Alerting + entity rollup
- AISOC_FEATURE_CONFIDENCE: bool = True # Detection confidence + explainability
- AISOC_FEATURE_CHATOPS_VERIFY: bool = True # Slack/Teams interactive user verification
- AISOC_FEATURE_DETECTION_DRIFT: bool = True # Weekly purple-team drift sweep
- AISOC_FEATURE_KPI_BAR: bool = True # 2026 KPI bar in SLA dashboard
+ AISOC_FEATURE_RBA: bool = True # Risk-Based Alerting + entity rollup
+ AISOC_FEATURE_CONFIDENCE: bool = True # Detection confidence + explainability
+ AISOC_FEATURE_CHATOPS_VERIFY: bool = True # Slack/Teams interactive user verification
+ AISOC_FEATURE_DETECTION_DRIFT: bool = True # Weekly purple-team drift sweep
+ AISOC_FEATURE_KPI_BAR: bool = True # 2026 KPI bar in SLA dashboard
# Wave 2 — eval-graded differentiation
- AISOC_FEATURE_DAC: bool = True # Detection-as-code lifecycle
- AISOC_FEATURE_HUNT_AS_CODE: bool = True # YAML hunt corpus + scheduler
- AISOC_FEATURE_BENCHMARK_PUBLIC: bool = True # Public scoreboard
- AISOC_FEATURE_AIVAI_EVAL: bool = True # AI-vs-AI adversary suite
+ AISOC_FEATURE_DAC: bool = True # Detection-as-code lifecycle
+ AISOC_FEATURE_HUNT_AS_CODE: bool = True # YAML hunt corpus + scheduler
+ AISOC_FEATURE_BENCHMARK_PUBLIC: bool = True # Public scoreboard
+ AISOC_FEATURE_AIVAI_EVAL: bool = True # AI-vs-AI adversary suite
# Wave 3 — operational maturity
- AISOC_FEATURE_FED_SEARCH: bool = True # Federated SIEM search
- AISOC_FEATURE_MSSP: bool = True # Parent-tenant console
- AISOC_FEATURE_ASSET_INVENTORY: bool = True # Asset table + KEV/EPSS
- AISOC_FEATURE_INSIDER_THREAT: bool = True # Insider-threat module
+ AISOC_FEATURE_FED_SEARCH: bool = True # Federated SIEM search
+ AISOC_FEATURE_MSSP: bool = True # Parent-tenant console
+ AISOC_FEATURE_ASSET_INVENTORY: bool = True # Asset table + KEV/EPSS
+ AISOC_FEATURE_INSIDER_THREAT: bool = True # Insider-threat module
AISOC_FEATURE_REMEDIATION_TIERS: bool = True # L0–L4 maturity tiers
# Wave 4 — strategic moat
- AISOC_FEATURE_INTERNAL_TI: bool = True # Closed-case IOC extraction
- AISOC_FEATURE_CSPM: bool = True # Cloud security posture
- AISOC_FEATURE_IDENTITY_GRAPH: bool = True # Identity-first correlation graph
- AISOC_FEATURE_BOARD_REPORTS: bool = True # Auto-generated monthly board reports
+ AISOC_FEATURE_INTERNAL_TI: bool = True # Closed-case IOC extraction
+ AISOC_FEATURE_CSPM: bool = True # Cloud security posture
+ AISOC_FEATURE_IDENTITY_GRAPH: bool = True # Identity-first correlation graph
+ AISOC_FEATURE_BOARD_REPORTS: bool = True # Auto-generated monthly board reports
# Drift sweep cadence (hours). Used by services/purple-team scheduler when
# AISOC_FEATURE_DETECTION_DRIFT is True. Defaults to 168h (weekly).
diff --git a/services/api/app/models/asset.py b/services/api/app/models/asset.py
index 4b5f33c9c..4f84cc99c 100644
--- a/services/api/app/models/asset.py
+++ b/services/api/app/models/asset.py
@@ -39,9 +39,7 @@ class Asset(Base):
onupdate=lambda: datetime.now(UTC),
)
- vulnerabilities: Mapped[list[AssetVulnerability]] = relationship(
- "AssetVulnerability", back_populates="asset", lazy="noload"
- )
+ vulnerabilities: Mapped[list[AssetVulnerability]] = relationship("AssetVulnerability", back_populates="asset", lazy="noload")
class AssetVulnerability(Base):
@@ -75,12 +73,8 @@ class AlertAssetCorrelation(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
alert_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
- asset_id: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("assets.id", ondelete="SET NULL"), nullable=True
- )
- vuln_id: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("asset_vulnerabilities.id", ondelete="SET NULL"), nullable=True
- )
+ asset_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("assets.id", ondelete="SET NULL"), nullable=True)
+ vuln_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("asset_vulnerabilities.id", ondelete="SET NULL"), nullable=True)
match_field: Mapped[str] = mapped_column(String(50), default="ip")
confidence: Mapped[float] = mapped_column(Float, default=1.0)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
diff --git a/services/api/app/models/identity_graph.py b/services/api/app/models/identity_graph.py
index 2e3280a10..f5f54f442 100644
--- a/services/api/app/models/identity_graph.py
+++ b/services/api/app/models/identity_graph.py
@@ -39,12 +39,8 @@ class IdentityEdge(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
- source_id: Mapped[uuid.UUID] = mapped_column(
- ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False
- )
- target_id: Mapped[uuid.UUID] = mapped_column(
- ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False
- )
+ source_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False)
+ target_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False)
edge_type: Mapped[str] = mapped_column(String(50), nullable=False)
weight: Mapped[float] = mapped_column(Float, default=1.0)
valid_from: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
@@ -59,9 +55,7 @@ class AlertIdentityLink(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
alert_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
- node_id: Mapped[uuid.UUID] = mapped_column(
- ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False
- )
+ node_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("identity_nodes.id", ondelete="CASCADE"), nullable=False)
link_reason: Mapped[str] = mapped_column(String(50), nullable=False)
confidence: Mapped[float] = mapped_column(Float, default=1.0)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
diff --git a/services/api/app/models/insider_threat.py b/services/api/app/models/insider_threat.py
index 9650500f5..abb7d0703 100644
--- a/services/api/app/models/insider_threat.py
+++ b/services/api/app/models/insider_threat.py
@@ -17,9 +17,7 @@ class UserRiskProfile(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
- user_id: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="CASCADE"), nullable=True
- )
+ user_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=True)
external_user_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)
risk_score: Mapped[float] = mapped_column(Float, default=0.0)
risk_tier: Mapped[str] = mapped_column(String(20), default="low")
@@ -33,9 +31,7 @@ class UserRiskProfile(Base):
is_watchlisted: Mapped[bool] = mapped_column(Boolean, default=False)
watchlist_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
watchlisted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
- watchlisted_by: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ watchlisted_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
# timestamps
last_evaluated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
@@ -45,9 +41,7 @@ class UserRiskProfile(Base):
onupdate=lambda: datetime.now(UTC),
)
- indicators: Mapped[list[InsiderIndicator]] = relationship(
- "InsiderIndicator", back_populates="profile", lazy="noload"
- )
+ indicators: Mapped[list[InsiderIndicator]] = relationship("InsiderIndicator", back_populates="profile", lazy="noload")
class InsiderIndicator(Base):
@@ -55,18 +49,14 @@ class InsiderIndicator(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
- profile_id: Mapped[uuid.UUID] = mapped_column(
- ForeignKey("user_risk_profiles.id", ondelete="CASCADE"), nullable=False
- )
+ profile_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("user_risk_profiles.id", ondelete="CASCADE"), nullable=False)
indicator_type: Mapped[str] = mapped_column(String(100), nullable=False)
severity: Mapped[str] = mapped_column(String(20), default="medium")
description: Mapped[str] = mapped_column(Text, nullable=False)
source_alert_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
evidence: Mapped[dict] = mapped_column(JSONB, default=dict)
occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
- acknowledged_by: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ acknowledged_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
acknowledged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
diff --git a/services/api/app/models/mssp.py b/services/api/app/models/mssp.py
index 341c3ad5e..ab101a41c 100644
--- a/services/api/app/models/mssp.py
+++ b/services/api/app/models/mssp.py
@@ -35,9 +35,7 @@ class MSSPDelegation(Base):
parent_tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
child_tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
granted_role: Mapped[str] = mapped_column(String(50), default="soc_analyst")
- granted_by_user: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ granted_by_user: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
diff --git a/services/api/app/models/posture.py b/services/api/app/models/posture.py
index 9623bb3e3..4f76af9d2 100644
--- a/services/api/app/models/posture.py
+++ b/services/api/app/models/posture.py
@@ -37,9 +37,7 @@ class PostureFinding(Base):
last_evaluated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
resolved_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
suppressed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
- suppressed_by: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ suppressed_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
suppress_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
updated_at: Mapped[datetime] = mapped_column(
@@ -79,7 +77,5 @@ class PostureDriftEvent(Base):
old_value: Mapped[str | None] = mapped_column(Text, nullable=True)
new_value: Mapped[str | None] = mapped_column(Text, nullable=True)
severity: Mapped[str] = mapped_column(String(20), default="medium")
- linked_finding: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("posture_findings.id", ondelete="SET NULL"), nullable=True
- )
+ linked_finding: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("posture_findings.id", ondelete="SET NULL"), nullable=True)
detected_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
diff --git a/services/api/app/models/remediation.py b/services/api/app/models/remediation.py
index f5c439d80..77de91872 100644
--- a/services/api/app/models/remediation.py
+++ b/services/api/app/models/remediation.py
@@ -16,14 +16,10 @@ class RemediationMaturity(Base):
__tablename__ = "remediation_maturity"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- tenant_id: Mapped[uuid.UUID] = mapped_column(
- ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, unique=True
- )
+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, unique=True)
maturity_tier: Mapped[int] = mapped_column(Integer, default=0)
action_overrides: Mapped[dict] = mapped_column(JSONB, default=dict)
- changed_by: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ changed_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
changed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
@@ -51,8 +47,6 @@ class RemediationWhitelist(Base):
action_type: Mapped[str] = mapped_column(String(100), nullable=False)
blast_radius: Mapped[str] = mapped_column(String(20), nullable=False)
constraints: Mapped[dict] = mapped_column(JSONB, default=dict)
- approved_by: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ approved_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
diff --git a/services/api/app/models/report.py b/services/api/app/models/report.py
index 7e0e87a7c..a4cb84ac2 100644
--- a/services/api/app/models/report.py
+++ b/services/api/app/models/report.py
@@ -26,9 +26,7 @@ class ReportTemplate(Base):
output_format: Mapped[str] = mapped_column(String(10), default="pdf")
is_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
last_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
- created_by: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("users.id", ondelete="SET NULL"), nullable=True
- )
+ created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
@@ -42,9 +40,7 @@ class ReportArtefact(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
- template_id: Mapped[uuid.UUID | None] = mapped_column(
- ForeignKey("report_templates.id", ondelete="SET NULL"), nullable=True
- )
+ template_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("report_templates.id", ondelete="SET NULL"), nullable=True)
report_type: Mapped[str] = mapped_column(String(50), nullable=False)
title: Mapped[str] = mapped_column(Text, nullable=False)
period_start: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
diff --git a/services/api/app/security/credential_vault.py b/services/api/app/security/credential_vault.py
index 54e76d83f..fa8548ebd 100644
--- a/services/api/app/security/credential_vault.py
+++ b/services/api/app/security/credential_vault.py
@@ -134,7 +134,7 @@ class CredentialVault:
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
if not value.startswith(_CIPHER_PREFIX):
return value
- token = value[len(_CIPHER_PREFIX):].encode("ascii")
+ token = value[len(_CIPHER_PREFIX) :].encode("ascii")
try:
return self._fernet.decrypt(token).decode("utf-8")
except InvalidToken as exc:
@@ -219,7 +219,7 @@ def get_vault() -> CredentialVault:
logger.warning(
"AISOC_CREDENTIAL_KEY is not set; using ephemeral process-local key. Connector secrets will not survive a restart. "
"Generate a key with "
- "`python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\"`"
+ '`python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`'
" and set AISOC_CREDENTIAL_KEY."
)
rotation = _split_keys(settings.AISOC_CREDENTIAL_KEY_ROTATION_FROM or "")
diff --git a/services/api/app/services/sla.py b/services/api/app/services/sla.py
index 182fbdde5..eaec455c2 100644
--- a/services/api/app/services/sla.py
+++ b/services/api/app/services/sla.py
@@ -158,14 +158,10 @@ async def _compute_kpi_bar(
total_r = await db.execute(select(func.count()).select_from(Alert).where(*base))
total = int(total_r.scalar_one() or 0)
- fp_r = await db.execute(
- select(func.count()).select_from(Alert).where(*base, Alert.status == "fp")
- )
+ fp_r = await db.execute(select(func.count()).select_from(Alert).where(*base, Alert.status == "fp"))
fp = int(fp_r.scalar_one() or 0)
- cases_r = await db.execute(
- select(func.count(func.distinct(Alert.case_id))).select_from(Alert).where(*base, Alert.case_id.is_not(None))
- )
+ cases_r = await db.execute(select(func.count(func.distinct(Alert.case_id))).select_from(Alert).where(*base, Alert.case_id.is_not(None)))
distinct_cases = int(cases_r.scalar_one() or 0)
tagged_r = await db.execute(
@@ -202,8 +198,7 @@ async def _compute_kpi_bar(
# alerts with zero linked cases are treated as meeting the ratio bar.
breaches = {
"false_positive_rate": fp_rate_pct > targets["false_positive_rate_max_pct"],
- "alert_to_incident_ratio": distinct_cases > 0
- and alert_to_incident < targets["alert_to_incident_ratio_min"],
+ "alert_to_incident_ratio": distinct_cases > 0 and alert_to_incident < targets["alert_to_incident_ratio_min"],
"mitre_technique_tagging": mitre_tag_pct < targets["mitre_technique_tagging_min_pct"],
"mitre_subtechnique_tagging": mitre_sub_pct < targets["mitre_subtechnique_tagging_min_pct"],
}
diff --git a/services/api/tests/test_connectors_endpoint.py b/services/api/tests/test_connectors_endpoint.py
index 1bd58b63c..f824c6898 100644
--- a/services/api/tests/test_connectors_endpoint.py
+++ b/services/api/tests/test_connectors_endpoint.py
@@ -38,11 +38,7 @@ def _mock_response(status_code: int, json_body: Any) -> MagicMock:
resp.status_code = status_code
resp.json = MagicMock(return_value=json_body)
if status_code >= 400:
- resp.raise_for_status = MagicMock(
- side_effect=httpx.HTTPStatusError(
- f"upstream {status_code}", request=MagicMock(), response=resp
- )
- )
+ resp.raise_for_status = MagicMock(side_effect=httpx.HTTPStatusError(f"upstream {status_code}", request=MagicMock(), response=resp))
else:
resp.raise_for_status = MagicMock()
return resp
diff --git a/services/api/tests/test_credential_vault.py b/services/api/tests/test_credential_vault.py
index 1fd12b9e8..1dbcf7675 100644
--- a/services/api/tests/test_credential_vault.py
+++ b/services/api/tests/test_credential_vault.py
@@ -71,8 +71,8 @@ def test_encrypt_dict_recursive(vault: CredentialVault) -> None:
def test_encrypt_dict_with_secret_keys_filter(vault: CredentialVault) -> None:
payload = {
"client_id": "public-id", # leave alone
- "client_secret": "shh", # encrypt
- "region": "us-east-1", # leave alone
+ "client_secret": "shh", # encrypt
+ "region": "us-east-1", # leave alone
}
encrypted = vault.encrypt_dict(payload, secret_keys={"client_secret"})
assert encrypted["client_id"] == "public-id"
diff --git a/services/api/tests/test_graphql.py b/services/api/tests/test_graphql.py
index 51135c025..e84cb3b4f 100644
--- a/services/api/tests/test_graphql.py
+++ b/services/api/tests/test_graphql.py
@@ -134,10 +134,7 @@ class TestGraphQLTenantIsolation:
stmt = _scope(select(Alert), info, Alert)
compiled = str(stmt.compile(compile_kwargs={"literal_binds": True}))
assert "tenant_id" in compiled.lower()
- assert (
- "00000000-0000-0000-0000-000000000000" in compiled
- or "00000000000000000000000000000000" in compiled
- )
+ assert "00000000-0000-0000-0000-000000000000" in compiled or "00000000000000000000000000000000" in compiled
def test_scope_isolates_tenants(self):
"""A query scoped to tenant A must not match rows from tenant B."""
diff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.py
index 8fb6d484f..14cc9c3b9 100644
--- a/services/connectors/app/connectors/__init__.py
+++ b/services/connectors/app/connectors/__init__.py
@@ -64,13 +64,10 @@ def _build_registry() -> dict[str, type[BaseConnector]]:
registry: dict[str, type[BaseConnector]] = {}
for cls in _CONNECTOR_CLASSES:
if not cls.connector_id:
- raise RuntimeError(
- f"connector class {cls.__name__} has empty connector_id; refusing to register"
- )
+ raise RuntimeError(f"connector class {cls.__name__} has empty connector_id; refusing to register")
if cls.connector_id in registry:
raise RuntimeError(
- f"duplicate connector_id '{cls.connector_id}' between "
- f"{registry[cls.connector_id].__name__} and {cls.__name__}"
+ f"duplicate connector_id '{cls.connector_id}' between {registry[cls.connector_id].__name__} and {cls.__name__}"
)
registry[cls.connector_id] = cls
return registry
diff --git a/services/connectors/app/connectors/azure_activity.py b/services/connectors/app/connectors/azure_activity.py
index 2f65ebdf6..df00708a1 100644
--- a/services/connectors/app/connectors/azure_activity.py
+++ b/services/connectors/app/connectors/azure_activity.py
@@ -160,20 +160,13 @@ class AzureActivityConnector(BaseConnector):
await self._authenticate()
# Activity log filter is OData; quote the literal datetime.
- since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%SZ"
- )
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
until = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
- url = (
- f"{_ARM_BASE}/subscriptions/{self._subscription_id}"
- f"/providers/Microsoft.Insights/eventtypes/management/values"
- )
+ url = f"{_ARM_BASE}/subscriptions/{self._subscription_id}/providers/Microsoft.Insights/eventtypes/management/values"
params = {
"api-version": _ACTIVITY_API_VERSION,
- "$filter": (
- f"eventTimestamp ge '{since}' and eventTimestamp le '{until}'"
- ),
+ "$filter": (f"eventTimestamp ge '{since}' and eventTimestamp le '{until}'"),
}
events: list[dict[str, Any]] = []
@@ -231,10 +224,7 @@ class AzureActivityConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("eventDataId") or raw.get("id", ""),
"title": op_name or "Azure Activity Log Event",
- "description": (
- f"status={status}; subStatus={sub_status}; "
- f"resource={resource_id}"
- ),
+ "description": (f"status={status}; subStatus={sub_status}; resource={resource_id}"),
"severity": severity,
"actor": caller,
"actor_email": caller if "@" in caller else None,
diff --git a/services/connectors/app/connectors/azure_defender.py b/services/connectors/app/connectors/azure_defender.py
index ad2a9db96..1e94ea144 100644
--- a/services/connectors/app/connectors/azure_defender.py
+++ b/services/connectors/app/connectors/azure_defender.py
@@ -124,9 +124,7 @@ class AzureDefenderConnector(BaseConnector):
if not self._access_token:
await self._authenticate()
- since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%S.000Z"
- )
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
params = {
"$filter": f"createdDateTime ge {since}",
"$top": _PAGE_SIZE,
@@ -194,9 +192,7 @@ class AzureDefenderConnector(BaseConnector):
"service_source": raw.get("serviceSource"),
"tactics": raw.get("mitreTechniques", []),
"category": raw.get("category"),
- "event_type": (
- f"azure.defender.{(raw.get('serviceSource') or 'unknown').lower()}"
- ),
+ "event_type": (f"azure.defender.{(raw.get('serviceSource') or 'unknown').lower()}"),
"raw_event": raw,
"created_at": raw.get("createdDateTime"),
}
diff --git a/services/connectors/app/connectors/azure_entra.py b/services/connectors/app/connectors/azure_entra.py
index 51c56c981..ebee4d003 100644
--- a/services/connectors/app/connectors/azure_entra.py
+++ b/services/connectors/app/connectors/azure_entra.py
@@ -135,9 +135,7 @@ class AzureEntraConnector(BaseConnector):
await self._authenticate()
# Graph wants ISO 8601 with milliseconds, e.g. ``2024-01-01T00:00:00.000Z``.
- since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%S.000Z"
- )
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
events: list[dict[str, Any]] = []
async with httpx.AsyncClient(timeout=30.0) as client:
@@ -172,10 +170,7 @@ class AzureEntraConnector(BaseConnector):
# Risky sign-ins — these are higher-signal than every signIn.
signin_params = {
- "$filter": (
- f"createdDateTime ge {since} and "
- f"riskLevelAggregated ne 'none'"
- ),
+ "$filter": (f"createdDateTime ge {since} and riskLevelAggregated ne 'none'"),
"$top": _PAGE_SIZE,
"$orderby": "createdDateTime desc",
}
@@ -251,11 +246,7 @@ class AzureEntraConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("id", ""),
"title": raw.get("activityDisplayName", "Entra Directory Audit"),
- "description": (
- f"category={category}; "
- f"result={raw.get('result')}; "
- f"resultReason={raw.get('resultReason', '')}"
- ),
+ "description": (f"category={category}; result={raw.get('result')}; resultReason={raw.get('resultReason', '')}"),
"severity": severity,
"actor": user_part.get("displayName") or app_part.get("displayName"),
"actor_email": user_part.get("userPrincipalName"),
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index 5c248dc13..898e53092 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -185,6 +185,4 @@ class BaseConnector(ABC):
rather than silently returning an empty result set (which would
be indistinguishable from "no matches" and is a footgun).
"""
- raise NotImplementedError(
- f"connector '{self.connector_id}' does not support federated search"
- )
+ raise NotImplementedError(f"connector '{self.connector_id}' does not support federated search")
diff --git a/services/connectors/app/connectors/cloudflare.py b/services/connectors/app/connectors/cloudflare.py
index 637a83b36..08c97aa45 100644
--- a/services/connectors/app/connectors/cloudflare.py
+++ b/services/connectors/app/connectors/cloudflare.py
@@ -56,19 +56,13 @@ class CloudflareConnector(BaseConnector):
"string",
"Account ID",
placeholder="abc123def456...",
- help_text=(
- "Found in the Cloudflare dashboard under any zone's "
- "Overview, lower-right pane (\"Account ID\")."
- ),
+ help_text=('Found in the Cloudflare dashboard under any zone\'s Overview, lower-right pane ("Account ID").'),
),
Field(
"api_token",
"secret",
"API Token",
- help_text=(
- "Account-scoped API token with the Audit Logs: Read "
- "permission. Avoid using the legacy Global API Key."
- ),
+ help_text=("Account-scoped API token with the Audit Logs: Read permission. Avoid using the legacy Global API Key."),
),
],
# Cloudflare doesn't have a meaningful OAuth flow for this API;
@@ -134,11 +128,7 @@ class CloudflareConnector(BaseConnector):
return {
"success": False,
"connector": self.connector_id,
- "error": (
- f"Token verified but audit_logs failed: "
- f"HTTP {audit_resp.status_code}: "
- f"{audit_resp.text[:200]}"
- ),
+ "error": (f"Token verified but audit_logs failed: HTTP {audit_resp.status_code}: {audit_resp.text[:200]}"),
}
return {
@@ -150,9 +140,7 @@ class CloudflareConnector(BaseConnector):
return {"success": False, "connector": self.connector_id, "error": str(exc)}
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
- since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%SZ"
- )
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
params = {
"since": since,
"per_page": _PER_PAGE,
diff --git a/services/connectors/app/connectors/elastic.py b/services/connectors/app/connectors/elastic.py
index 0d41ac0fa..b250d26f0 100644
--- a/services/connectors/app/connectors/elastic.py
+++ b/services/connectors/app/connectors/elastic.py
@@ -72,9 +72,7 @@ class ElasticConnector(BaseConnector):
index: str = "logs-*",
):
if not api_key and not (username and password):
- raise ValueError(
- "Elastic connector requires either api_key or username+password"
- )
+ raise ValueError("Elastic connector requires either api_key or username+password")
self._base_url = base_url.rstrip("/")
self._api_key = api_key
self._username = username
@@ -111,11 +109,7 @@ class ElasticConnector(BaseConnector):
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
# Elastic Security stores detection rule alerts in this hidden index pattern.
- esql = (
- f'FROM .alerts-security.alerts-* '
- f'| WHERE @timestamp > NOW() - {since_seconds} seconds '
- f'| LIMIT 100'
- )
+ esql = f"FROM .alerts-security.alerts-* | WHERE @timestamp > NOW() - {since_seconds} seconds | LIMIT 100"
async with httpx.AsyncClient(timeout=60.0, verify=False) as client:
resp = await client.post(
f"{self._base_url}/_query",
diff --git a/services/connectors/app/connectors/gcp_cloud_audit.py b/services/connectors/app/connectors/gcp_cloud_audit.py
index 0e69bd5c2..f20bbf9ce 100644
--- a/services/connectors/app/connectors/gcp_cloud_audit.py
+++ b/services/connectors/app/connectors/gcp_cloud_audit.py
@@ -79,19 +79,13 @@ class GCPCloudAuditConnector(BaseConnector):
"string",
"Project ID",
placeholder="my-prod-project",
- help_text=(
- "The GCP project to read audit logs from. Use a "
- "log-sink aggregator project if you've consolidated."
- ),
+ help_text=("The GCP project to read audit logs from. Use a log-sink aggregator project if you've consolidated."),
),
Field(
"service_account_json",
"secret",
"Service account JSON key",
- help_text=(
- "Paste the full JSON key file. It will be encrypted "
- "at rest by the credential vault."
- ),
+ help_text=("Paste the full JSON key file. It will be encrypted at rest by the credential vault."),
),
],
oauth=OAuthHints(
@@ -116,15 +110,10 @@ class GCPCloudAuditConnector(BaseConnector):
try:
sa = json.loads(blob)
except json.JSONDecodeError as exc:
- raise ValueError(
- "service_account_json is not valid JSON. Paste the entire "
- "key file contents."
- ) from exc
+ raise ValueError("service_account_json is not valid JSON. Paste the entire key file contents.") from exc
for required in ("client_email", "private_key", "token_uri"):
if required not in sa:
- raise ValueError(
- f"service_account_json missing required field: {required}"
- )
+ raise ValueError(f"service_account_json missing required field: {required}")
return sa
def _build_jwt(self) -> str:
@@ -140,9 +129,7 @@ class GCPCloudAuditConnector(BaseConnector):
"exp": now + 3600,
}
signing_input = (
- _b64url(json.dumps(header, separators=(",", ":")).encode())
- + "."
- + _b64url(json.dumps(claims, separators=(",", ":")).encode())
+ _b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + _b64url(json.dumps(claims, separators=(",", ":")).encode())
).encode("ascii")
private_key = serialization.load_pem_private_key(
@@ -217,9 +204,7 @@ class GCPCloudAuditConnector(BaseConnector):
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
await self._authenticate()
- since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%SZ"
- )
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
# Filter to the three Cloud Audit log streams. We exclude DataAccess
# by default because most projects emit it at huge volume; operators
diff --git a/services/connectors/app/connectors/gcp_scc.py b/services/connectors/app/connectors/gcp_scc.py
index af2315b0d..dad0aea8f 100644
--- a/services/connectors/app/connectors/gcp_scc.py
+++ b/services/connectors/app/connectors/gcp_scc.py
@@ -80,10 +80,7 @@ class GCPSCCConnector(BaseConnector):
"service_account_json",
"secret",
"Service account JSON key",
- help_text=(
- "Paste the full JSON key file. It will be encrypted "
- "at rest by the credential vault."
- ),
+ help_text=("Paste the full JSON key file. It will be encrypted at rest by the credential vault."),
),
],
oauth=OAuthHints(
@@ -107,15 +104,10 @@ class GCPSCCConnector(BaseConnector):
try:
sa = json.loads(blob)
except json.JSONDecodeError as exc:
- raise ValueError(
- "service_account_json is not valid JSON. Paste the entire "
- "key file contents."
- ) from exc
+ raise ValueError("service_account_json is not valid JSON. Paste the entire key file contents.") from exc
for required in ("client_email", "private_key", "token_uri"):
if required not in sa:
- raise ValueError(
- f"service_account_json missing required field: {required}"
- )
+ raise ValueError(f"service_account_json missing required field: {required}")
return sa
def _build_jwt(self) -> str:
@@ -129,9 +121,7 @@ class GCPSCCConnector(BaseConnector):
"exp": now + 3600,
}
signing_input = (
- _b64url(json.dumps(header, separators=(",", ":")).encode())
- + "."
- + _b64url(json.dumps(claims, separators=(",", ":")).encode())
+ _b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + _b64url(json.dumps(claims, separators=(",", ":")).encode())
).encode("ascii")
private_key = serialization.load_pem_private_key(
@@ -199,18 +189,13 @@ class GCPSCCConnector(BaseConnector):
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
await self._authenticate()
- since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%SZ"
- )
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
# ``-`` as the source ID means "across all sources" — the standard
# way to enumerate findings in an org without iterating sources.
# We filter on ``eventTime`` so we get net-new findings since the
# last poll, and exclude already-resolved findings.
- scc_filter = (
- f'state="ACTIVE" '
- f'AND eventTime >= "{since}"'
- )
+ scc_filter = f'state="ACTIVE" AND eventTime >= "{since}"'
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.get(
@@ -261,11 +246,7 @@ class GCPSCCConnector(BaseConnector):
"source": self.connector_id,
"external_id": finding.get("name", ""),
"title": finding.get("category", "GCP SCC Finding"),
- "description": (
- finding.get("description")
- or finding.get("category", "")
- or "GCP Security Command Center finding"
- ),
+ "description": (finding.get("description") or finding.get("category", "") or "GCP Security Command Center finding"),
"severity": severity,
"actor": (finding.get("access", {}) or {}).get("principalEmail"),
"actor_email": (finding.get("access", {}) or {}).get("principalEmail"),
diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.py
index 2a490dccb..7f38db5ef 100644
--- a/services/connectors/app/connectors/github.py
+++ b/services/connectors/app/connectors/github.py
@@ -128,11 +128,7 @@ class GitHubConnector(BaseConnector):
return {
"success": False,
"connector": self.connector_id,
- "error": (
- f"Org reachable but audit-log probe failed: "
- f"HTTP {audit_resp.status_code}: "
- f"{audit_resp.text[:200]}"
- ),
+ "error": (f"Org reachable but audit-log probe failed: HTTP {audit_resp.status_code}: {audit_resp.text[:200]}"),
}
audit_available = audit_resp.status_code == 200
@@ -205,9 +201,7 @@ class GitHubConnector(BaseConnector):
created_at = alert.get("created_at")
if created_at:
try:
- created_dt = datetime.fromisoformat(
- created_at.replace("Z", "+00:00")
- )
+ created_dt = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
if created_dt.timestamp() * 1000 < start_ms:
# Sorted desc → first too-old result means
# all subsequent ones are also too old.
@@ -292,12 +286,7 @@ class GitHubConnector(BaseConnector):
"source": self.connector_id,
"external_id": str(raw.get("_document_id") or raw.get("@timestamp") or ""),
"title": action or "GitHub audit event",
- "description": (
- f"actor={actor}; "
- f"action={action}; "
- f"repo={raw.get('repo', '')}; "
- f"org={raw.get('org', self._org)}"
- ),
+ "description": (f"actor={actor}; action={action}; repo={raw.get('repo', '')}; org={raw.get('org', self._org)}"),
"severity": severity,
"actor": actor,
"actor_email": raw.get("user_email"),
diff --git a/services/connectors/app/connectors/google_workspace.py b/services/connectors/app/connectors/google_workspace.py
index 3d4ddb0be..70b12ee25 100644
--- a/services/connectors/app/connectors/google_workspace.py
+++ b/services/connectors/app/connectors/google_workspace.py
@@ -85,10 +85,7 @@ class GoogleWorkspaceConnector(BaseConnector):
"service_account_json",
"secret",
"Service account JSON key",
- help_text=(
- "Paste the full JSON key file. Encrypted at rest by "
- "the credential vault."
- ),
+ help_text=("Paste the full JSON key file. Encrypted at rest by the credential vault."),
),
],
oauth=OAuthHints(
@@ -112,15 +109,10 @@ class GoogleWorkspaceConnector(BaseConnector):
try:
sa = json.loads(blob)
except json.JSONDecodeError as exc:
- raise ValueError(
- "service_account_json is not valid JSON. Paste the entire "
- "key file contents."
- ) from exc
+ raise ValueError("service_account_json is not valid JSON. Paste the entire key file contents.") from exc
for required in ("client_email", "private_key", "token_uri"):
if required not in sa:
- raise ValueError(
- f"service_account_json missing required field: {required}"
- )
+ raise ValueError(f"service_account_json missing required field: {required}")
return sa
def _build_jwt(self) -> str:
@@ -139,9 +131,7 @@ class GoogleWorkspaceConnector(BaseConnector):
"sub": self._admin_email,
}
signing_input = (
- _b64url(json.dumps(header, separators=(",", ":")).encode())
- + "."
- + _b64url(json.dumps(claims, separators=(",", ":")).encode())
+ _b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + _b64url(json.dumps(claims, separators=(",", ":")).encode())
).encode("ascii")
private_key = serialization.load_pem_private_key(
self._sa_info["private_key"].encode("utf-8"),
@@ -209,9 +199,7 @@ class GoogleWorkspaceConnector(BaseConnector):
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
await self._authenticate()
- start_time = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
- "%Y-%m-%dT%H:%M:%S.000Z"
- )
+ start_time = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
events: list[dict[str, Any]] = []
async with httpx.AsyncClient(timeout=30.0) as client:
@@ -289,9 +277,7 @@ class GoogleWorkspaceConnector(BaseConnector):
)
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
- application = raw.get("_aisoc_application") or raw.get("id", {}).get(
- "applicationName"
- )
+ application = raw.get("_aisoc_application") or raw.get("id", {}).get("applicationName")
actor = (raw.get("actor") or {}).get("email", "unknown")
# The Reports API encodes individual events as a list under each
# activity. Most activities have a single event; a few bundle
@@ -325,21 +311,13 @@ class GoogleWorkspaceConnector(BaseConnector):
"source": self.connector_id,
"external_id": (raw.get("id") or {}).get("uniqueQualifier", ""),
"title": event_name or f"Workspace {application} event",
- "description": (
- f"application={application}; "
- f"event={event_name}; "
- f"actor={actor}"
- ),
+ "description": (f"application={application}; event={event_name}; actor={actor}"),
"severity": severity,
"actor": actor,
"actor_email": actor if "@" in actor else None,
"src_ip": ip_address,
"application": application,
- "event_type": (
- f"workspace.{application}.{event_name}".lower()
- if application and event_name
- else "workspace.audit"
- ),
+ "event_type": (f"workspace.{application}.{event_name}".lower() if application and event_name else "workspace.audit"),
"raw_event": raw,
"created_at": (raw.get("id") or {}).get("time"),
}
diff --git a/services/connectors/app/connectors/m365_audit.py b/services/connectors/app/connectors/m365_audit.py
index 267d0b23a..fbe70650d 100644
--- a/services/connectors/app/connectors/m365_audit.py
+++ b/services/connectors/app/connectors/m365_audit.py
@@ -141,9 +141,7 @@ class M365AuditConnector(BaseConnector):
"success": True,
"connector": self.connector_id,
"tenant_id": self._tenant_id,
- "active_subscriptions": [
- s.get("contentType") for s in resp.json() if s.get("status") == "enabled"
- ],
+ "active_subscriptions": [s.get("contentType") for s in resp.json() if s.get("status") == "enabled"],
}
except httpx.HTTPStatusError as exc:
return {
@@ -312,21 +310,13 @@ class M365AuditConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("Id", ""),
"title": operation or f"M365 {workload} event",
- "description": (
- f"workload={workload}; "
- f"operation={operation}; "
- f"result={result_status or 'success'}"
- ),
+ "description": (f"workload={workload}; operation={operation}; result={result_status or 'success'}"),
"severity": severity,
"actor": actor,
"actor_email": actor if "@" in actor else None,
"src_ip": raw.get("ClientIP"),
"workload": workload,
- "event_type": (
- f"m365.{workload.lower()}.{operation.replace(' ', '').lower()}"
- if workload and operation
- else "m365.audit"
- ),
+ "event_type": (f"m365.{workload.lower()}.{operation.replace(' ', '').lower()}" if workload and operation else "m365.audit"),
"raw_event": raw,
"created_at": raw.get("CreationTime"),
}
diff --git a/services/connectors/app/connectors/tailscale.py b/services/connectors/app/connectors/tailscale.py
index 7f9f2f431..662a7ddf8 100644
--- a/services/connectors/app/connectors/tailscale.py
+++ b/services/connectors/app/connectors/tailscale.py
@@ -136,8 +136,7 @@ class TailscaleConnector(BaseConnector):
"API Key (optional if using OAuth)",
required=False,
help_text=(
- "Tailscale API key (starts with 'tskey-api-'). "
- "Use either this *or* the OAuth client credentials below — not both."
+ "Tailscale API key (starts with 'tskey-api-'). Use either this *or* the OAuth client credentials below — not both."
),
),
Field(
@@ -145,20 +144,14 @@ class TailscaleConnector(BaseConnector):
"string",
"OAuth Client ID (optional)",
required=False,
- help_text=(
- "OAuth 2.0 client ID from the Tailscale admin console. "
- "Required scope: 'audit:read'."
- ),
+ help_text=("OAuth 2.0 client ID from the Tailscale admin console. Required scope: 'audit:read'."),
),
Field(
"client_secret",
"secret",
"OAuth Client Secret (optional)",
required=False,
- help_text=(
- "OAuth 2.0 client secret. "
- "Only needed when using client-credential flow instead of an API key."
- ),
+ help_text=("OAuth 2.0 client secret. Only needed when using client-credential flow instead of an API key."),
),
],
oauth=OAuthHints(
@@ -210,10 +203,7 @@ class TailscaleConnector(BaseConnector):
self._oauth_expires_at = time.time() + int(payload.get("expires_in", 3600))
return self._oauth_token # type: ignore[return-value]
- raise ValueError(
- "TailscaleConnector: provide either 'api_key' or "
- "both 'client_id' and 'client_secret'."
- )
+ raise ValueError("TailscaleConnector: provide either 'api_key' or both 'client_id' and 'client_secret'.")
async def _auth_header(self) -> dict[str, str]:
token = await self._ensure_token()
@@ -296,12 +286,7 @@ class TailscaleConnector(BaseConnector):
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
action: str = raw.get("action") or raw.get("type") or ""
- actor: str = (
- raw.get("actor", {}).get("loginName")
- or raw.get("actor", {}).get("id")
- or raw.get("user")
- or "unknown"
- )
+ actor: str = raw.get("actor", {}).get("loginName") or raw.get("actor", {}).get("id") or raw.get("user") or "unknown"
if action in _HIGH_SEVERITY_ACTIONS:
severity = "high"
diff --git a/services/connectors/app/db/engine.py b/services/connectors/app/db/engine.py
index 1eeaff093..e2c2b71f3 100644
--- a/services/connectors/app/db/engine.py
+++ b/services/connectors/app/db/engine.py
@@ -33,13 +33,11 @@ def _resolve_database_url() -> str:
"""
url = os.getenv("DATABASE_URL")
if not url:
- raise RuntimeError(
- "DATABASE_URL is not set; the connectors service requires it to read the connectors table."
- )
+ raise RuntimeError("DATABASE_URL is not set; the connectors service requires it to read the connectors table.")
if url.startswith("postgresql://"):
- url = "postgresql+asyncpg://" + url[len("postgresql://"):]
+ url = "postgresql+asyncpg://" + url[len("postgresql://") :]
elif url.startswith("postgres://"):
- url = "postgresql+asyncpg://" + url[len("postgres://"):]
+ url = "postgresql+asyncpg://" + url[len("postgres://") :]
return url
diff --git a/services/connectors/app/federated/query.py b/services/connectors/app/federated/query.py
index f964f9d84..023e6b5cb 100644
--- a/services/connectors/app/federated/query.py
+++ b/services/connectors/app/federated/query.py
@@ -31,16 +31,16 @@ from typing import Any, Literal
# Operator vocabulary kept deliberately narrow. Adding a new operator
# means updating every translator, so we keep the surface tight.
Operator = Literal[
- "eq", # field == value
- "ne", # field != value
- "contains", # substring match (case-insensitive when the backend supports it)
- "starts_with", # prefix match
- "ends_with", # suffix match
- "gt", # field > value (numeric / timestamp)
- "gte", # field >= value
- "lt", # field < value
- "lte", # field <= value
- "in", # field is one of [...]
+ "eq", # field == value
+ "ne", # field != value
+ "contains", # substring match (case-insensitive when the backend supports it)
+ "starts_with", # prefix match
+ "ends_with", # suffix match
+ "gt", # field > value (numeric / timestamp)
+ "gte", # field >= value
+ "lt", # field < value
+ "lte", # field <= value
+ "in", # field is one of [...]
]
_VALID_OPERATORS: frozenset[str] = frozenset(
@@ -79,9 +79,7 @@ class Indicator:
if not isinstance(self.field, str) or not self.field.strip():
raise QueryError("indicator.field must be a non-empty string")
if self.operator not in _VALID_OPERATORS:
- raise QueryError(
- f"indicator.operator '{self.operator}' is not one of {sorted(_VALID_OPERATORS)}"
- )
+ raise QueryError(f"indicator.operator '{self.operator}' is not one of {sorted(_VALID_OPERATORS)}")
if self.operator == "in":
if not isinstance(self.value, (list, tuple)) or not self.value:
raise QueryError("indicator with operator='in' requires a non-empty list value")
@@ -124,10 +122,7 @@ class UnifiedQuery:
def to_dict(self) -> dict[str, Any]:
return {
"free_text": self.free_text,
- "indicators": [
- {"field": i.field, "operator": i.operator, "value": i.value}
- for i in self.indicators
- ],
+ "indicators": [{"field": i.field, "operator": i.operator, "value": i.value} for i in self.indicators],
"since_seconds": self.since_seconds,
"limit": self.limit,
}
diff --git a/services/connectors/app/ingest_client.py b/services/connectors/app/ingest_client.py
index 44826d765..00c2ba5c3 100644
--- a/services/connectors/app/ingest_client.py
+++ b/services/connectors/app/ingest_client.py
@@ -116,18 +116,14 @@ class IngestClient:
try:
resp = await client.post(url, headers=headers, json=payload)
except httpx.HTTPError as exc:
- raise IngestClientError(
- f"ingest service unreachable at {url}: {exc}"
- ) from exc
+ raise IngestClientError(f"ingest service unreachable at {url}: {exc}") from exc
if resp.status_code >= 400:
# Pull the body so logs show *why* — typically a missing tenant
# header or oversized batch, both of which we want surfaced
# rather than swallowed.
body_preview = resp.text[:500]
- raise IngestClientError(
- f"ingest service returned {resp.status_code} for connector {connector_id}: {body_preview}"
- )
+ raise IngestClientError(f"ingest service returned {resp.status_code} for connector {connector_id}: {body_preview}")
try:
data = resp.json()
diff --git a/services/connectors/app/main.py b/services/connectors/app/main.py
index e97c1444f..f1d1fee31 100644
--- a/services/connectors/app/main.py
+++ b/services/connectors/app/main.py
@@ -36,10 +36,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Start/stop the scheduler alongside the HTTP server."""
scheduler: ConnectorScheduler | None = None
if scheduler_disabled():
- logger.info(
- "connector.scheduler.disabled "
- "AISOC_CONNECTORS_DISABLE_SCHEDULER set; HTTP only mode"
- )
+ logger.info("connector.scheduler.disabled AISOC_CONNECTORS_DISABLE_SCHEDULER set; HTTP only mode")
else:
try:
scheduler = ConnectorScheduler()
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 266e774ea..1e65b1b71 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -308,9 +308,7 @@ class ConnectorScheduler:
)
return
- target: ConnectorInstance | None = next(
- (i for i in instances if i.id == connector_id), None
- )
+ target: ConnectorInstance | None = next((i for i in instances if i.id == connector_id), None)
if target is None:
# Instance was deleted / disabled between reload and poll.
# Reload will clean up the job on its next tick.
@@ -350,11 +348,7 @@ class ConnectorScheduler:
# Filter out the scheduler-only knobs from connector_config before
# passing to the constructor — connectors don't accept
# ``poll_interval_seconds`` as a kwarg.
- runtime_config = {
- k: v
- for k, v in (target.connector_config or {}).items()
- if k not in {"poll_interval_seconds"}
- }
+ runtime_config = {k: v for k, v in (target.connector_config or {}).items() if k not in {"poll_interval_seconds"}}
kwargs = {**auth, **runtime_config}
started = datetime.now(UTC)
diff --git a/services/connectors/app/security/credential_vault.py b/services/connectors/app/security/credential_vault.py
index c6f7b2f98..0d05133be 100644
--- a/services/connectors/app/security/credential_vault.py
+++ b/services/connectors/app/security/credential_vault.py
@@ -87,7 +87,7 @@ class CredentialVault:
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
if not value.startswith(_CIPHER_PREFIX):
return value
- token = value[len(_CIPHER_PREFIX):].encode("ascii")
+ token = value[len(_CIPHER_PREFIX) :].encode("ascii")
try:
return self._fernet.decrypt(token).decode("utf-8")
except InvalidToken as exc:
diff --git a/services/connectors/tests/test_azure_connectors.py b/services/connectors/tests/test_azure_connectors.py
index f15509a2c..34d6899bd 100644
--- a/services/connectors/tests/test_azure_connectors.py
+++ b/services/connectors/tests/test_azure_connectors.py
@@ -44,8 +44,7 @@ def test_azure_activity_schema_includes_subscription_field():
schema = AzureActivityConnector.schema()
field_names = {f.name for f in schema.fields}
assert "subscription_id" in field_names, (
- "azure_activity must collect a subscription_id; without it the polling "
- "loop has no scope to query"
+ "azure_activity must collect a subscription_id; without it the polling loop has no scope to query"
)
assert {"tenant_id", "client_id", "client_secret"} <= field_names
assert schema.category == "cloud"
@@ -123,9 +122,7 @@ def test_azure_activity_normalize_role_assignment_write_is_high():
"eventTimestamp": "2026-01-01T00:00:00Z",
}
out = connector.normalize(raw)
- assert out["severity"] == "high", (
- "writing role assignments is a high-blast-radius operation"
- )
+ assert out["severity"] == "high", "writing role assignments is a high-blast-radius operation"
assert out["external_id"] == "act-1"
assert out["actor"] == "[email protected]"
assert out["actor_email"] == "[email protected]"
@@ -209,9 +206,7 @@ async def test_azure_entra_test_connection_success():
return_value=httpx.Response(200, json={"access_token": "abc"})
)
respx.get("https://graph.microsoft.com/v1.0/organization").mock(
- return_value=httpx.Response(
- 200, json={"value": [{"id": "org-1", "displayName": "Acme Corp"}]}
- )
+ return_value=httpx.Response(200, json={"value": [{"id": "org-1", "displayName": "Acme Corp"}]})
)
connector = AzureEntraConnector(_TENANT, _CLIENT, _SECRET)
@@ -256,9 +251,7 @@ async def test_azure_entra_fetch_alerts_returns_normalized_events():
},
)
)
- respx.get("https://graph.microsoft.com/v1.0/auditLogs/signIns").mock(
- return_value=httpx.Response(200, json={"value": []})
- )
+ respx.get("https://graph.microsoft.com/v1.0/auditLogs/signIns").mock(return_value=httpx.Response(200, json={"value": []}))
connector = AzureEntraConnector(_TENANT, _CLIENT, _SECRET)
events = await connector.fetch_alerts(since_seconds=300)
@@ -274,9 +267,7 @@ async def test_azure_activity_test_connection_success():
return_value=httpx.Response(200, json={"access_token": "abc"})
)
respx.get(f"https://management.azure.com/subscriptions/{_SUB}").mock(
- return_value=httpx.Response(
- 200, json={"id": f"/subscriptions/{_SUB}", "displayName": "Production"}
- )
+ return_value=httpx.Response(200, json={"id": f"/subscriptions/{_SUB}", "displayName": "Production"})
)
connector = AzureActivityConnector(_TENANT, _CLIENT, _SECRET, _SUB)
@@ -291,13 +282,8 @@ async def test_azure_activity_fetch_alerts_handles_empty_response():
respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
return_value=httpx.Response(200, json={"access_token": "abc"})
)
- activity_url = (
- f"https://management.azure.com/subscriptions/{_SUB}"
- "/providers/Microsoft.Insights/eventtypes/management/values"
- )
- respx.get(activity_url).mock(
- return_value=httpx.Response(200, json={"value": []})
- )
+ activity_url = f"https://management.azure.com/subscriptions/{_SUB}/providers/Microsoft.Insights/eventtypes/management/values"
+ respx.get(activity_url).mock(return_value=httpx.Response(200, json={"value": []}))
connector = AzureActivityConnector(_TENANT, _CLIENT, _SECRET, _SUB)
events = await connector.fetch_alerts(since_seconds=600)
@@ -310,9 +296,7 @@ async def test_azure_defender_test_connection_handles_failure():
respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
return_value=httpx.Response(200, json={"access_token": "abc"})
)
- respx.get("https://graph.microsoft.com/v1.0/security/alerts_v2").mock(
- return_value=httpx.Response(403, text="insufficient_privileges")
- )
+ respx.get("https://graph.microsoft.com/v1.0/security/alerts_v2").mock(return_value=httpx.Response(403, text="insufficient_privileges"))
connector = AzureDefenderConnector(_TENANT, _CLIENT, _SECRET)
result = await connector.test_connection()
diff --git a/services/connectors/tests/test_federated.py b/services/connectors/tests/test_federated.py
index 55c14529b..fa93ae72f 100644
--- a/services/connectors/tests/test_federated.py
+++ b/services/connectors/tests/test_federated.py
@@ -153,9 +153,7 @@ def test_federated_capable_connectors_are_registered_and_advertised():
for connector_id in ("splunk", "microsoft_sentinel", "elastic"):
cls = CONNECTOR_REGISTRY.get(connector_id)
assert cls is not None, f"connector '{connector_id}' missing from registry"
- assert getattr(cls, "supports_federated_search", False), (
- f"connector '{connector_id}' must opt into federated search"
- )
+ assert getattr(cls, "supports_federated_search", False), f"connector '{connector_id}' must opt into federated search"
def test_elastic_connector_flattens_esql_columns_and_values():
@@ -304,9 +302,7 @@ async def test_sentinel_query_assembles_loganalytics_call(monkeypatch):
connector._access_token = "fake-bearer" # noqa: SLF001
rows = await connector.query(_SAMPLE_QUERY)
- assert rows == [
- {"TimeGenerated": "2026-05-05T00:00:00Z", "UserPrincipalName": "[email protected]"}
- ]
+ assert rows == [{"TimeGenerated": "2026-05-05T00:00:00Z", "UserPrincipalName": "[email protected]"}]
# Log Analytics API path; workspace id must appear in the URL.
assert "loganalytics" in captured["url"].lower()
assert "workspace-uuid" in captured["url"]
diff --git a/services/connectors/tests/test_gcp_connectors.py b/services/connectors/tests/test_gcp_connectors.py
index 411d25113..9376737b6 100644
--- a/services/connectors/tests/test_gcp_connectors.py
+++ b/services/connectors/tests/test_gcp_connectors.py
@@ -145,9 +145,7 @@ def test_cloud_audit_normalize_failed_op_bumps_to_medium(fake_sa_json):
"resource": {"type": "gce_instance"},
}
out = connector.normalize(raw)
- assert out["severity"] == "medium", (
- "failed control-plane operations should escalate above info"
- )
+ assert out["severity"] == "medium", "failed control-plane operations should escalate above info"
def test_cloud_audit_normalize_routine_read_is_info(fake_sa_json):
@@ -209,10 +207,7 @@ def test_scc_normalize_critical_collapses_to_high(fake_sa_json):
}
out = connector.normalize(raw)
assert out["source"] == "gcp_scc"
- assert out["severity"] == "high", (
- "SCC CRITICAL collapses to AiSOC 'high' since downstream pipelines "
- "expect that vocabulary"
- )
+ assert out["severity"] == "high", "SCC CRITICAL collapses to AiSOC 'high' since downstream pipelines expect that vocabulary"
assert out["title"] == "MALWARE_BAD_DOMAIN"
assert out["actor_email"] == "[email protected]"
assert out["resource_type"] == "google.compute.Instance"
@@ -253,13 +248,9 @@ def test_scc_normalize_unknown_severity_falls_back_to_info(fake_sa_json):
@respx.mock
async def test_cloud_audit_test_connection_success(fake_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
- )
- respx.post("https://logging.googleapis.com/v2/entries:list").mock(
- return_value=httpx.Response(200, json={"entries": []})
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
+ respx.post("https://logging.googleapis.com/v2/entries:list").mock(return_value=httpx.Response(200, json={"entries": []}))
connector = GCPCloudAuditConnector(_PROJECT, fake_sa_json)
result = await connector.test_connection()
@@ -272,9 +263,7 @@ async def test_cloud_audit_test_connection_success(fake_sa_json):
@respx.mock
async def test_cloud_audit_test_connection_surfaces_403(fake_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
respx.post("https://logging.googleapis.com/v2/entries:list").mock(
return_value=httpx.Response(403, text="caller does not have permission")
@@ -290,9 +279,7 @@ async def test_cloud_audit_test_connection_surfaces_403(fake_sa_json):
@respx.mock
async def test_cloud_audit_fetch_alerts_returns_normalized_events(fake_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
respx.post("https://logging.googleapis.com/v2/entries:list").mock(
return_value=httpx.Response(
@@ -306,9 +293,7 @@ async def test_cloud_audit_fetch_alerts_returns_normalized_events(fake_sa_json):
"protoPayload": {
"methodName": "SetIamPolicy",
"serviceName": "cloudresourcemanager.googleapis.com",
- "authenticationInfo": {
- "principalEmail": "[email protected]"
- },
+ "authenticationInfo": {"principalEmail": "[email protected]"},
"status": {},
},
"resource": {"type": "project"},
@@ -330,13 +315,9 @@ async def test_cloud_audit_fetch_alerts_returns_normalized_events(fake_sa_json):
@respx.mock
async def test_cloud_audit_fetch_alerts_returns_empty_on_500(fake_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
- )
- respx.post("https://logging.googleapis.com/v2/entries:list").mock(
- return_value=httpx.Response(500, text="internal")
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
+ respx.post("https://logging.googleapis.com/v2/entries:list").mock(return_value=httpx.Response(500, text="internal"))
connector = GCPCloudAuditConnector(_PROJECT, fake_sa_json)
events = await connector.fetch_alerts(since_seconds=300)
@@ -347,13 +328,11 @@ async def test_cloud_audit_fetch_alerts_returns_empty_on_500(fake_sa_json):
@respx.mock
async def test_scc_test_connection_success(fake_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
+ )
+ respx.get(f"https://securitycenter.googleapis.com/v1/organizations/{_ORG}/sources").mock(
+ return_value=httpx.Response(200, json={"sources": []})
)
- respx.get(
- f"https://securitycenter.googleapis.com/v1/organizations/{_ORG}/sources"
- ).mock(return_value=httpx.Response(200, json={"sources": []}))
connector = GCPSCCConnector(_ORG, fake_sa_json)
result = await connector.test_connection()
@@ -365,13 +344,9 @@ async def test_scc_test_connection_success(fake_sa_json):
@respx.mock
async def test_scc_fetch_alerts_returns_normalized_findings(fake_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
- respx.get(
- f"https://securitycenter.googleapis.com/v1/organizations/{_ORG}/sources/-/findings"
- ).mock(
+ respx.get(f"https://securitycenter.googleapis.com/v1/organizations/{_ORG}/sources/-/findings").mock(
return_value=httpx.Response(
200,
json={
diff --git a/services/connectors/tests/test_saas_connectors.py b/services/connectors/tests/test_saas_connectors.py
index e05fc0a30..edee45ed9 100644
--- a/services/connectors/tests/test_saas_connectors.py
+++ b/services/connectors/tests/test_saas_connectors.py
@@ -171,12 +171,10 @@ def test_m365_normalize_routine_user_op_is_info():
@pytest.mark.asyncio
@respx.mock
async def test_m365_test_connection_success():
- respx.post(
- f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token"
- ).mock(return_value=httpx.Response(200, json={"access_token": "tok-abc"}))
- respx.get(
- f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/list"
- ).mock(
+ respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "tok-abc"})
+ )
+ respx.get(f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/list").mock(
return_value=httpx.Response(
200,
json=[
@@ -197,12 +195,10 @@ async def test_m365_test_connection_success():
@pytest.mark.asyncio
@respx.mock
async def test_m365_test_connection_surfaces_403():
- respx.post(
- f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token"
- ).mock(return_value=httpx.Response(200, json={"access_token": "tok-abc"}))
- respx.get(
- f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/list"
- ).mock(
+ respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "tok-abc"})
+ )
+ respx.get(f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/list").mock(
return_value=httpx.Response(403, text="ActivityFeed.Read not granted")
)
@@ -218,22 +214,20 @@ async def test_m365_fetch_alerts_pulls_blob_content():
# The Activity API is a two-step flow: list content blobs, then GET each
# blob URI. We mock both layers and assert the connector materializes
# the inner events through normalize().
- respx.post(
- f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token"
- ).mock(return_value=httpx.Response(200, json={"access_token": "tok-abc"}))
+ respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
+ return_value=httpx.Response(200, json={"access_token": "tok-abc"})
+ )
# Idempotent subscribe on every content type — return 200 OK.
- respx.post(
- f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/start"
- ).mock(return_value=httpx.Response(200, json={"contentType": "ok"}))
+ respx.post(f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/start").mock(
+ return_value=httpx.Response(200, json={"contentType": "ok"})
+ )
blob_uri = "https://manage.office.com/api/v1.0/blob/abc"
# Only the AzureActiveDirectory listing returns a blob; the rest are
# empty so we can assert filtering plus de-duplication of empty content
# types in a single test.
- aad_url = (
- f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/content"
- )
+ aad_url = f"https://manage.office.com/api/v1.0/{_TENANT}/activity/feed/subscriptions/content"
def list_handler(request: httpx.Request) -> httpx.Response:
if request.url.params.get("contentType") == "Audit.AzureActiveDirectory":
@@ -363,13 +357,11 @@ def test_workspace_normalize_routine_event_is_info(fake_workspace_sa_json):
@respx.mock
async def test_workspace_test_connection_success(fake_workspace_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
+ )
+ respx.get("https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login").mock(
+ return_value=httpx.Response(200, json={"items": []})
)
- respx.get(
- "https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login"
- ).mock(return_value=httpx.Response(200, json={"items": []}))
connector = GoogleWorkspaceConnector(_ADMIN_EMAIL, fake_workspace_sa_json)
result = await connector.test_connection()
@@ -382,16 +374,10 @@ async def test_workspace_test_connection_success(fake_workspace_sa_json):
@respx.mock
async def test_workspace_test_connection_surfaces_403(fake_workspace_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
- respx.get(
- "https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login"
- ).mock(
- return_value=httpx.Response(
- 403, text="The user is not authorized to access this resource"
- )
+ respx.get("https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login").mock(
+ return_value=httpx.Response(403, text="The user is not authorized to access this resource")
)
connector = GoogleWorkspaceConnector(_ADMIN_EMAIL, fake_workspace_sa_json)
@@ -404,9 +390,7 @@ async def test_workspace_test_connection_surfaces_403(fake_workspace_sa_json):
@respx.mock
async def test_workspace_fetch_alerts_iterates_apps(fake_workspace_sa_json):
respx.post("https://oauth2.googleapis.com/token").mock(
- return_value=httpx.Response(
- 200, json={"access_token": "tok-abc", "expires_in": 3600}
- )
+ return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
# Each ApplicationName has its own URL. We return one event for
@@ -427,9 +411,9 @@ async def test_workspace_fetch_alerts_iterates_apps(fake_workspace_sa_json):
app = request.url.path.rsplit("/", 1)[-1]
return httpx.Response(200, json={"items": apps_with_data.get(app, [])})
- respx.get(
- url__regex=r"^https://admin\.googleapis\.com/admin/reports/v1/activity/users/all/applications/.*"
- ).mock(side_effect=app_handler)
+ respx.get(url__regex=r"^https://admin\.googleapis\.com/admin/reports/v1/activity/users/all/applications/.*").mock(
+ side_effect=app_handler
+ )
connector = GoogleWorkspaceConnector(_ADMIN_EMAIL, fake_workspace_sa_json)
events = await connector.fetch_alerts(since_seconds=300)
@@ -521,9 +505,9 @@ async def test_cloudflare_test_connection_success():
respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").mock(
return_value=httpx.Response(200, json={"result": {"status": "active"}})
)
- respx.get(
- f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs"
- ).mock(return_value=httpx.Response(200, json={"result": []}))
+ respx.get(f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs").mock(
+ return_value=httpx.Response(200, json={"result": []})
+ )
connector = CloudflareConnector(_ACCOUNT_ID, "cf-token")
result = await connector.test_connection()
@@ -550,9 +534,9 @@ async def test_cloudflare_test_connection_missing_audit_perm_fails():
respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").mock(
return_value=httpx.Response(200, json={"result": {"status": "active"}})
)
- respx.get(
- f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs"
- ).mock(return_value=httpx.Response(403, text="missing scope"))
+ respx.get(f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs").mock(
+ return_value=httpx.Response(403, text="missing scope")
+ )
connector = CloudflareConnector(_ACCOUNT_ID, "cf-token")
result = await connector.test_connection()
@@ -563,9 +547,7 @@ async def test_cloudflare_test_connection_missing_audit_perm_fails():
@pytest.mark.asyncio
@respx.mock
async def test_cloudflare_fetch_alerts_returns_normalized_events():
- respx.get(
- f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs"
- ).mock(
+ respx.get(f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs").mock(
return_value=httpx.Response(
200,
json={
@@ -596,9 +578,9 @@ async def test_cloudflare_fetch_alerts_returns_normalized_events():
@pytest.mark.asyncio
@respx.mock
async def test_cloudflare_fetch_alerts_returns_empty_on_500():
- respx.get(
- f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs"
- ).mock(return_value=httpx.Response(500, text="bad gateway"))
+ respx.get(f"https://api.cloudflare.com/client/v4/accounts/{_ACCOUNT_ID}/audit_logs").mock(
+ return_value=httpx.Response(500, text="bad gateway")
+ )
connector = CloudflareConnector(_ACCOUNT_ID, "cf-token")
events = await connector.fetch_alerts(since_seconds=300)
@@ -746,12 +728,8 @@ def test_github_normalize_code_scanning_unknown_severity_falls_back_to_info():
@pytest.mark.asyncio
@respx.mock
async def test_github_test_connection_success_with_audit_log():
- respx.get(f"https://api.github.com/orgs/{_ORG}").mock(
- return_value=httpx.Response(200, json={"login": _ORG})
- )
- respx.get(f"https://api.github.com/orgs/{_ORG}/audit-log").mock(
- return_value=httpx.Response(200, json=[])
- )
+ respx.get(f"https://api.github.com/orgs/{_ORG}").mock(return_value=httpx.Response(200, json={"login": _ORG}))
+ respx.get(f"https://api.github.com/orgs/{_ORG}/audit-log").mock(return_value=httpx.Response(200, json=[]))
connector = GitHubConnector(_ORG, _TOKEN)
result = await connector.test_connection()
@@ -767,12 +745,8 @@ async def test_github_test_connection_succeeds_when_audit_log_404():
# That's a legitimate operational state — we still consider the
# connector "connected" but flag audit_log_available = False so the
# frontend can warn the operator.
- respx.get(f"https://api.github.com/orgs/{_ORG}").mock(
- return_value=httpx.Response(200, json={"login": _ORG})
- )
- respx.get(f"https://api.github.com/orgs/{_ORG}/audit-log").mock(
- return_value=httpx.Response(404, text="not found")
- )
+ respx.get(f"https://api.github.com/orgs/{_ORG}").mock(return_value=httpx.Response(200, json={"login": _ORG}))
+ respx.get(f"https://api.github.com/orgs/{_ORG}/audit-log").mock(return_value=httpx.Response(404, text="not found"))
connector = GitHubConnector(_ORG, _TOKEN)
result = await connector.test_connection()
@@ -783,9 +757,7 @@ async def test_github_test_connection_succeeds_when_audit_log_404():
@pytest.mark.asyncio
@respx.mock
async def test_github_test_connection_403_org_fails():
- respx.get(f"https://api.github.com/orgs/{_ORG}").mock(
- return_value=httpx.Response(403, text="bad token")
- )
+ respx.get(f"https://api.github.com/orgs/{_ORG}").mock(return_value=httpx.Response(403, text="bad token"))
connector = GitHubConnector(_ORG, _TOKEN)
result = await connector.test_connection()
@@ -839,9 +811,7 @@ async def test_github_fetch_alerts_merges_audit_and_code_scanning():
@respx.mock
async def test_github_fetch_alerts_handles_audit_log_unavailable():
# 404 on audit log shouldn't stop us from delivering code scanning.
- respx.get(f"https://api.github.com/orgs/{_ORG}/audit-log").mock(
- return_value=httpx.Response(404, text="not found")
- )
+ respx.get(f"https://api.github.com/orgs/{_ORG}/audit-log").mock(return_value=httpx.Response(404, text="not found"))
respx.get(f"https://api.github.com/orgs/{_ORG}/code-scanning/alerts").mock(
return_value=httpx.Response(
200,
diff --git a/services/connectors/tests/test_scheduler.py b/services/connectors/tests/test_scheduler.py
index 5fdaa99fd..31c1c4b4b 100644
--- a/services/connectors/tests/test_scheduler.py
+++ b/services/connectors/tests/test_scheduler.py
@@ -98,17 +98,13 @@ async def test_poll_one_happy_path(monkeypatch):
fake_vault = _FakeVault()
fake_ingest = _FakeIngestClient(accepted=1)
- scheduler = ConnectorScheduler(
- engine=fake_engine, ingest_client=fake_ingest, vault=fake_vault
- )
+ scheduler = ConnectorScheduler(engine=fake_engine, ingest_client=fake_ingest, vault=fake_vault)
# We don't call start() because we don't want APScheduler running for
# this test — _poll_one operates on the injected fakes directly.
await scheduler._poll_one(connector_id=inst.id)
- fake_connector_class.assert_called_once_with(
- client_id="id", client_secret="secret"
- )
+ fake_connector_class.assert_called_once_with(client_id="id", client_secret="secret")
fake_connector.fetch_alerts.assert_awaited_once_with(since_seconds=60)
assert fake_ingest.calls == 1
pushed = fake_ingest.last_payload
@@ -127,9 +123,7 @@ async def test_poll_one_unknown_connector_type(monkeypatch):
inst = _make_instance(connector_type="not_in_registry")
monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {})
- scheduler = ConnectorScheduler(
- engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=_FakeVault())
await scheduler._poll_one(connector_id=inst.id)
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
@@ -139,16 +133,12 @@ async def test_poll_one_unknown_connector_type(monkeypatch):
@pytest.mark.asyncio
async def test_poll_one_decrypt_failure(monkeypatch):
inst = _make_instance(connector_type="fake_connector")
- monkeypatch.setattr(
- "app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": MagicMock()}
- )
+ monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": MagicMock()})
bad_vault = _FakeVault()
bad_vault.fail = True
- scheduler = ConnectorScheduler(
- engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=bad_vault
- )
+ scheduler = ConnectorScheduler(engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=bad_vault)
await scheduler._poll_one(connector_id=inst.id)
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
@@ -165,13 +155,9 @@ async def test_poll_one_constructor_typeerror(monkeypatch):
def bad_ctor(**_kwargs: Any) -> Any:
raise TypeError("got unexpected keyword argument")
- monkeypatch.setattr(
- "app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": bad_ctor}
- )
+ monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": bad_ctor})
- scheduler = ConnectorScheduler(
- engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=_FakeVault())
await scheduler._poll_one(connector_id=inst.id)
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
@@ -188,9 +174,7 @@ async def test_poll_one_fetch_raises(monkeypatch):
{"fake_connector": MagicMock(return_value=fake_connector)},
)
- scheduler = ConnectorScheduler(
- engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=_FakeEngine([inst]), ingest_client=_FakeIngestClient(), vault=_FakeVault())
await scheduler._poll_one(connector_id=inst.id)
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
@@ -213,9 +197,7 @@ async def test_poll_one_ingest_raises(monkeypatch):
bad_ingest = _FakeIngestClient()
bad_ingest.exc = IngestClientError("ingest down")
- scheduler = ConnectorScheduler(
- engine=_FakeEngine([inst]), ingest_client=bad_ingest, vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=_FakeEngine([inst]), ingest_client=bad_ingest, vault=_FakeVault())
await scheduler._poll_one(connector_id=inst.id)
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
@@ -226,9 +208,7 @@ async def test_poll_one_ingest_raises(monkeypatch):
async def test_poll_one_instance_disappeared(monkeypatch):
"""If the connector row was deleted between reload and poll, we no-op."""
monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {})
- scheduler = ConnectorScheduler(
- engine=_FakeEngine([]), ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=_FakeEngine([]), ingest_client=_FakeIngestClient(), vault=_FakeVault())
await scheduler._poll_one(connector_id=uuid.uuid4())
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
@@ -247,9 +227,7 @@ async def test_reload_adds_and_drops_jobs(monkeypatch):
a = _make_instance()
b = _make_instance()
engine = _FakeEngine([a, b])
- scheduler = ConnectorScheduler(
- engine=engine, ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=engine, ingest_client=_FakeIngestClient(), vault=_FakeVault())
fake_aps = _FakeAPScheduler()
scheduler._scheduler = fake_aps
@@ -269,9 +247,7 @@ async def test_reload_skips_unchanged_jobs(monkeypatch):
monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {})
inst = _make_instance(connector_config={"poll_interval_seconds": 120})
engine = _FakeEngine([inst])
- scheduler = ConnectorScheduler(
- engine=engine, ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=engine, ingest_client=_FakeIngestClient(), vault=_FakeVault())
fake_aps = _FakeAPScheduler()
scheduler._scheduler = fake_aps
@@ -288,9 +264,7 @@ async def test_reload_reschedules_when_interval_changes(monkeypatch):
monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {})
inst = _make_instance(connector_config={"poll_interval_seconds": 120})
engine = _FakeEngine([inst])
- scheduler = ConnectorScheduler(
- engine=engine, ingest_client=_FakeIngestClient(), vault=_FakeVault()
- )
+ scheduler = ConnectorScheduler(engine=engine, ingest_client=_FakeIngestClient(), vault=_FakeVault())
fake_aps = _FakeAPScheduler()
scheduler._scheduler = fake_aps
diff --git a/services/connectors/tests/test_schemas.py b/services/connectors/tests/test_schemas.py
index d0ccb03d9..456a7a4c0 100644
--- a/services/connectors/tests/test_schemas.py
+++ b/services/connectors/tests/test_schemas.py
@@ -37,12 +37,9 @@ def test_registry_has_expected_baseline_connectors(registry):
def test_every_connector_returns_a_schema(registry):
for connector_id, cls in registry.items():
schema = cls.schema()
- assert isinstance(schema, ConnectorSchema), (
- f"{cls.__name__}.schema() must return ConnectorSchema, got {type(schema).__name__}"
- )
+ assert isinstance(schema, ConnectorSchema), f"{cls.__name__}.schema() must return ConnectorSchema, got {type(schema).__name__}"
assert schema.connector_id == connector_id, (
- f"{cls.__name__}.schema().connector_id ({schema.connector_id!r}) "
- f"does not match registry key ({connector_id!r})"
+ f"{cls.__name__}.schema().connector_id ({schema.connector_id!r}) does not match registry key ({connector_id!r})"
)
@@ -50,9 +47,7 @@ def test_schema_metadata_is_well_formed(registry):
for cls in registry.values():
schema = cls.schema()
assert schema.connector_name, f"{cls.__name__}: connector_name is empty"
- assert schema.category in ALLOWED_CATEGORIES, (
- f"{cls.__name__}: category {schema.category!r} not in {ALLOWED_CATEGORIES}"
- )
+ assert schema.category in ALLOWED_CATEGORIES, f"{cls.__name__}: category {schema.category!r} not in {ALLOWED_CATEGORIES}"
assert schema.description, f"{cls.__name__}: description is empty"
assert schema.fields, f"{cls.__name__}: at least one field is required"
@@ -64,18 +59,12 @@ def test_schema_fields_are_well_formed(registry):
for field in schema.fields:
assert isinstance(field, Field)
assert field.name, f"{cls.__name__}: field with empty name"
- assert field.name not in seen_names, (
- f"{cls.__name__}: duplicate field name {field.name!r}"
- )
+ assert field.name not in seen_names, f"{cls.__name__}: duplicate field name {field.name!r}"
seen_names.add(field.name)
assert field.label, f"{cls.__name__}.{field.name}: label is empty"
- assert field.type in ALLOWED_FIELD_TYPES, (
- f"{cls.__name__}.{field.name}: unknown field type {field.type!r}"
- )
+ assert field.type in ALLOWED_FIELD_TYPES, f"{cls.__name__}.{field.name}: unknown field type {field.type!r}"
if field.type == "select":
- assert field.options, (
- f"{cls.__name__}.{field.name}: select fields require options"
- )
+ assert field.options, f"{cls.__name__}.{field.name}: select fields require options"
def test_schemas_are_json_serialisable():
@@ -105,6 +94,5 @@ def test_secret_fields_are_marked_secret(registry):
for field in cls.schema().fields:
if any(s in field.name.lower() for s in suspicious):
assert field.type == "secret", (
- f"{cls.__name__}.{field.name}: looks like a credential but type is "
- f"{field.type!r}, expected 'secret'"
+ f"{cls.__name__}.{field.name}: looks like a credential but type is {field.type!r}, expected 'secret'"
)
diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.py
index 2db20dd8a..5ca33364e 100644
--- a/services/fusion/app/core/config.py
+++ b/services/fusion/app/core/config.py
@@ -37,9 +37,7 @@ class Settings(BaseSettings):
rba_enabled: bool = Field(default=True, alias="AISOC_FEATURE_RBA")
rba_promotion_threshold: float = Field(default=80.0, alias="RBA_PROMOTION_THRESHOLD")
rba_window_seconds: int = Field(default=86400, alias="RBA_WINDOW_SECONDS") # 24h decay window
- rba_decay_half_life_seconds: int = Field(
- default=14400, alias="RBA_DECAY_HALF_LIFE_SECONDS"
- ) # 4h half-life
+ rba_decay_half_life_seconds: int = Field(default=14400, alias="RBA_DECAY_HALF_LIFE_SECONDS") # 4h half-life
# Severity points contributed by each correlated alert. Keep additive and
# capped so a single noisy detection can't promote on its own.
rba_severity_weights_critical: float = Field(default=40.0, alias="RBA_W_CRITICAL")
diff --git a/services/fusion/app/services/confidence.py b/services/fusion/app/services/confidence.py
index 429654cb2..7219d4272 100644
--- a/services/fusion/app/services/confidence.py
+++ b/services/fusion/app/services/confidence.py
@@ -289,9 +289,7 @@ class ConfidenceScorer:
fused.confidence_label = label
# Sort rationale by absolute contribution, descending — UI shows the
# most-impactful evidence first.
- fused.confidence_rationale = sorted(
- rationale, key=lambda f: abs(f.contribution * f.weight), reverse=True
- )
+ fused.confidence_rationale = sorted(rationale, key=lambda f: abs(f.contribution * f.weight), reverse=True)
logger.debug(
"confidence_scored",
diff --git a/services/fusion/app/services/entity_risk.py b/services/fusion/app/services/entity_risk.py
index 7c7d990c9..7126a9b6b 100644
--- a/services/fusion/app/services/entity_risk.py
+++ b/services/fusion/app/services/entity_risk.py
@@ -174,9 +174,7 @@ class EntityRiskEngine:
records.append(rec)
return records
- async def get(
- self, tenant_id: UUID | str, entity_type: str, entity_value: str
- ) -> EntityRiskRecord | None:
+ async def get(self, tenant_id: UUID | str, entity_type: str, entity_value: str) -> EntityRiskRecord | None:
return await self._load(str(tenant_id), entity_type, entity_value)
async def stats(self, tenant_id: UUID | str) -> dict:
@@ -331,17 +329,13 @@ class EntityRiskEngine:
await self._redis.zremrangebyrank(topn_key, 0, -(self._max_top + 1))
await self._redis.expire(topn_key, self._window)
- async def _load(
- self, tenant_id: str, entity_type: str, entity_value: str
- ) -> EntityRiskRecord | None:
+ async def _load(self, tenant_id: str, entity_type: str, entity_value: str) -> EntityRiskRecord | None:
key = _ENTITY_PREFIX + f"{tenant_id}:{entity_type}:{entity_value}"
data = await self._redis.hgetall(key)
if not data:
return None
decoded = {
- (k.decode() if isinstance(k, (bytes, bytearray)) else k): (
- v.decode() if isinstance(v, (bytes, bytearray)) else v
- )
+ (k.decode() if isinstance(k, (bytes, bytearray)) else k): (v.decode() if isinstance(v, (bytes, bytearray)) else v)
for k, v in data.items()
}
promoted_at = None
diff --git a/services/fusion/app/services/fusion_engine.py b/services/fusion/app/services/fusion_engine.py
index 932257d95..e0e492cb2 100644
--- a/services/fusion/app/services/fusion_engine.py
+++ b/services/fusion/app/services/fusion_engine.py
@@ -107,9 +107,7 @@ class FusionEngine:
logger.info(
"rba_promotions",
alert_id=str(alert.id),
- promoted=[
- f"{p.entity_type}:{p.entity_value}" for p in promotions
- ],
+ promoted=[f"{p.entity_type}:{p.entity_value}" for p in promotions],
)
except Exception as exc:
logger.warning("rba_observation_failed", error=str(exc))
diff --git a/services/fusion/tests/conftest.py b/services/fusion/tests/conftest.py
index 201f2824f..203f9adb2 100644
--- a/services/fusion/tests/conftest.py
+++ b/services/fusion/tests/conftest.py
@@ -18,5 +18,6 @@ def pytest_collection_modifyitems(items):
if isinstance(item, pytest.Function) and item.get_closest_marker("asyncio") is None:
if callable(item.function):
import asyncio
+
if asyncio.iscoroutinefunction(item.function):
item.add_marker(pytest.mark.asyncio)
diff --git a/services/fusion/tests/test_confidence.py b/services/fusion/tests/test_confidence.py
index ec5528b37..396702750 100644
--- a/services/fusion/tests/test_confidence.py
+++ b/services/fusion/tests/test_confidence.py
@@ -145,9 +145,7 @@ def test_score_is_deterministic(scorer: ConfidenceScorer) -> None:
b = scorer.score(_fused(alert, anomaly_score=0.7, priority_score=0.6))
assert a.confidence_score == b.confidence_score
assert a.confidence_label == b.confidence_label
- assert [f.factor for f in a.confidence_rationale] == [
- f.factor for f in b.confidence_rationale
- ]
+ assert [f.factor for f in a.confidence_rationale] == [f.factor for f in b.confidence_rationale]
# ─── Banding ─────────────────────────────────────────────────────────────────
diff --git a/services/fusion/tests/test_entity_risk.py b/services/fusion/tests/test_entity_risk.py
index 37e64fef7..04d7ed8dd 100644
--- a/services/fusion/tests/test_entity_risk.py
+++ b/services/fusion/tests/test_entity_risk.py
@@ -37,9 +37,7 @@ class _FakeRedis:
async def hset(self, key: str, mapping: dict[str, Any]) -> int:
bucket = self.hashes.setdefault(key, {})
for k, v in mapping.items():
- bucket[k.encode() if isinstance(k, str) else k] = (
- v.encode() if isinstance(v, str) else v
- )
+ bucket[k.encode() if isinstance(k, str) else k] = v.encode() if isinstance(v, str) else v
return len(mapping)
async def hgetall(self, key: str) -> dict[bytes, bytes]:
@@ -57,9 +55,7 @@ class _FakeRedis:
bucket[member] = float(score)
return added
- async def zrevrange(
- self, key: str, start: int, stop: int, withscores: bool = False
- ) -> list[Any]:
+ async def zrevrange(self, key: str, start: int, stop: int, withscores: bool = False) -> list[Any]:
bucket = self.zsets.get(key, {})
sorted_pairs = sorted(bucket.items(), key=lambda kv: kv[1], reverse=True)
# Redis ranges are inclusive on both ends.
diff --git a/services/purple-team/app/models/purple_team.py b/services/purple-team/app/models/purple_team.py
index 34b2b8365..a55e21c03 100644
--- a/services/purple-team/app/models/purple_team.py
+++ b/services/purple-team/app/models/purple_team.py
@@ -124,9 +124,7 @@ class DetectionDriftSnapshot(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, server_default=func.gen_random_uuid())
tenant_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False, index=True)
- captured_at: Mapped[datetime] = mapped_column(
- DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
- )
+ captured_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
# "scheduled" | "manual" | "post-run"
trigger: Mapped[str] = mapped_column(String(32), nullable=False, server_default="scheduled")
diff --git a/services/purple-team/app/services/drift.py b/services/purple-team/app/services/drift.py
index dc840ac6e..a7b0f41e4 100644
--- a/services/purple-team/app/services/drift.py
+++ b/services/purple-team/app/services/drift.py
@@ -48,16 +48,10 @@ async def compute_coverage_for_tenant(
used.
"""
- exec_result = await session.execute(
- select(TestExecution).where(TestExecution.tenant_id == tenant_id)
- )
+ exec_result = await session.execute(select(TestExecution).where(TestExecution.tenant_id == tenant_id))
executions = exec_result.scalars().all()
- atomic_result = await session.execute(
- select(AtomicTest.technique_id, AtomicTest.tactic).where(
- AtomicTest.tenant_id == tenant_id
- )
- )
+ atomic_result = await session.execute(select(AtomicTest.technique_id, AtomicTest.tactic).where(AtomicTest.tenant_id == tenant_id))
tactic_by_technique: dict[str, str] = {}
for technique_id, tactic in atomic_result.all():
# Atomic Red Team can list the same technique under multiple
diff --git a/services/purple-team/app/services/drift_diff.py b/services/purple-team/app/services/drift_diff.py
index 5ffc44314..1c765eb07 100644
--- a/services/purple-team/app/services/drift_diff.py
+++ b/services/purple-team/app/services/drift_diff.py
@@ -68,12 +68,10 @@ def compute_drift(
"current": cur,
"previous": prev,
"delta_coverage": round(
- float((cur or {}).get("coverage", 0.0))
- - float((prev or {}).get("coverage", 0.0)),
+ float((cur or {}).get("coverage", 0.0)) - float((prev or {}).get("coverage", 0.0)),
3,
),
- "delta_detected": int((cur or {}).get("detected", 0))
- - int((prev or {}).get("detected", 0)),
+ "delta_detected": int((cur or {}).get("detected", 0)) - int((prev or {}).get("detected", 0)),
"status": status,
}
)
@@ -81,15 +79,11 @@ def compute_drift(
cur_sum = current.get("summary") or {}
prev_sum = previous.get("summary") or {}
summary_delta = {
- "delta_total": int(cur_sum.get("total_techniques", 0))
- - int(prev_sum.get("total_techniques", 0)),
- "delta_tested": int(cur_sum.get("tested_techniques", 0))
- - int(prev_sum.get("tested_techniques", 0)),
- "delta_detected": int(cur_sum.get("detected_techniques", 0))
- - int(prev_sum.get("detected_techniques", 0)),
+ "delta_total": int(cur_sum.get("total_techniques", 0)) - int(prev_sum.get("total_techniques", 0)),
+ "delta_tested": int(cur_sum.get("tested_techniques", 0)) - int(prev_sum.get("tested_techniques", 0)),
+ "delta_detected": int(cur_sum.get("detected_techniques", 0)) - int(prev_sum.get("detected_techniques", 0)),
"delta_coverage": round(
- float(cur_sum.get("overall_coverage", 0.0))
- - float(prev_sum.get("overall_coverage", 0.0)),
+ float(cur_sum.get("overall_coverage", 0.0)) - float(prev_sum.get("overall_coverage", 0.0)),
3,
),
}
diff --git a/services/purple-team/app/services/scheduler.py b/services/purple-team/app/services/scheduler.py
index e8e28e3be..a281372f8 100644
--- a/services/purple-team/app/services/scheduler.py
+++ b/services/purple-team/app/services/scheduler.py
@@ -65,9 +65,7 @@ class DriftScheduler:
async with self._session_factory() as session:
for tenant_id in tenants:
try:
- snap = await capture_snapshot(
- session, tenant_id, trigger="scheduled"
- )
+ snap = await capture_snapshot(session, tenant_id, trigger="scheduled")
LOG.info(
"Captured drift snapshot tenant=%s coverage=%.3f tested=%d",
tenant_id,
@@ -75,9 +73,7 @@ class DriftScheduler:
snap.tested_techniques,
)
except Exception:
- LOG.exception(
- "Drift snapshot failed for tenant=%s", tenant_id
- )
+ LOG.exception("Drift snapshot failed for tenant=%s", tenant_id)
await session.commit()
def start(self) -> None:
@@ -98,9 +94,7 @@ class DriftScheduler:
)
if not self._scheduler.running:
self._scheduler.start()
- LOG.info(
- "Drift scheduler started (interval=%ss)", self._interval_seconds
- )
+ LOG.info("Drift scheduler started (interval=%ss)", self._interval_seconds)
def stop(self) -> None:
"""Gracefully stop the scheduler."""
diff --git a/services/purple-team/tests/test_drift.py b/services/purple-team/tests/test_drift.py
index 0ed79ad5e..a141e61de 100644
--- a/services/purple-team/tests/test_drift.py
+++ b/services/purple-team/tests/test_drift.py
@@ -65,12 +65,8 @@ class TestComputeDrift:
assert drift["summary"]["removed"] == 1
def test_regression_lowers_detection_count(self) -> None:
- prev = build_coverage_matrix(
- [_exec("T1078", "initial-access", status="success", detected=True)]
- )
- curr = build_coverage_matrix(
- [_exec("T1078", "initial-access", status="success", detected=False)]
- )
+ prev = build_coverage_matrix([_exec("T1078", "initial-access", status="success", detected=True)])
+ curr = build_coverage_matrix([_exec("T1078", "initial-access", status="success", detected=False)])
drift = compute_drift(curr, prev)
regressed = [t for t in drift["techniques"] if t["status"] == "regressed"]
assert len(regressed) == 1
@@ -78,12 +74,8 @@ class TestComputeDrift:
assert drift["summary"]["regressed"] == 1
def test_improvement_raises_detection_count(self) -> None:
- prev = build_coverage_matrix(
- [_exec("T1078", "initial-access", status="success", detected=False)]
- )
- curr = build_coverage_matrix(
- [_exec("T1078", "initial-access", status="success", detected=True)]
- )
+ prev = build_coverage_matrix([_exec("T1078", "initial-access", status="success", detected=False)])
+ curr = build_coverage_matrix([_exec("T1078", "initial-access", status="success", detected=True)])
drift = compute_drift(curr, prev)
improved = [t for t in drift["techniques"] if t["status"] == "improved"]
assert len(improved) == 1
@@ -91,9 +83,7 @@ class TestComputeDrift:
assert drift["summary"]["improved"] == 1
def test_summary_delta_reflects_aggregate_change(self) -> None:
- prev = build_coverage_matrix(
- [_exec("T1078", "initial-access", status="success", detected=False)]
- )
+ prev = build_coverage_matrix([_exec("T1078", "initial-access", status="success", detected=False)])
curr = build_coverage_matrix(
[
_exec("T1078", "initial-access", status="success", detected=True),