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(ci): clean up Ruff lint errors blocking main CI (#194)

Beenu Arora1798d6e2d4bf
diff --git a/scripts/run_evals.py b/scripts/run_evals.py
index 2fcc803b4..d53021c2d 100755
--- a/scripts/run_evals.py
+++ b/scripts/run_evals.py
@@ -63,10 +63,10 @@ _AGENTS_ROOT = _REPO_ROOT / "services" / "agents"
# Order matters: scripts/ also contains a tests/ package (scripts/tests/) for
# the CLI smoke test, and would shadow services/agents/tests/ if it landed at
# position 0 of sys.path. Insert scripts/ first, then agents/ on top, so that
-# `from tests.test_adversary_eval import ...` resolves to the substrate tests.
+# `from tests.test_adversary_eval import ...` resolves to the substrate tests
+# under services/agents/tests/.
sys.path.insert(0, str(_REPO_ROOT / "scripts"))
sys.path.insert(0, str(_AGENTS_ROOT))
-sys.path.insert(0, str(_REPO_ROOT / "scripts"))
# The per-investigation token/USD/latency telemetry block (T2.4) is stdlib-only
# and lives in ``scripts/eval_telemetry.py`` so it can run on hosts that
diff --git a/services/actions/app/security/credential_vault.py b/services/actions/app/security/credential_vault.py
index c26b2f2fa..583113893 100644
--- a/services/actions/app/security/credential_vault.py
+++ b/services/actions/app/security/credential_vault.py
@@ -95,7 +95,7 @@ class CredentialVault:
if isinstance(payload, Mapping):
out: dict[str, Any] = {}
for k, v in payload.items():
- if secret_keys is not None and k not in secret_keys and not isinstance(v, (Mapping, list)):
+ if secret_keys is not None and k not in secret_keys and not isinstance(v, Mapping | list):
out[k] = v
else:
out[k] = self._walk(v, encrypt=encrypt, secret_keys=secret_keys, _key=k)
diff --git a/services/agents/app/agents/__init__.py b/services/agents/app/agents/__init__.py
index ca9ca6040..dbb4ca0f8 100644
--- a/services/agents/app/agents/__init__.py
+++ b/services/agents/app/agents/__init__.py
@@ -167,10 +167,10 @@ class TriageCapability:
self.name = name
self._runner = runner
- async def __call__(self, state: "InvestigationState") -> "InvestigationState":
+ async def __call__(self, state: InvestigationState) -> InvestigationState:
return await self._runner(state)
- async def run(self, state: "InvestigationState") -> "InvestigationState":
+ async def run(self, state: InvestigationState) -> InvestigationState:
return await self._runner(state)
def __repr__(self) -> str: # pragma: no cover - debug helper
@@ -214,7 +214,7 @@ class TriageAgent:
}
@staticmethod
- async def auto_triage(state: "InvestigationState") -> "InvestigationState":
+ async def auto_triage(state: InvestigationState) -> InvestigationState:
"""LLM-based auto-triage entry point.
Delegates to :func:`app.agents.auto_triage_agent.run_auto_triage`.
@@ -222,7 +222,7 @@ class TriageAgent:
return await _run_auto_triage(state)
@staticmethod
- async def heuristic_triage(state: "InvestigationState") -> "InvestigationState":
+ async def heuristic_triage(state: InvestigationState) -> InvestigationState:
"""Deterministic heuristic triage (severity scoring + IOC extraction).
Delegates to :func:`app.agents.triage_agent.run_triage`. Used by the
@@ -234,10 +234,10 @@ class TriageAgent:
@classmethod
async def analyse(
cls,
- state: "InvestigationState",
+ state: InvestigationState,
*,
capability: str,
- ) -> "InvestigationState":
+ ) -> InvestigationState:
"""Dispatch to a named sub-agent capability.
Args:
@@ -253,7 +253,7 @@ class TriageAgent:
# Convenience callable so ``await TriageAgent()(state)`` and
# ``await TriageAgent.auto_triage(state)`` both work.
- async def __call__(self, state: "InvestigationState") -> "InvestigationState":
+ async def __call__(self, state: InvestigationState) -> InvestigationState:
return await _run_auto_triage(state)
@classmethod
@@ -450,10 +450,10 @@ class _CapabilityShim:
cls.capability = capability
@classmethod
- async def run(cls, state: "InvestigationState") -> "InvestigationState":
+ async def run(cls, state: InvestigationState) -> InvestigationState:
return await cls.capability(state)
- async def __call__(self, state: "InvestigationState") -> "InvestigationState":
+ async def __call__(self, state: InvestigationState) -> InvestigationState:
return await type(self).capability(state)
diff --git a/services/agents/app/agents/cloud_agent.py b/services/agents/app/agents/cloud_agent.py
index 444cf231e..347b802b2 100644
--- a/services/agents/app/agents/cloud_agent.py
+++ b/services/agents/app/agents/cloud_agent.py
@@ -90,34 +90,21 @@ def _build_cloud_context(state: InvestigationState) -> str:
parts.append(f"Bucket ACL: {raw.get('bucket_acl', 'N/A')}")
if raw.get("bucket_policy"):
parts.append(
- "Bucket Policy:\n"
- + summarize_structure_for_llm(
- raw["bucket_policy"], label="bucket_policy", max_lines=28, max_depth=3
- )
+ "Bucket Policy:\n" + summarize_structure_for_llm(raw["bucket_policy"], label="bucket_policy", max_lines=28, max_depth=3)
)
if raw.get("security_group_rules"):
parts.append(
"SG Rules:\n"
- + summarize_structure_for_llm(
- raw["security_group_rules"], label="security_group_rules", max_lines=28, max_depth=3
- )
+ + summarize_structure_for_llm(raw["security_group_rules"], label="security_group_rules", max_lines=28, max_depth=3)
)
if raw.get("iam_policy") or raw.get("permissions"):
val = raw.get("iam_policy") or raw.get("permissions")
- parts.append(
- "IAM/Permissions:\n"
- + summarize_structure_for_llm(val, label="iam_permissions", max_lines=28, max_depth=3)
- )
+ parts.append("IAM/Permissions:\n" + summarize_structure_for_llm(val, label="iam_permissions", max_lines=28, max_depth=3))
if raw.get("api_calls"):
- parts.append(
- "API calls:\n"
- + summarize_structure_for_llm(
- raw["api_calls"], label="api_calls", max_lines=28, max_depth=2
- )
- )
+ parts.append("API calls:\n" + summarize_structure_for_llm(raw["api_calls"], label="api_calls", max_lines=28, max_depth=2))
if raw.get("is_public") is not None:
parts.append(f"Public access: {raw['is_public']}")
diff --git a/services/agents/app/agents/identity_agent.py b/services/agents/app/agents/identity_agent.py
index 65e406231..b9242dacf 100644
--- a/services/agents/app/agents/identity_agent.py
+++ b/services/agents/app/agents/identity_agent.py
@@ -19,8 +19,8 @@ from langchain_openai import ChatOpenAI
from app.context import ContextBundle
from app.llm import safe_ainvoke
-from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
from app.models.state import AgentStatus, InvestigationState
+from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
logger = structlog.get_logger()
@@ -85,10 +85,7 @@ def _build_identity_context(state: InvestigationState) -> str:
if raw.get("login_attempts"):
parts.append(
- "Login attempts:\n"
- + summarize_structure_for_llm(
- raw["login_attempts"], label="login_attempts", max_lines=24, max_depth=2
- )
+ "Login attempts:\n" + summarize_structure_for_llm(raw["login_attempts"], label="login_attempts", max_lines=24, max_depth=2)
)
if raw.get("failed_count"):
parts.append(f"Failed attempt count: {raw['failed_count']}")
@@ -96,10 +93,7 @@ def _build_identity_context(state: InvestigationState) -> str:
geo_fields = ["login_locations", "geo_locations"]
for gf in geo_fields:
if raw.get(gf):
- parts.append(
- f"Geo locations ({gf}):\n"
- + summarize_structure_for_llm(raw[gf], label=gf, max_lines=20, max_depth=2)
- )
+ parts.append(f"Geo locations ({gf}):\n" + summarize_structure_for_llm(raw[gf], label=gf, max_lines=20, max_depth=2))
priv_fields = ["role_change", "group_added", "permissions_changed", "privilege_level"]
priv_parts = []
@@ -113,10 +107,7 @@ def _build_identity_context(state: InvestigationState) -> str:
parts.append(f"Event time: {raw['timestamp']}")
if raw.get("previous_login"):
parts.append(
- "Previous login:\n"
- + summarize_structure_for_llm(
- raw["previous_login"], label="previous_login", max_lines=16, max_depth=2
- )
+ "Previous login:\n" + summarize_structure_for_llm(raw["previous_login"], label="previous_login", max_lines=16, max_depth=2)
)
extra_keys = {
diff --git a/services/agents/app/agents/insider_threat_agent.py b/services/agents/app/agents/insider_threat_agent.py
index 0722e55e2..4de3e659a 100644
--- a/services/agents/app/agents/insider_threat_agent.py
+++ b/services/agents/app/agents/insider_threat_agent.py
@@ -115,19 +115,11 @@ def _build_insider_context(state: InvestigationState) -> str:
parts.append(f"Destination domain: {raw['destination_domain']}")
if raw.get("usb_events"):
- parts.append(
- "USB events:\n"
- + summarize_structure_for_llm(
- raw["usb_events"], label="usb_events", max_lines=24, max_depth=2
- )
- )
+ parts.append("USB events:\n" + summarize_structure_for_llm(raw["usb_events"], label="usb_events", max_lines=24, max_depth=2))
if raw.get("recent_activity"):
parts.append(
- "Recent activity:\n"
- + summarize_structure_for_llm(
- raw["recent_activity"], label="recent_activity", max_lines=24, max_depth=2
- )
+ "Recent activity:\n" + summarize_structure_for_llm(raw["recent_activity"], label="recent_activity", max_lines=24, max_depth=2)
)
if raw.get("baseline_deviation"):
diff --git a/services/agents/app/agents/phishing_agent.py b/services/agents/app/agents/phishing_agent.py
index 21d9ccc69..c8fa991c2 100644
--- a/services/agents/app/agents/phishing_agent.py
+++ b/services/agents/app/agents/phishing_agent.py
@@ -20,8 +20,8 @@ from langchain_openai import ChatOpenAI
from app.context import ContextBundle
from app.llm import safe_ainvoke
-from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
from app.models.state import AgentStatus, InvestigationState
+from app.prompt_serialization import format_extra_fields_for_llm, summarize_structure_for_llm
logger = structlog.get_logger()
@@ -72,10 +72,7 @@ def _build_phishing_context(state: InvestigationState) -> str:
parts.append(f"{label}: {raw[key]}")
if raw.get("urls"):
- parts.append(
- "URLs found:\n"
- + summarize_structure_for_llm(raw["urls"], label="urls", max_lines=24, max_depth=2)
- )
+ parts.append("URLs found:\n" + summarize_structure_for_llm(raw["urls"], label="urls", max_lines=24, max_depth=2))
if raw.get("url"):
parts.append(f"Primary URL: {raw['url']}")
if raw.get("domain"):
@@ -84,9 +81,7 @@ def _build_phishing_context(state: InvestigationState) -> str:
if raw.get("attachment_hashes"):
parts.append(
"Attachment hashes:\n"
- + summarize_structure_for_llm(
- raw["attachment_hashes"], label="attachment_hashes", max_lines=16, max_depth=1
- )
+ + summarize_structure_for_llm(raw["attachment_hashes"], label="attachment_hashes", max_lines=16, max_depth=1)
)
if raw.get("file_hash"):
parts.append(f"File hash: {raw['file_hash']}")
diff --git a/services/agents/app/context/bundle.py b/services/agents/app/context/bundle.py
index cbd9daed3..1b41f28e5 100644
--- a/services/agents/app/context/bundle.py
+++ b/services/agents/app/context/bundle.py
@@ -107,7 +107,7 @@ def _string_field(raw: dict[str, Any], keys: tuple[str, ...]) -> list[str]:
val = raw.get(key)
if isinstance(val, str) and val.strip():
out.append(val.strip())
- elif isinstance(val, (list, tuple)):
+ elif isinstance(val, list | tuple):
for v in val:
if isinstance(v, str) and v.strip():
out.append(v.strip())
@@ -300,12 +300,7 @@ class ContextBundle(BaseModel):
Used by sub-agents to decide whether to short-circuit to the
bundle-aware prompt or fall back to bare-alert reasoning.
"""
- return bool(
- self.entity_neighborhoods
- or self.peer_baselines
- or self.threat_intel
- or self.historical_similar_cases
- )
+ return bool(self.entity_neighborhoods or self.peer_baselines or self.threat_intel or self.historical_similar_cases)
def prompt_context_lines(self) -> list[str]:
"""Render the bundle's safe summary fields as prompt-ready lines.
@@ -321,10 +316,7 @@ class ContextBundle(BaseModel):
s = self.summary_for_llm()
parts: list[str] = ["", "Pre-fetched investigation context (ContextBundle):"]
if s.get("entity_count"):
- parts.append(
- f"- Entities resolved: {s['entity_count']} "
- f"({', '.join(s.get('entity_types') or []) or 'unknown'})"
- )
+ parts.append(f"- Entities resolved: {s['entity_count']} " f"({', '.join(s.get('entity_types') or []) or 'unknown'})")
if s.get("neighborhood_summaries"):
parts.append("- Graph neighbourhood:")
for line in s["neighborhood_summaries"]:
@@ -336,10 +328,7 @@ class ContextBundle(BaseModel):
(h["similarity"] for h in s.get("historical_verdicts") or []),
default=0.0,
)
- parts.append(
- f"- Similar historical cases: {s['historical_similar_count']} "
- f"(top similarity={top:.2f})"
- )
+ parts.append(f"- Similar historical cases: {s['historical_similar_count']} " f"(top similarity={top:.2f})")
for h in (s.get("historical_verdicts") or [])[:3]:
parts.append(f" * {h['key']} → {h['verdict']} (sim={h['similarity']:.2f})")
if s.get("ueba_entities_with_baseline"):
@@ -367,15 +356,9 @@ class ContextBundle(BaseModel):
+ (f", blast_radius={nbr.blast_radius_score:.2f}" if nbr.blast_radius_score is not None else "")
for key, nbr in sorted(self.entity_neighborhoods.items())
]
- blast_scores = [
- n.blast_radius_score
- for n in self.entity_neighborhoods.values()
- if n.blast_radius_score is not None
- ]
+ blast_scores = [n.blast_radius_score for n in self.entity_neighborhoods.values() if n.blast_radius_score is not None]
ueba_devs = [b.deviation_score for b in self.peer_baselines.values()]
- high_risk = sorted(
- ti.ioc for ti in self.threat_intel.values() if ti.risk == "high"
- )
+ high_risk = sorted(ti.ioc for ti in self.threat_intel.values() if ti.risk == "high")
ti_sources: set[str] = set()
for ti in self.threat_intel.values():
ti_sources.update(ti.sources)
@@ -440,7 +423,7 @@ def _ti_sources(payload: dict[str, Any]) -> list[str]:
if isinstance(sources, list):
return [str(s) for s in sources][:10]
if isinstance(sources, dict):
- return list(sorted(sources.keys()))[:10]
+ return sorted(sources.keys())[:10]
return []
@@ -464,9 +447,7 @@ class ContextBundleBuilder:
per_source_timeout: float = 3.5,
api_token: str | None = None,
) -> None:
- self.depth = depth if depth is not None else int(
- os.getenv("AISOC_CONTEXT_BUNDLE_DEPTH", str(self.DEFAULT_DEPTH))
- )
+ self.depth = depth if depth is not None else int(os.getenv("AISOC_CONTEXT_BUNDLE_DEPTH", str(self.DEFAULT_DEPTH)))
self.max_neighborhood_nodes = max_neighborhood_nodes
self.history_limit = history_limit
self.ti_concurrency = ti_concurrency
@@ -543,9 +524,7 @@ class ContextBundleBuilder:
# Source fetchers — each returns its own slice of the bundle
# ------------------------------------------------------------------
- async def _fetch_neighborhoods(
- self, entities: list[EntityRef]
- ) -> dict[str, EntityNeighborhood]:
+ async def _fetch_neighborhoods(self, entities: list[EntityRef]) -> dict[str, EntityNeighborhood]:
"""Walk the graph for each principal entity, depth-N."""
# Lazy import so ``services/agents`` modules without the API tool
# installed (e.g. eval harness) can still import this builder.
@@ -571,10 +550,7 @@ class ContextBundleBuilder:
blast = None
if isinstance(blast_payload, dict):
blast = blast_payload.get("blast_radius_score")
- summary = (
- f"{len(nodes)} neighbors at depth {self.depth}"
- + (f", blast_radius={float(blast):.2f}" if blast is not None else "")
- )
+ summary = f"{len(nodes)} neighbors at depth {self.depth}" + (f", blast_radius={float(blast):.2f}" if blast is not None else "")
return entity.key, EntityNeighborhood(
entity=entity,
depth=self.depth,
@@ -625,11 +601,7 @@ class ContextBundleBuilder:
if not isinstance(value, dict):
value = {}
row_tags = {str(t).lower() for t in (row.get("tags") or [])}
- jaccard = (
- len(own_set & row_tags) / max(1, len(own_set | row_tags))
- if own_set or row_tags
- else 0.0
- )
+ jaccard = len(own_set & row_tags) / max(1, len(own_set | row_tags)) if own_set or row_tags else 0.0
out.append(
HistoricalCase(
key=str(row.get("key", "")),
@@ -659,9 +631,7 @@ class ContextBundleBuilder:
raise RuntimeError(f"httpx unavailable: {exc}") from exc
ueba_url = os.getenv("AISOC_UEBA_URL", "http://ueba:8086")
- principals = [
- e for e in entities if e.type in ("user", "email", "host", "ip")
- ]
+ principals = [e for e in entities if e.type in ("user", "email", "host", "ip")]
if not principals:
self._record_source("ueba")
return {}
@@ -669,6 +639,7 @@ class ContextBundleBuilder:
out: dict[str, UEBABaseline] = {}
async with httpx.AsyncClient(timeout=self.per_source_timeout) as client:
+
async def _one(entity: EntityRef) -> tuple[str, UEBABaseline] | None:
# The UEBA list endpoint takes tenant + entity_type, then we
# filter client-side. We accept that this is over-fetching
@@ -709,18 +680,14 @@ class ContextBundleBuilder:
self._record_source("ueba")
return out
- async def _fetch_threat_intel(
- self, entities: list[EntityRef]
- ) -> dict[str, ThreatIntelMatch]:
+ async def _fetch_threat_intel(self, entities: list[EntityRef]) -> dict[str, ThreatIntelMatch]:
"""Bulk-enrich every IOC-shaped entity in the alert."""
try:
from app.tools.enrichment import bulk_enrich_iocs
except Exception as exc: # noqa: BLE001
raise RuntimeError(f"enrichment tool unavailable: {exc}") from exc
- ioc_entities = [
- e for e in entities if e.type in ("ip", "domain", "hash", "url")
- ]
+ ioc_entities = [e for e in entities if e.type in ("ip", "domain", "hash", "url")]
if not ioc_entities:
self._record_source("threat_intel")
return {}
@@ -759,7 +726,7 @@ class ContextBundleBuilder:
"""Run ``coro`` with a per-source timeout; record errors instead of raising."""
try:
return await asyncio.wait_for(coro, timeout=self.per_source_timeout)
- except asyncio.TimeoutError:
+ except TimeoutError:
bundle.errors.append(f"{name}:timeout")
return None
except Exception as exc: # noqa: BLE001
diff --git a/services/agents/app/hunt/engine.py b/services/agents/app/hunt/engine.py
index 36d765023..43f6eea15 100644
--- a/services/agents/app/hunt/engine.py
+++ b/services/agents/app/hunt/engine.py
@@ -67,7 +67,7 @@ def _get_field(event: dict[str, Any], dotted: str) -> Any:
def _coerce_number(value: Any) -> float | None:
if isinstance(value, bool): # bool is a subclass of int — exclude on purpose
return None
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return float(value)
if isinstance(value, str):
try:
@@ -108,7 +108,7 @@ def _indicator_matches(event: dict[str, Any], ind: HuntIndicator) -> bool:
return num is not None and num <= ind.lte
if ind.contains_any is not None:
- if isinstance(val, (list, tuple, set)):
+ if isinstance(val, list | tuple | set):
haystack = list(val)
else:
haystack = [val]
diff --git a/services/agents/app/investigator/prompt_sanitizer.py b/services/agents/app/investigator/prompt_sanitizer.py
index 58fab8e68..f3369c0d0 100644
--- a/services/agents/app/investigator/prompt_sanitizer.py
+++ b/services/agents/app/investigator/prompt_sanitizer.py
@@ -90,8 +90,7 @@ _INJECTION_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
# phrases such as "the database is unrestricted" or
# "you are running an unrestricted query" do not false-trip.
re.compile(
- r"\byou are\s+(?:now\s+)?(?:in\s+)?(?:a\s+|an\s+|the\s+)?"
- r"(?:dan|developer\s+mode|jailbroken|unrestricted|no-?op)\b",
+ r"\byou are\s+(?:now\s+)?(?:in\s+)?(?:a\s+|an\s+|the\s+)?" r"(?:dan|developer\s+mode|jailbroken|unrestricted|no-?op)\b",
re.IGNORECASE,
),
"[REDACTED:INJECTION]",
@@ -177,11 +176,11 @@ def sanitize_value(
if _depth > 6:
return "[REDACTED:DEPTH]"
- if value is None or isinstance(value, (bool, int, float)):
+ if value is None or isinstance(value, bool | int | float):
return value
if isinstance(value, str):
return sanitize_text(value, max_len=max_field_len)
- if isinstance(value, (list, tuple)):
+ if isinstance(value, list | tuple):
items = list(value)
truncated = max(0, len(items) - max_list_items) if max_list_items > 0 else 0
items = items[:max_list_items] if max_list_items > 0 else items
diff --git a/services/agents/app/llm/contract.py b/services/agents/app/llm/contract.py
index 946c455cc..84c45ef96 100644
--- a/services/agents/app/llm/contract.py
+++ b/services/agents/app/llm/contract.py
@@ -223,9 +223,7 @@ def classify_message(content: str, *, role: str = "user") -> str | None:
elif isinstance(parsed, list) and parsed:
head = parsed[0]
if isinstance(head, dict):
- if len(head) > _MAX_JSON_LINE_KEYS and (
- _looks_like_ocsf(head) or _looks_like_raw_log(head)
- ):
+ if len(head) > _MAX_JSON_LINE_KEYS and (_looks_like_ocsf(head) or _looks_like_raw_log(head)):
return "raw event array detected (looks like log batch)"
return None
diff --git a/services/agents/app/nl_query/translator.py b/services/agents/app/nl_query/translator.py
index b706914c2..2e8d6ca2b 100644
--- a/services/agents/app/nl_query/translator.py
+++ b/services/agents/app/nl_query/translator.py
@@ -267,23 +267,19 @@ _TIME_REGEX_SINGULAR = re.compile(
# boundary so we don't drag the rest of the question into the field name.
_NUMERIC_AGG_PATTERNS: list[tuple[str, str]] = [
(
- r"\b(?:average|avg|mean)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:average|avg|mean)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"AVG",
),
(
- r"\b(?:sum(?:\s+of)?|total(?:\s+of)?)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:sum(?:\s+of)?|total(?:\s+of)?)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"SUM",
),
(
- r"\b(?:max|maximum|largest|highest)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:max|maximum|largest|highest)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"MAX",
),
(
- r"\b(?:min|minimum|lowest|smallest)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:min|minimum|lowest|smallest)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"MIN",
),
]
@@ -598,8 +594,7 @@ def _extract_aggregations(question: str, intents: QueryIntents) -> None:
# next clause boundary (``with``, ``having``, ``in the last 24h`` etc.)
# without dragging the whole tail of the question into the field name.
for m in re.finditer(
- r"\b(?:unique|distinct)\s+([a-z _]+?)"
- r"(?=\b(?:by|per|in|over|with|where|having|from|and|,|$))",
+ r"\b(?:unique|distinct)\s+([a-z _]+?)" r"(?=\b(?:by|per|in|over|with|where|having|from|and|,|$))",
text + " ,",
):
candidate = m.group(1).strip().rstrip(",")
diff --git a/services/agents/app/orchestrator/router.py b/services/agents/app/orchestrator/router.py
index abc5c30c3..49f13fa61 100644
--- a/services/agents/app/orchestrator/router.py
+++ b/services/agents/app/orchestrator/router.py
@@ -241,15 +241,15 @@ def _resolve_runner(name: str) -> _SubAgentRunner:
agents_pkg = importlib.import_module("app.agents")
if name == "auto_triage":
- return getattr(agents_pkg, "run_auto_triage")
+ return agents_pkg.run_auto_triage
if name == "phishing":
- return getattr(agents_pkg, "run_phishing")
+ return agents_pkg.run_phishing
if name == "identity":
- return getattr(agents_pkg, "run_identity")
+ return agents_pkg.run_identity
if name == "cloud":
- return getattr(agents_pkg, "run_cloud")
+ return agents_pkg.run_cloud
if name == "insider":
- return getattr(agents_pkg, "run_insider_threat")
+ return agents_pkg.run_insider_threat
raise KeyError(f"Unknown sub-agent capability: {name}")
@@ -380,10 +380,7 @@ async def _run_parallel(state: InvestigationState, signals: list[str]) -> Invest
copy.iteration_count = state.iteration_count
branch_inputs.append(copy)
- coros = [
- _resolve_runner(name)(branch_inputs[idx])
- for idx, name in enumerate(signals)
- ]
+ coros = [_resolve_runner(name)(branch_inputs[idx]) for idx, name in enumerate(signals)]
branch_results = await asyncio.gather(*coros, return_exceptions=True)
successful: list[InvestigationState] = []
diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.py
index d46e69b82..5bf8b55fc 100644
--- a/services/agents/app/playbook/engine.py
+++ b/services/agents/app/playbook/engine.py
@@ -119,7 +119,7 @@ def _resolve_field(context: dict[str, Any], field: str) -> Any:
for part in field.split("."):
if isinstance(cur, dict):
cur = cur.get(part)
- elif isinstance(cur, (list, tuple)):
+ elif isinstance(cur, list | tuple):
# Numeric indices may be specified as bare ints in a dot-path.
try:
idx = int(part)
@@ -145,7 +145,7 @@ def _to_float(value: Any) -> float | None:
return 0.0
if isinstance(value, bool): # bool is a subclass of int; treat explicitly
return 1.0 if value else 0.0
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return float(value)
try:
return float(value)
@@ -194,7 +194,7 @@ def _evaluate_condition(condition: StepCondition, context: dict[str, Any]) -> bo
# pattern of testing field membership in an allowed set.
if value is None:
return False
- if isinstance(expected, (list, tuple, set)):
+ if isinstance(expected, list | tuple | set):
return value in expected
return str(expected) in str(value)
if op in ("gt", "lt"):
@@ -308,13 +308,13 @@ def _evaluate_expression(expression: str, context: dict[str, Any]) -> bool:
if op == "in_":
if rhs is None:
return False
- if isinstance(rhs, (list, tuple, set)):
+ if isinstance(rhs, list | tuple | set):
return lhs in rhs
return str(lhs) in str(rhs)
if op == "not_in":
if rhs is None:
return True
- if isinstance(rhs, (list, tuple, set)):
+ if isinstance(rhs, list | tuple | set):
return lhs not in rhs
return str(lhs) not in str(rhs)
except TypeError:
diff --git a/services/agents/app/policy/guardrails.py b/services/agents/app/policy/guardrails.py
index 6494cda7f..279e6bc04 100644
--- a/services/agents/app/policy/guardrails.py
+++ b/services/agents/app/policy/guardrails.py
@@ -150,7 +150,7 @@ def _yaml_policy_path() -> Path:
def _coerce_threshold_value(action: str, value: Any) -> ActionThresholds | None:
"""Accept either a scalar (== ``auto`` only) or a ``{auto, review, escalation}`` dict."""
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
try:
return _make_thresholds(float(value))
except (TypeError, ValueError):
diff --git a/services/agents/app/prompt_serialization.py b/services/agents/app/prompt_serialization.py
index 3a0b94740..1b3540ea7 100644
--- a/services/agents/app/prompt_serialization.py
+++ b/services/agents/app/prompt_serialization.py
@@ -17,7 +17,7 @@ def _format_primitive(v: Any) -> str:
return "(null)"
if isinstance(v, bool):
return "true" if v else "false"
- if isinstance(v, (int, float)):
+ if isinstance(v, int | float):
return str(v)
s = str(v).replace("\r", " ").replace("\n", " ")
if len(s) > 400:
@@ -46,13 +46,9 @@ def format_extra_fields_for_llm(
continue
v = extra[k]
if isinstance(v, dict):
- lines.append(
- f"{k}:\n{summarize_structure_for_llm(v, label=str(k), max_lines=10, max_depth=max_depth)}"
- )
- elif isinstance(v, (list, tuple)):
- lines.append(
- f"{k}:\n{summarize_structure_for_llm(list(v), label=str(k), max_lines=10, max_depth=max_depth)}"
- )
+ lines.append(f"{k}:\n{summarize_structure_for_llm(v, label=str(k), max_lines=10, max_depth=max_depth)}")
+ elif isinstance(v, list | tuple):
+ lines.append(f"{k}:\n{summarize_structure_for_llm(list(v), label=str(k), max_lines=10, max_depth=max_depth)}")
else:
lines.append(f"{k}: {_format_primitive(v)}")
if omitted > 0:
@@ -95,7 +91,7 @@ def summarize_structure_for_llm(
add(f"{sub}: dict({nk} keys)")
if depth < max_depth and nk <= 12:
visit(v, sub, depth + 1)
- elif isinstance(v, (list, tuple)):
+ elif isinstance(v, list | tuple):
add(f"{sub}: list[{len(v)} items]")
if depth < max_depth:
cap = min(5, len(v))
@@ -105,7 +101,7 @@ def summarize_structure_for_llm(
add(f"{sub}: … {len(v) - cap} more items omitted")
else:
add(f"{sub}: {_format_primitive(v)}")
- elif isinstance(node, (list, tuple)):
+ elif isinstance(node, list | tuple):
add(f"{path}: list[{len(node)}]")
if depth < max_depth:
for i, it in enumerate(node[:6]):
diff --git a/services/agents/app/security/credential_vault.py b/services/agents/app/security/credential_vault.py
index 1859ac07c..c2b885cab 100644
--- a/services/agents/app/security/credential_vault.py
+++ b/services/agents/app/security/credential_vault.py
@@ -134,7 +134,7 @@ class CredentialVault:
if isinstance(payload, Mapping):
out: dict[str, Any] = {}
for k, v in payload.items():
- if secret_keys is not None and k not in secret_keys and not isinstance(v, (Mapping, list)):
+ if secret_keys is not None and k not in secret_keys and not isinstance(v, Mapping | list):
out[k] = v
else:
out[k] = self._walk(v, encrypt=encrypt, secret_keys=secret_keys, _key=k)
diff --git a/services/agents/tests/fidelity/cicids_loader.py b/services/agents/tests/fidelity/cicids_loader.py
index 63db19abd..bc930246e 100644
--- a/services/agents/tests/fidelity/cicids_loader.py
+++ b/services/agents/tests/fidelity/cicids_loader.py
@@ -25,7 +25,7 @@ import csv
import ipaddress
import logging
from collections.abc import Iterable, Iterator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -175,13 +175,13 @@ def _parse_timestamp(value: str) -> str:
text = (value or "").strip()
if not text:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
for fmt in ("%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%Y-%m-%d %H:%M:%S"):
try:
parsed = datetime.strptime(text, fmt)
except ValueError:
continue
- return parsed.replace(tzinfo=timezone.utc).isoformat()
+ return parsed.replace(tzinfo=UTC).isoformat()
return text
@@ -226,9 +226,7 @@ def to_ocsf(row: dict[str, Any]) -> dict[str, Any]:
"""
bytes_in = int(max(row.get("flow_bytes_per_sec", 0.0), 0.0))
- packets_total = int(row.get("total_fwd_packets", 0)) + int(
- row.get("total_bwd_packets", 0)
- )
+ packets_total = int(row.get("total_fwd_packets", 0)) + int(row.get("total_bwd_packets", 0))
return {
"category_uid": 4,
diff --git a/services/agents/tests/fidelity/ctu13_loader.py b/services/agents/tests/fidelity/ctu13_loader.py
index 4ad35345c..8b21b5189 100644
--- a/services/agents/tests/fidelity/ctu13_loader.py
+++ b/services/agents/tests/fidelity/ctu13_loader.py
@@ -24,7 +24,7 @@ import csv
import ipaddress
import logging
from collections.abc import Iterator
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -102,7 +102,7 @@ def _coerce_ip(value: str) -> str:
def _parse_timestamp(value: str) -> str:
text = (value or "").strip()
if not text:
- return datetime.now(timezone.utc).isoformat()
+ return datetime.now(UTC).isoformat()
for fmt in (
"%Y/%m/%d %H:%M:%S.%f",
"%Y-%m-%d %H:%M:%S.%f",
@@ -113,7 +113,7 @@ def _parse_timestamp(value: str) -> str:
parsed = datetime.strptime(text, fmt)
except ValueError:
continue
- return parsed.replace(tzinfo=timezone.utc).isoformat()
+ return parsed.replace(tzinfo=UTC).isoformat()
return text
diff --git a/services/agents/tests/fidelity/runner.py b/services/agents/tests/fidelity/runner.py
index e0bfd1cd0..7a7eee68d 100644
--- a/services/agents/tests/fidelity/runner.py
+++ b/services/agents/tests/fidelity/runner.py
@@ -224,10 +224,7 @@ class FidelityResult:
"rows_skipped": self.rows_skipped,
"accuracy": round(self.accuracy, 4),
"macro_f1": round(self.macro_f1, 4),
- "per_family": {
- family: {k: round(v, 4) for k, v in metrics.items()}
- for family, metrics in self.per_family.items()
- },
+ "per_family": {family: {k: round(v, 4) for k, v in metrics.items()} for family, metrics in self.per_family.items()},
"confusion_matrix": self.confusion_matrix,
}
@@ -243,23 +240,11 @@ def _per_family_metrics(cm: ConfusionMatrix) -> dict[str, dict[str, float]]:
out: dict[str, dict[str, float]] = {}
for label in cm.labels:
tp = cm.matrix.get(label, {}).get(label, 0)
- fp = sum(
- cm.matrix.get(other, {}).get(label, 0)
- for other in cm.labels
- if other != label
- )
- fn = sum(
- cm.matrix.get(label, {}).get(other, 0)
- for other in cm.labels
- if other != label
- )
+ fp = sum(cm.matrix.get(other, {}).get(label, 0) for other in cm.labels if other != label)
+ fn = sum(cm.matrix.get(label, {}).get(other, 0) for other in cm.labels if other != label)
precision = tp / (tp + fp) if (tp + fp) else 0.0
recall = tp / (tp + fn) if (tp + fn) else 0.0
- f1 = (
- 2 * precision * recall / (precision + recall)
- if (precision + recall)
- else 0.0
- )
+ f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
support = tp + fn
out[label] = {
"precision": precision,
@@ -352,9 +337,7 @@ def evaluate(
ocsf_event = _to_ocsf(dataset, row)
if mode == "wet":
if not endpoint:
- raise RuntimeError(
- "wet mode requires --wet-endpoint or AISOC_WET_EVAL_ENDPOINT"
- )
+ raise RuntimeError("wet mode requires --wet-endpoint or AISOC_WET_EVAL_ENDPOINT")
predicted = _classify_wet(ocsf_event, endpoint)
else:
predicted = classifier(row)
diff --git a/services/agents/tests/smoke_explain.py b/services/agents/tests/smoke_explain.py
index e0e4c4c05..691251976 100644
--- a/services/agents/tests/smoke_explain.py
+++ b/services/agents/tests/smoke_explain.py
@@ -33,7 +33,7 @@ os.environ.pop("OPENAI_API_KEY", None)
os.environ["AISOC_AIRGAPPED"] = "true"
from app.api.explain import ExplainRequest, _stream_explanation # noqa: E402
-from app.security.llm_resolver import LlmConfig
+from app.security.llm_resolver import LlmConfig # noqa: E402
SAMPLE_ALERT: dict[str, Any] = {
"id": "ALERT-SMOKE-0001",
diff --git a/services/agents/tests/test_confidence_calibration.py b/services/agents/tests/test_confidence_calibration.py
index 6e914f07c..d50e890eb 100644
--- a/services/agents/tests/test_confidence_calibration.py
+++ b/services/agents/tests/test_confidence_calibration.py
@@ -103,9 +103,9 @@ _DATASET_PATH = _TESTS_DIR / "eval_data" / "synthetic_incidents.json"
with _DATASET_PATH.open() as _f:
_POSITIVE_INCIDENTS: list[dict[str, Any]] = json.load(_f)
-assert len(_POSITIVE_INCIDENTS) >= 100, (
- f"synthetic_incidents.json must contain at least 100 cases for stable calibration (got {len(_POSITIVE_INCIDENTS)})"
-)
+assert (
+ len(_POSITIVE_INCIDENTS) >= 100
+), f"synthetic_incidents.json must contain at least 100 cases for stable calibration (got {len(_POSITIVE_INCIDENTS)})"
# ---------------------------------------------------------------------------
diff --git a/services/agents/tests/test_context_bundle.py b/services/agents/tests/test_context_bundle.py
index 566e1ee80..64fef2f3c 100644
--- a/services/agents/tests/test_context_bundle.py
+++ b/services/agents/tests/test_context_bundle.py
@@ -63,8 +63,7 @@ _BUILD_P95_LATENCY_S = 5.0
def _load_dataset() -> list[dict[str, Any]]:
if not _DATASET_PATH.exists():
raise FileNotFoundError(
- f"Eval dataset missing at {_DATASET_PATH}. "
- "Run `python3 scripts/generate_eval_incidents.py` to regenerate."
+ f"Eval dataset missing at {_DATASET_PATH}. " "Run `python3 scripts/generate_eval_incidents.py` to regenerate."
)
with _DATASET_PATH.open() as f:
return json.load(f)
@@ -120,9 +119,7 @@ async def _stub_blast(*_args: Any, **_kwargs: Any) -> dict[str, Any]:
async def _stub_bulk_enrich(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
# Echo the items back with a low-risk reputation so the threat-intel
# branch of the bundle exercises its post-processing path.
- return [
- {**item, "risk_score": 0.0, "sources": ["stub"]} for item in items[:32]
- ]
+ return [{**item, "risk_score": 0.0, "sources": ["stub"]} for item in items[:32]]
async def _stub_institutional_search(*_args: Any, **_kwargs: Any) -> list[dict[str, Any]]:
@@ -149,7 +146,7 @@ class _FakeUEBAClient:
self._args = args
self._kwargs = kwargs
- async def __aenter__(self) -> "_FakeUEBAClient":
+ async def __aenter__(self) -> _FakeUEBAClient:
return self
async def __aexit__(self, *args: Any) -> None:
@@ -282,9 +279,7 @@ class ContextBundleBuildLatencyTests(unittest.TestCase):
)
@staticmethod
- async def _run_all(
- fn: Any, incidents: list[dict[str, Any]]
- ) -> list[tuple[ContextBundle, float]]:
+ async def _run_all(fn: Any, incidents: list[dict[str, Any]]) -> list[tuple[ContextBundle, float]]:
# Fan-out is bounded so a hung incident can't cascade across the
# whole 200-case sweep. ``asyncio.gather`` keeps order.
return list(await asyncio.gather(*[fn(inc) for inc in incidents]))
diff --git a/services/agents/tests/test_eval_telemetry.py b/services/agents/tests/test_eval_telemetry.py
index adc239f80..d0b86a341 100644
--- a/services/agents/tests/test_eval_telemetry.py
+++ b/services/agents/tests/test_eval_telemetry.py
@@ -147,9 +147,7 @@ class RateCardTests(unittest.TestCase):
crash. Keeps wet-eval re-rendering robust if the rate card is
renamed mid-run."""
unknown = _eval_telemetry.cost_usd(1_000_000, 0, model="not-a-real-model")
- gpt4o = _eval_telemetry.cost_usd(
- 1_000_000, 0, model=_eval_telemetry.DEFAULT_MODEL
- )
+ gpt4o = _eval_telemetry.cost_usd(1_000_000, 0, model=_eval_telemetry.DEFAULT_MODEL)
self.assertAlmostEqual(unknown, gpt4o, places=6)
def test_cost_usd_accepts_custom_rate_card(self) -> None:
@@ -205,14 +203,18 @@ class ComputePerInvestigationTests(unittest.TestCase):
wet-eval column (workspace rule: never present substrate as
agent metrics)."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=True,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=True,
)
d = rep.to_dict(include_records=True)
self.assertEqual(d["mode"], "deterministic_substrate")
def test_report_counts_incidents_and_templates(self) -> None:
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=True,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=True,
)
self.assertEqual(rep.incidents, 3)
self.assertEqual(rep.templates, 2)
@@ -220,7 +222,9 @@ class ComputePerInvestigationTests(unittest.TestCase):
def test_report_aggregate_has_required_fields(self) -> None:
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=True,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=True,
)
agg = rep.aggregate
self.assertIn("tokens", agg)
@@ -236,7 +240,9 @@ class ComputePerInvestigationTests(unittest.TestCase):
percentile helper this catches it before docs ship a chart with
p99 < median."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=True,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=True,
)
for kind in ("prompt", "completion", "total"):
block = rep.aggregate["tokens"][kind]
@@ -254,7 +260,9 @@ class ComputePerInvestigationTests(unittest.TestCase):
low-severity ones. INC-FIXT-001 (critical) vs INC-FIXT-003 (low)
in the fixture."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=True,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=True,
)
by_id = {r["incident_id"]: r for r in rep.incident_records}
self.assertGreater(
@@ -264,7 +272,9 @@ class ComputePerInvestigationTests(unittest.TestCase):
def test_keep_records_false_drops_per_incident_array(self) -> None:
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=False,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=False,
)
self.assertEqual(rep.incident_records, [])
d = rep.to_dict(include_records=False)
@@ -275,7 +285,9 @@ class ComputePerInvestigationTests(unittest.TestCase):
incident count. Stops bucketing bugs from quietly dropping
templates."""
rep = _eval_telemetry.compute_per_investigation_telemetry(
- self.incidents_path, model="gpt-4o", keep_records=True,
+ self.incidents_path,
+ model="gpt-4o",
+ keep_records=True,
)
total = sum(t["incidents"] for t in rep.per_template)
self.assertEqual(total, rep.incidents)
@@ -303,18 +315,24 @@ def _build_renderable_report() -> dict[str, Any]:
usd = block["aggregate"]["usd"]
latency = block["aggregate"]["latency_ms"]
block["tokens_per_investigation"] = {
- "mean": total["mean"], "median": total["median"],
- "p95": total["p95"], "p99": total["p99"],
+ "mean": total["mean"],
+ "median": total["median"],
+ "p95": total["p95"],
+ "p99": total["p99"],
"prompt_mean": block["aggregate"]["tokens"]["prompt"]["mean"],
"completion_mean": block["aggregate"]["tokens"]["completion"]["mean"],
}
block["usd_per_investigation"] = {
- "mean": usd["mean"], "median": usd["median"],
- "p95": usd["p95"], "p99": usd["p99"],
+ "mean": usd["mean"],
+ "median": usd["median"],
+ "p95": usd["p95"],
+ "p99": usd["p99"],
}
block["latency_per_investigation_ms"] = {
- "p50": latency["p50"], "p95": latency["p95"],
- "p99": latency["p99"], "mean": latency["mean"],
+ "p50": latency["p50"],
+ "p95": latency["p95"],
+ "p99": latency["p99"],
+ "mean": latency["mean"],
}
return {"per_investigation": block}
diff --git a/services/agents/tests/test_explain_endpoint.py b/services/agents/tests/test_explain_endpoint.py
index 899442aa6..b007fbabc 100644
--- a/services/agents/tests/test_explain_endpoint.py
+++ b/services/agents/tests/test_explain_endpoint.py
@@ -164,9 +164,9 @@ def test_explain_streams_grounded_ndjson(monkeypatch: pytest.MonkeyPatch) -> Non
# Evidence surfaces the offending user from rawEvent.
evidence = [f for f in frames if f["kind"] == "evidence"]
- assert any("alice.tan" in e["value"] for e in evidence), (
- f"evidence missing user from rawEvent: {[(e['label'], e['value']) for e in evidence]}"
- )
+ assert any(
+ "alice.tan" in e["value"] for e in evidence
+ ), f"evidence missing user from rawEvent: {[(e['label'], e['value']) for e in evidence]}"
def test_explain_uses_default_tenant_when_omitted(
diff --git a/services/agents/tests/test_fidelity_harness.py b/services/agents/tests/test_fidelity_harness.py
index 03b86e9e2..97735e5ac 100644
--- a/services/agents/tests/test_fidelity_harness.py
+++ b/services/agents/tests/test_fidelity_harness.py
@@ -36,12 +36,8 @@ import pytest
from tests.fidelity import cicids_loader, ctu13_loader, runner
REPO_ROOT = Path(__file__).resolve().parents[3]
-MICRO_FIXTURE = (
- REPO_ROOT / "services/agents/tests/eval_data/cicids_micro.csv"
-)
-EXPECTED_RESULTS = (
- REPO_ROOT / "services/agents/tests/fidelity/expected_results.yaml"
-)
+MICRO_FIXTURE = REPO_ROOT / "services/agents/tests/eval_data/cicids_micro.csv"
+EXPECTED_RESULTS = REPO_ROOT / "services/agents/tests/fidelity/expected_results.yaml"
def _load_expected() -> dict[str, object]:
@@ -256,9 +252,7 @@ def test_wet_mode_falls_back_to_benign_on_http_failure(
# is defensive on transport errors.
assert result.rows_scored == 2
benign_predicted = sum(
- cell.get("benign", 0)
- for actual, cell in result.confusion_matrix["matrix"].items()
- if actual in result.confusion_matrix["labels"]
+ cell.get("benign", 0) for actual, cell in result.confusion_matrix["matrix"].items() if actual in result.confusion_matrix["labels"]
)
assert benign_predicted == 2
diff --git a/services/agents/tests/test_four_agent_facade.py b/services/agents/tests/test_four_agent_facade.py
index 3d57c04f0..1b2ab4794 100644
--- a/services/agents/tests/test_four_agent_facade.py
+++ b/services/agents/tests/test_four_agent_facade.py
@@ -48,7 +48,6 @@ from app.agents import ( # noqa: E402
)
from app.models.state import AgentStatus, InvestigationState # noqa: E402
-
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -119,9 +118,7 @@ def test_triage_capabilities_are_not_top_level_agents() -> None:
# And the package's "branded" set must only contain the four names.
branded_in_pkg = {
- name
- for name in agents_pkg.__all__
- if name.endswith("Agent") and name not in {"AutoTriageAgent", "ResponderAgent"} | forbidden
+ name for name in agents_pkg.__all__ if name.endswith("Agent") and name not in {"AutoTriageAgent", "ResponderAgent"} | forbidden
}
assert branded_in_pkg == branded
diff --git a/services/agents/tests/test_graph_freshness.py b/services/agents/tests/test_graph_freshness.py
index d5f01bfd8..a8d66938b 100644
--- a/services/agents/tests/test_graph_freshness.py
+++ b/services/agents/tests/test_graph_freshness.py
@@ -44,9 +44,7 @@ pytestmark = pytest.mark.integration
# Test config — env-overridable so CI can point at the dockerised stack.
INGEST_BASE_URL = os.environ.get("AISOC_INGEST_URL", "http://localhost:8080")
-KAFKA_BOOTSTRAP = os.environ.get(
- "KAFKA_BOOTSTRAP_SERVERS", os.environ.get("KAFKA_BROKERS", "localhost:9092")
-)
+KAFKA_BOOTSTRAP = os.environ.get("KAFKA_BOOTSTRAP_SERVERS", os.environ.get("KAFKA_BROKERS", "localhost:9092"))
NEO4J_URI = os.environ.get("AISOC_NEO4J_URI", "bolt://localhost:7687")
NEO4J_USER = os.environ.get("AISOC_NEO4J_USER", "neo4j")
NEO4J_PASSWORD = os.environ.get("AISOC_NEO4J_PASSWORD", "neo4j")
@@ -65,9 +63,7 @@ def _import_or_skip(mod_name: str, hint: str) -> Any:
try:
return __import__(mod_name)
except ImportError:
- pytest.skip(
- f"{mod_name} not installed locally — install {hint} to run this integration test"
- )
+ pytest.skip(f"{mod_name} not installed locally — install {hint} to run this integration test")
return None # unreachable; pytest.skip raises, but keeps return paths consistent
@@ -144,9 +140,7 @@ def test_graph_freshness_p95_under_2s() -> None:
tenant = f"test-{uuid.uuid4().hex[:8]}"
try:
- driver = neo4j_pkg.GraphDatabase.driver(
- NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD)
- )
+ driver = neo4j_pkg.GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
driver.verify_connectivity()
except Exception as exc: # noqa: BLE001
pytest.skip(f"Neo4j unreachable at {NEO4J_URI}: {exc}")
@@ -178,9 +172,7 @@ def test_graph_freshness_p95_under_2s() -> None:
}
)
)
- assert p95 < P95_LATENCY_BUDGET_S, (
- f"graph freshness p95={p95:.3f}s exceeds budget {P95_LATENCY_BUDGET_S}s"
- )
+ assert p95 < P95_LATENCY_BUDGET_S, f"graph freshness p95={p95:.3f}s exceeds budget {P95_LATENCY_BUDGET_S}s"
def test_graph_writer_does_not_block_fusion_on_failure() -> None:
@@ -215,9 +207,7 @@ def test_graph_writer_does_not_block_fusion_on_failure() -> None:
pytest.skip(f"ingest service unreachable at {INGEST_BASE_URL}: {exc}")
return # CodeQL doesn't model ``pytest.skip`` as terminating
- assert resp.status_code < 400, (
- f"ingest returned {resp.status_code} — fusion should never block on graph: {resp.text}"
- )
+ assert resp.status_code < 400, f"ingest returned {resp.status_code} — fusion should never block on graph: {resp.text}"
# TODO(T1.1+): expand to the 360-event synthetic corpus referenced in the
diff --git a/services/agents/tests/test_latency.py b/services/agents/tests/test_latency.py
index c92caa6a4..4a0db6b61 100644
--- a/services/agents/tests/test_latency.py
+++ b/services/agents/tests/test_latency.py
@@ -179,9 +179,5 @@ async def test_parallel_topology_latency_substrate(monkeypatch: pytest.MonkeyPat
f"\n budget: p50 < {P50_BUDGET_SECONDS*1000:.0f} ms, p95 < {P95_BUDGET_SECONDS*1000:.0f} ms (substrate)"
)
- assert p50_ms < P50_BUDGET_SECONDS * 1000.0, (
- f"p50 substrate latency over budget: {p50_ms:.2f} ms >= {P50_BUDGET_SECONDS*1000:.0f} ms"
- )
- assert p95_ms < P95_BUDGET_SECONDS * 1000.0, (
- f"p95 substrate latency over budget: {p95_ms:.2f} ms >= {P95_BUDGET_SECONDS*1000:.0f} ms"
- )
+ assert p50_ms < P50_BUDGET_SECONDS * 1000.0, f"p50 substrate latency over budget: {p50_ms:.2f} ms >= {P50_BUDGET_SECONDS*1000:.0f} ms"
+ assert p95_ms < P95_BUDGET_SECONDS * 1000.0, f"p95 substrate latency over budget: {p95_ms:.2f} ms >= {P95_BUDGET_SECONDS*1000:.0f} ms"
diff --git a/services/agents/tests/test_llm_contract.py b/services/agents/tests/test_llm_contract.py
index 0e2c31d05..3ca2ca09c 100644
--- a/services/agents/tests/test_llm_contract.py
+++ b/services/agents/tests/test_llm_contract.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import json
import pytest
-
from app.llm.contract import (
LLMContractViolation,
LLMInputContract,
@@ -48,9 +47,7 @@ def test_validate_messages_accepts_summarized_structure(contract_enforced) -> No
"display_name": "Alice",
"risk": {"score": 42},
}
- body = summarize_structure_for_llm(
- entity, label="entity_snapshot", max_lines=80, max_depth=3
- )
+ body = summarize_structure_for_llm(entity, label="entity_snapshot", max_lines=80, max_depth=3)
msgs = [
{"role": "system", "content": "You are a security analyst."},
{"role": "user", "content": body},
diff --git a/services/agents/tests/test_nl_query_eval.py b/services/agents/tests/test_nl_query_eval.py
index 09cfacd37..7294f5fea 100644
--- a/services/agents/tests/test_nl_query_eval.py
+++ b/services/agents/tests/test_nl_query_eval.py
@@ -34,7 +34,7 @@ def _load_dataset() -> dict:
def _normalise_filters(items) -> set[tuple[str, str, str]]:
- return {(f, op, v) for f, op, v in items}
+ return set(items)
def _semantic_score(expected: dict, actual: QueryIntents) -> tuple[float, list[str]]:
diff --git a/services/api/app/_vendor/nl_query/translator.py b/services/api/app/_vendor/nl_query/translator.py
index b706914c2..2e8d6ca2b 100644
--- a/services/api/app/_vendor/nl_query/translator.py
+++ b/services/api/app/_vendor/nl_query/translator.py
@@ -267,23 +267,19 @@ _TIME_REGEX_SINGULAR = re.compile(
# boundary so we don't drag the rest of the question into the field name.
_NUMERIC_AGG_PATTERNS: list[tuple[str, str]] = [
(
- r"\b(?:average|avg|mean)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:average|avg|mean)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"AVG",
),
(
- r"\b(?:sum(?:\s+of)?|total(?:\s+of)?)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:sum(?:\s+of)?|total(?:\s+of)?)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"SUM",
),
(
- r"\b(?:max|maximum|largest|highest)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:max|maximum|largest|highest)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"MAX",
),
(
- r"\b(?:min|minimum|lowest|smallest)\s+([a-z][a-z _\.]+?)"
- r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
+ r"\b(?:min|minimum|lowest|smallest)\s+([a-z][a-z _\.]+?)" r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",
"MIN",
),
]
@@ -598,8 +594,7 @@ def _extract_aggregations(question: str, intents: QueryIntents) -> None:
# next clause boundary (``with``, ``having``, ``in the last 24h`` etc.)
# without dragging the whole tail of the question into the field name.
for m in re.finditer(
- r"\b(?:unique|distinct)\s+([a-z _]+?)"
- r"(?=\b(?:by|per|in|over|with|where|having|from|and|,|$))",
+ r"\b(?:unique|distinct)\s+([a-z _]+?)" r"(?=\b(?:by|per|in|over|with|where|having|from|and|,|$))",
text + " ,",
):
candidate = m.group(1).strip().rstrip(",")
diff --git a/services/api/app/api/v1/endpoints/attack_chain.py b/services/api/app/api/v1/endpoints/attack_chain.py
index 23f665e7c..118d92fac 100644
--- a/services/api/app/api/v1/endpoints/attack_chain.py
+++ b/services/api/app/api/v1/endpoints/attack_chain.py
@@ -68,11 +68,7 @@ async def get_attack_chain(
# but a future schema change could relax that — fail closed.
raise HTTPException(status_code=400, detail=f"unknown window: {window}")
- case_row = (
- await db.execute(
- select(Case).where(Case.id == case_id, Case.tenant_id == user.tenant_id)
- )
- ).scalar_one_or_none()
+ case_row = (await db.execute(select(Case).where(Case.id == case_id, Case.tenant_id == user.tenant_id))).scalar_one_or_none()
if case_row is None:
raise HTTPException(status_code=404, detail="case_not_found")
@@ -82,10 +78,7 @@ async def get_attack_chain(
# case still resolves.
seed_alert_id: uuid.UUID | None = None
if case_row.alert_ids:
- candidate_ids = [
- uuid.UUID(str(a)) if not isinstance(a, uuid.UUID) else a
- for a in case_row.alert_ids
- ]
+ candidate_ids = [uuid.UUID(str(a)) if not isinstance(a, uuid.UUID) else a for a in case_row.alert_ids]
seed_row = (
await db.execute(
select(Alert)
diff --git a/services/api/app/api/v1/endpoints/business_context.py b/services/api/app/api/v1/endpoints/business_context.py
index 2a694dc4f..edd419a97 100644
--- a/services/api/app/api/v1/endpoints/business_context.py
+++ b/services/api/app/api/v1/endpoints/business_context.py
@@ -97,7 +97,7 @@ class RuleConditionWire(BaseModel):
op: str | None = None
value: Any = None
logical: str | None = None
- children: list["RuleConditionWire"] = Field(default_factory=list)
+ children: list[RuleConditionWire] = Field(default_factory=list)
class RuleActionWire(BaseModel):
@@ -455,10 +455,7 @@ async def update_rule(
if new_rule.id != rule_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
- detail=(
- f"rule id in URL ({rule_id!r}) must match rule id in body "
- f"({new_rule.id!r})"
- ),
+ detail=(f"rule id in URL ({rule_id!r}) must match rule id in body " f"({new_rule.id!r})"),
)
existing_yaml = _load_for(user.tenant_id)["yaml"]
@@ -553,9 +550,7 @@ async def preview_rules(
alerts = alerts[:_MAX_PREVIEW_ALERTS]
start = time.perf_counter()
- evaluations = _engine().preview_against(
- user.tenant_id, alerts, rules=rules
- )
+ evaluations = _engine().preview_against(user.tenant_id, alerts, rules=rules)
elapsed_ms = (time.perf_counter() - start) * 1000
rows = [
diff --git a/services/api/app/api/v1/endpoints/effective_permissions.py b/services/api/app/api/v1/endpoints/effective_permissions.py
index a61ec86ff..3ce122146 100644
--- a/services/api/app/api/v1/endpoints/effective_permissions.py
+++ b/services/api/app/api/v1/endpoints/effective_permissions.py
@@ -87,8 +87,7 @@ async def get_effective_permissions(
snapshot_b64: str | None = Query(
None,
description=(
- "Optional base64-encoded JSON snapshot for dry-run resolution. "
- "Only honoured when AISOC_ALLOW_INLINE_SNAPSHOT=1 is set."
+ "Optional base64-encoded JSON snapshot for dry-run resolution. " "Only honoured when AISOC_ALLOW_INLINE_SNAPSHOT=1 is set."
),
),
_user: User = Depends(get_current_user),
@@ -102,10 +101,7 @@ async def get_effective_permissions(
if provider not in SUPPORTED_PROVIDERS:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
- detail=(
- f"unknown provider {provider!r}; "
- f"supported: {sorted(SUPPORTED_PROVIDERS)}"
- ),
+ detail=(f"unknown provider {provider!r}; " f"supported: {sorted(SUPPORTED_PROVIDERS)}"),
)
snapshot: dict[str, Any] | None = None
@@ -113,8 +109,7 @@ async def get_effective_permissions(
if os.getenv(_INLINE_SNAPSHOT_FLAG, "0") != "1":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
- detail="inline snapshots are disabled; set "
- f"{_INLINE_SNAPSHOT_FLAG}=1 to dry-run.",
+ detail="inline snapshots are disabled; set " f"{_INLINE_SNAPSHOT_FLAG}=1 to dry-run.",
)
try:
snapshot = json.loads(base64.b64decode(snapshot_b64).decode("utf-8"))
diff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.py
index 1534a44d6..46f4f04a0 100644
--- a/services/api/app/api/v1/endpoints/health.py
+++ b/services/api/app/api/v1/endpoints/health.py
@@ -185,7 +185,7 @@ async def _ingest_stage(db, tenant_id, *, now: datetime) -> PipelineStage:
override: int | None = None
if isinstance(r.connector_config, dict):
raw_override = r.connector_config.get("expected_cadence_seconds")
- if isinstance(raw_override, (int, float)) and raw_override > 0:
+ if isinstance(raw_override, int | float) and raw_override > 0:
override = int(raw_override)
verdict = compute_freshness(
category=r.category,
diff --git a/services/api/app/api/v1/endpoints/insights.py b/services/api/app/api/v1/endpoints/insights.py
index b08296403..1fedd624a 100644
--- a/services/api/app/api/v1/endpoints/insights.py
+++ b/services/api/app/api/v1/endpoints/insights.py
@@ -117,10 +117,7 @@ class InsightTile(BaseModel):
)
)
previous_value: float = Field(
- description=(
- "Value of the same metric over the immediately preceding "
- "window of equal length. Used to compute the delta."
- )
+ description=("Value of the same metric over the immediately preceding " "window of equal length. Used to compute the delta.")
)
delta_pct: float | None = Field(
default=None,
@@ -188,9 +185,7 @@ async def _mean_hours(
end_col.isnot(None),
]
filters.extend(extra_filters)
- result = await db.scalar(
- select(func.avg(func.extract("epoch", end_col - start_col) / 3600)).where(and_(*filters))
- )
+ result = await db.scalar(select(func.avg(func.extract("epoch", end_col - start_col) / 3600)).where(and_(*filters)))
return round(float(result or 0.0), 2)
@@ -320,11 +315,15 @@ async def _llm_cost_aggregate(
)
try:
row = (
- await db.execute(
- sql,
- {"tenant_id": str(tenant_id), "start_at": start, "end_at": end},
+ (
+ await db.execute(
+ sql,
+ {"tenant_id": str(tenant_id), "start_at": start, "end_at": end},
+ )
)
- ).mappings().first()
+ .mappings()
+ .first()
+ )
if not row:
return 0.0, 0
return float(row["cost"] or 0.0), int(row["runs"] or 0)
diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.py
index 4c515d4ef..a72f324bd 100644
--- a/services/api/app/api/v1/endpoints/metrics.py
+++ b/services/api/app/api/v1/endpoints/metrics.py
@@ -292,11 +292,7 @@ async def get_dashboard_metrics(
# jsonb_array_elements_text + GROUP BY in the same SELECT 500s on some
# Postgres builds.
tactic_rows = (
- await db.execute(
- select(Alert.mitre_tactics).where(
- and_(Alert.tenant_id == tenant_id, Alert.mitre_tactics.isnot(None))
- )
- )
+ await db.execute(select(Alert.mitre_tactics).where(and_(Alert.tenant_id == tenant_id, Alert.mitre_tactics.isnot(None))))
).all()
tactic_counts: dict[str, int] = {}
@@ -308,8 +304,7 @@ async def get_dashboard_metrics(
tactic_counts[t] = tactic_counts.get(t, 0) + 1
top_mitre = [
- MitreTactic(tactic=tactic, count=count)
- for tactic, count in sorted(tactic_counts.items(), key=lambda x: x[1], reverse=True)[:10]
+ MitreTactic(tactic=tactic, count=count) for tactic, count in sorted(tactic_counts.items(), key=lambda x: x[1], reverse=True)[:10]
]
# ── 24-hour trend (hourly buckets) ────────────────────────────────────────
@@ -582,9 +577,7 @@ async def get_soc_metrics(
heatmap = [
AttackHeatmapCell(tactic=tactic, technique=technique, count=count)
- for (tactic, technique), count in sorted(
- pair_counts.items(), key=lambda x: x[1], reverse=True
- )[:50]
+ for (tactic, technique), count in sorted(pair_counts.items(), key=lambda x: x[1], reverse=True)[:50]
]
# ── Confidence calibration curve ──────────────────────────────────────────
diff --git a/services/api/app/api/v1/endpoints/oauth.py b/services/api/app/api/v1/endpoints/oauth.py
index 576c57546..582a321f0 100644
--- a/services/api/app/api/v1/endpoints/oauth.py
+++ b/services/api/app/api/v1/endpoints/oauth.py
@@ -994,7 +994,7 @@ async def oauth_callback(
# Compute an absolute expires_at so the auto-refresh worker
# (Workstream 5) doesn't have to track when we received the token.
expires_in = token_payload.get("expires_in")
- if isinstance(expires_in, (int, float)) and expires_in > 0:
+ if isinstance(expires_in, int | float) and expires_in > 0:
auth_payload["expires_at"] = (datetime.now(UTC) + timedelta(seconds=int(expires_in))).isoformat()
try:
diff --git a/services/api/app/api/v1/endpoints/saved_hunts.py b/services/api/app/api/v1/endpoints/saved_hunts.py
index c239f2e0a..40110a39b 100644
--- a/services/api/app/api/v1/endpoints/saved_hunts.py
+++ b/services/api/app/api/v1/endpoints/saved_hunts.py
@@ -51,8 +51,6 @@ from sqlalchemy import and_, delete, select, update
from sqlalchemy.exc import IntegrityError
from app.api.v1.deps import AuthUser
-from app.db.rls import TenantDBSession
-from app.models.saved_hunt import SavedHunt
# Defer import of the NL translator helpers — `nl_query.py` already does the
# vendored-tree resolution dance at import time and we want the same module
@@ -60,6 +58,8 @@ from app.models.saved_hunt import SavedHunt
from app.api.v1.endpoints.nl_query import ( # noqa: E402
deterministic_translate,
)
+from app.db.rls import TenantDBSession
+from app.models.saved_hunt import SavedHunt
logger = structlog.get_logger()
@@ -270,13 +270,7 @@ async def list_saved_hunts(
first; the UI renders this list as the "Saved hunts" sidebar.
"""
rows = (
- (
- await db.execute(
- select(SavedHunt)
- .where(SavedHunt.tenant_id == user.tenant_id)
- .order_by(SavedHunt.updated_at.desc())
- )
- )
+ (await db.execute(select(SavedHunt).where(SavedHunt.tenant_id == user.tenant_id).order_by(SavedHunt.updated_at.desc())))
.scalars()
.all()
)
diff --git a/services/api/app/api/v1/endpoints/tenant_provision.py b/services/api/app/api/v1/endpoints/tenant_provision.py
index 66ee23ca6..1591b0148 100644
--- a/services/api/app/api/v1/endpoints/tenant_provision.py
+++ b/services/api/app/api/v1/endpoints/tenant_provision.py
@@ -41,8 +41,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.deps import AuthUser, DBSession
from app.models.tenant import Tenant
from app.services.tenant_provision import (
- ProvisionResult,
ProvisioningError,
+ ProvisionResult,
SlugCollisionError,
WaitlistEntryNotFoundError,
WaitlistEntryNotPromotableError,
@@ -185,9 +185,7 @@ def _tenant_to_wire(row: Tenant) -> TenantListEntry:
plan=row.plan or "starter",
is_active=bool(row.is_active),
is_managed=bool(settings_blob.get("managed", False)),
- provisioned_from_waitlist_id=settings_blob.get(
- "provisioned_from_waitlist_id"
- ),
+ provisioned_from_waitlist_id=settings_blob.get("provisioned_from_waitlist_id"),
provisioned_at=settings_blob.get("provisioned_at"),
created_at=row.created_at.isoformat() if row.created_at else "",
)
diff --git a/services/api/app/api/v1/endpoints/waitlist.py b/services/api/app/api/v1/endpoints/waitlist.py
index 573294f3e..ff48497d7 100644
--- a/services/api/app/api/v1/endpoints/waitlist.py
+++ b/services/api/app/api/v1/endpoints/waitlist.py
@@ -229,9 +229,7 @@ class WaitlistPatchRequest(BaseModel):
def _validate_status(cls, value: str) -> str:
v = value.strip().lower()
if v not in ALLOWED_WAITLIST_STATUSES:
- raise ValueError(
- f"status must be one of: {sorted(ALLOWED_WAITLIST_STATUSES)}"
- )
+ raise ValueError(f"status must be one of: {sorted(ALLOWED_WAITLIST_STATUSES)}")
return v
@@ -269,9 +267,7 @@ def _to_wire(row: WaitlistEntry) -> WaitlistEntryWire:
soc_stack=list(row.soc_stack or []),
motivation=row.motivation,
status=row.status,
- provisioned_tenant_id=(
- str(row.provisioned_tenant_id) if row.provisioned_tenant_id else None
- ),
+ provisioned_tenant_id=(str(row.provisioned_tenant_id) if row.provisioned_tenant_id else None),
created_at=row.created_at.isoformat(),
contacted_at=row.contacted_at.isoformat() if row.contacted_at else None,
onboarded_at=row.onboarded_at.isoformat() if row.onboarded_at else None,
@@ -333,9 +329,7 @@ async def signup(
# path — only the admin PATCH endpoint moves an entry off ``new``.
entry: WaitlistEntry | None = None
try:
- existing = (
- await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))
- ).scalar_one_or_none()
+ existing = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))).scalar_one_or_none()
if existing is not None:
return WaitlistSignupResponse(entry_id=str(existing.id))
@@ -354,9 +348,7 @@ async def signup(
# Race: another request inserted between SELECT and commit.
# Treat as idempotent success and look the row back up.
await db.rollback()
- existing = (
- await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))
- ).scalar_one_or_none()
+ existing = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.email == payload.email))).scalar_one_or_none()
if existing is not None:
return WaitlistSignupResponse(entry_id=str(existing.id))
# If we still can't find it, fall through to a generic success
@@ -437,13 +429,9 @@ async def patch_entry(
user: AuthUser,
) -> WaitlistEntryWire:
await _require_admin(user, db)
- row = (
- await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))
- ).scalar_one_or_none()
+ row = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))).scalar_one_or_none()
if row is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND, detail="waitlist_entry_not_found"
- )
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="waitlist_entry_not_found")
now = datetime.now(UTC)
previous = row.status
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 4877afb80..27930e33f 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -246,9 +246,7 @@ class Settings(BaseSettings):
# ------------------------------------------------------------------
HUNT_SCHEDULER_ENABLED: bool = Field(
default=False,
- validation_alias=AliasChoices(
- "HUNT_SCHEDULER_ENABLED", "AISOC_HUNT_SCHEDULER_ENABLED"
- ),
+ validation_alias=AliasChoices("HUNT_SCHEDULER_ENABLED", "AISOC_HUNT_SCHEDULER_ENABLED"),
)
HUNT_SCHEDULER_POLL_INTERVAL_SECONDS: int = 30
diff --git a/services/api/app/main.py b/services/api/app/main.py
index a4d78b8df..73853f445 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -133,9 +133,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
hunt_scheduler_task: asyncio.Task | None = None
if settings.HUNT_SCHEDULER_ENABLED:
try:
- hunt_scheduler_task = asyncio.create_task(
- run_hunt_scheduler(), name="hunt_scheduler_worker"
- )
+ hunt_scheduler_task = asyncio.create_task(run_hunt_scheduler(), name="hunt_scheduler_worker")
logger.info("hunt_scheduler worker started")
except Exception as exc:
logger.warning("hunt_scheduler worker failed to start", error=str(exc))
diff --git a/services/api/app/models/waitlist.py b/services/api/app/models/waitlist.py
index d841f8391..786299430 100644
--- a/services/api/app/models/waitlist.py
+++ b/services/api/app/models/waitlist.py
@@ -39,7 +39,6 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.db.database import Base
-
# Status ladder. Kept in sync with the CHECK constraint in
# ``migrations/042_waitlist.sql`` — adding a new state requires both an
# entry here AND a migration to widen the constraint.
@@ -73,11 +72,7 @@ class WaitlistEntry(Base):
# ForeignKey here so the import graph stays free of circular deps
# with the tenant model; the migration adds the actual FK at the
# database layer.
- provisioned_tenant_id: Mapped[uuid.UUID | None] = mapped_column(
- UUID(as_uuid=True), nullable=True, index=True
- )
- created_at: Mapped[datetime] = mapped_column(
- DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False
- )
+ provisioned_tenant_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True, index=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False)
contacted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
onboarded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index c5bb77af5..995e7bdf7 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -2410,6 +2410,7 @@ _DEMO_QUICK_DEFAULT_CLOCK_ISO = "2026-05-13T19:00:00+00:00"
# The constant has no security meaning — it's just a fixed seed.
_DEMO_QUICK_UUID_NS = uuid.UUID("a15a1c00-0000-4d04-8000-000000000064")
+
def _parse_clock(value: str | None) -> datetime:
"""Parse the `--clock` argument (ISO-8601) into a UTC-aware datetime.
@@ -2939,16 +2940,11 @@ async def _seed_demo_quick_connectors(
created = 0
for connector_type in sorted(needed):
existing = await session.execute(
- select(Connector)
- .where(Connector.tenant_id == tenant.id)
- .where(Connector.connector_type == connector_type)
- .limit(1)
+ select(Connector).where(Connector.tenant_id == tenant.id).where(Connector.connector_type == connector_type).limit(1)
)
if existing.scalar_one_or_none() is not None:
continue
- display, category = _DEMO_QUICK_CONNECTOR_PROFILES.get(
- connector_type, (connector_type, "siem")
- )
+ display, category = _DEMO_QUICK_CONNECTOR_PROFILES.get(connector_type, (connector_type, "siem"))
session.add(
Connector(
id=_demo_quick_uuid("connector", connector_type),
@@ -2979,19 +2975,13 @@ async def _purge_demo_quick(session, tenant: Tenant) -> tuple[int, int, int]:
keys = [incident["key"] for incident in _DEMO_QUICK_INCIDENTS]
# Collect existing case IDs first so we can scope the timeline delete.
- case_rows = await session.execute(
- select(Case.id)
- .where(Case.tenant_id == tenant.id)
- .where(Case.case_number.in_(keys))
- )
+ case_rows = await session.execute(select(Case.id).where(Case.tenant_id == tenant.id).where(Case.case_number.in_(keys)))
case_ids = [row[0] for row in case_rows.all()]
deleted_timelines = 0
if case_ids:
result = await session.execute(
- delete(CaseTimeline)
- .where(CaseTimeline.tenant_id == tenant.id)
- .where(CaseTimeline.case_id.in_(case_ids))
+ delete(CaseTimeline).where(CaseTimeline.tenant_id == tenant.id).where(CaseTimeline.case_id.in_(case_ids))
)
deleted_timelines = result.rowcount or 0
@@ -2999,20 +2989,12 @@ async def _purge_demo_quick(session, tenant: Tenant) -> tuple[int, int, int]:
# tag, but case-scoped deletion is the safer ON DELETE path.
deleted_alerts = 0
if case_ids:
- result = await session.execute(
- delete(Alert)
- .where(Alert.tenant_id == tenant.id)
- .where(Alert.case_id.in_(case_ids))
- )
+ result = await session.execute(delete(Alert).where(Alert.tenant_id == tenant.id).where(Alert.case_id.in_(case_ids)))
deleted_alerts = result.rowcount or 0
deleted_cases = 0
if case_ids:
- result = await session.execute(
- delete(Case)
- .where(Case.tenant_id == tenant.id)
- .where(Case.id.in_(case_ids))
- )
+ result = await session.execute(delete(Case).where(Case.tenant_id == tenant.id).where(Case.id.in_(case_ids)))
deleted_cases = result.rowcount or 0
await session.flush()
@@ -3162,12 +3144,8 @@ async def _run_quick_seed(clock: datetime) -> None:
tenant = await _ensure_tenant(session)
user = await _ensure_user(session, tenant)
connectors = await _seed_demo_quick_connectors(session, tenant, clock=clock)
- deleted_cases, deleted_alerts, deleted_timelines = await _purge_demo_quick(
- session, tenant
- )
- cases, alerts, timelines = await _seed_demo_quick(
- session, tenant, clock=clock
- )
+ deleted_cases, deleted_alerts, deleted_timelines = await _purge_demo_quick(session, tenant)
+ cases, alerts, timelines = await _seed_demo_quick(session, tenant, clock=clock)
await session.commit()
except Exception:
await session.rollback()
@@ -3176,16 +3154,11 @@ async def _run_quick_seed(clock: datetime) -> None:
print(f"[seed] tenant: {tenant.id} ({tenant.slug})")
print(f"[seed] user: {user.email} (role={user.role})")
print(f"[seed] connectors upserted: {connectors}")
- print(
- "[seed] purged DEMO-* — cases:%d alerts:%d timelines:%d"
- % (deleted_cases, deleted_alerts, deleted_timelines)
- )
+ print("[seed] purged DEMO-* — cases:%d alerts:%d timelines:%d" % (deleted_cases, deleted_alerts, deleted_timelines))
print(f"[seed] DEMO-* cases seeded: {cases}")
print(f"[seed] DEMO-* alerts seeded: {alerts}")
print(f"[seed] DEMO-* timelines seeded: {timelines}")
- print(
- "[seed] showcase case: DEMO-004 — http://localhost:3000/cases/DEMO-004?tab=ledger"
- )
+ print("[seed] showcase case: DEMO-004 — http://localhost:3000/cases/DEMO-004?tab=ledger")
print("[seed] done — four-case demo set is live")
diff --git a/services/api/app/security/credential_vault.py b/services/api/app/security/credential_vault.py
index c603b4727..9c4092d0f 100644
--- a/services/api/app/security/credential_vault.py
+++ b/services/api/app/security/credential_vault.py
@@ -168,7 +168,7 @@ class CredentialVault:
for k, v in payload.items():
# If the caller restricted to specific keys, leave everything
# else alone. Otherwise fall through and recurse.
- if secret_keys is not None and k not in secret_keys and not isinstance(v, (Mapping, list)):
+ if secret_keys is not None and k not in secret_keys and not isinstance(v, Mapping | list):
out[k] = v
else:
out[k] = self._walk(v, encrypt=encrypt, secret_keys=secret_keys, _key=k)
diff --git a/services/api/app/services/attack_chain.py b/services/api/app/services/attack_chain.py
index b0bc7803e..4e02daae5 100644
--- a/services/api/app/services/attack_chain.py
+++ b/services/api/app/services/attack_chain.py
@@ -223,9 +223,7 @@ class AttackChainLoader(Protocol):
set passed in.
"""
- async def load_seed(
- self, alert_id: uuid.UUID, tenant_id: uuid.UUID
- ) -> CandidateAlert | None:
+ async def load_seed(self, alert_id: uuid.UUID, tenant_id: uuid.UUID) -> CandidateAlert | None:
# Protocol method body: ``pass`` rather than ``...`` so CodeQL
# ``py/ineffectual-statement`` doesn't flag the ellipsis as a
# discarded expression. Semantically identical for a Protocol
@@ -250,9 +248,7 @@ class AttackChainLoader(Protocol):
# ---------------------------------------------------------------------------
-def _temporal_score(
- seed_time: datetime, candidate_time: datetime, window: timedelta
-) -> tuple[float, float]:
+def _temporal_score(seed_time: datetime, candidate_time: datetime, window: timedelta) -> tuple[float, float]:
"""Return (score, |Δt| in seconds). Score is in [0, 1] — closer in
time → higher score. ``|Δt|`` is exposed in the response so the UI
can render the absolute time delta beside the chain link."""
@@ -379,9 +375,7 @@ def _entity_graph_payload(
_add_alert_node(seed)
for kind, value in sorted(seed.entities()):
_add_entity_node(kind, value)
- edges.append(
- {"source": f"alert:{seed.id}", "target": f"{kind.lower()}:{value}", "kind": "TOUCHES"}
- )
+ edges.append({"source": f"alert:{seed.id}", "target": f"{kind.lower()}:{value}", "kind": "TOUCHES"})
for link in chain:
cand = candidate_index.get(link.alert_id)
@@ -527,15 +521,12 @@ class PostgresAttackChainLoader:
def __init__(self, db: Any) -> None:
self._db = db
- async def load_seed(
- self, alert_id: uuid.UUID, tenant_id: uuid.UUID
- ) -> CandidateAlert | None:
+ async def load_seed(self, alert_id: uuid.UUID, tenant_id: uuid.UUID) -> CandidateAlert | None:
from sqlalchemy import select # local import keeps the module
+
from app.models.alert import Alert # test-importable w/o DB
- result = await self._db.execute(
- select(Alert).where(Alert.id == alert_id, Alert.tenant_id == tenant_id)
- )
+ result = await self._db.execute(select(Alert).where(Alert.id == alert_id, Alert.tenant_id == tenant_id))
row = result.scalar_one_or_none()
if row is None:
return None
@@ -550,6 +541,7 @@ class PostgresAttackChainLoader:
exclude_ids: set[uuid.UUID],
) -> list[CandidateAlert]:
from sqlalchemy import and_, or_, select, text
+
from app.models.alert import Alert
users: list[str] = []
diff --git a/services/api/app/services/audit_hash.py b/services/api/app/services/audit_hash.py
index 6b6ca9cfe..8b1c4de3d 100644
--- a/services/api/app/services/audit_hash.py
+++ b/services/api/app/services/audit_hash.py
@@ -49,7 +49,7 @@ from typing import Any
def _canonicalise(value: Any) -> Any:
"""Map non-JSON-native types into something ``json.dumps`` can encode deterministically."""
- if value is None or isinstance(value, (bool, int, float, str)):
+ if value is None or isinstance(value, bool | int | float | str):
return value
if isinstance(value, uuid.UUID):
return str(value)
@@ -60,7 +60,7 @@ def _canonicalise(value: Any) -> Any:
return value.isoformat()
if isinstance(value, dict):
return {str(k): _canonicalise(v) for k, v in value.items()}
- if isinstance(value, (list, tuple)):
+ if isinstance(value, list | tuple):
return [_canonicalise(v) for v in value]
# Fallback: stringify. Audit metadata occasionally contains exotic
# values (e.g. enum instances); we never want the hash to crash.
diff --git a/services/api/app/services/audit_redaction.py b/services/api/app/services/audit_redaction.py
index 355b0d3c8..0dc201c53 100644
--- a/services/api/app/services/audit_redaction.py
+++ b/services/api/app/services/audit_redaction.py
@@ -120,7 +120,7 @@ def _redact_node(value: Any, depth: int, counter: list[int]) -> Any:
else:
out[key] = _redact_node(v, depth + 1, counter)
return out
- if isinstance(value, (list, tuple)):
+ if isinstance(value, list | tuple):
return [_redact_node(item, depth + 1, counter) for item in value]
# Primitives pass through unchanged. We deliberately do NOT inspect
# the value side for "looks like a token" heuristics — that creates
diff --git a/services/api/app/services/business_context/engine.py b/services/api/app/services/business_context/engine.py
index 3a3e8055d..9ef7876b0 100644
--- a/services/api/app/services/business_context/engine.py
+++ b/services/api/app/services/business_context/engine.py
@@ -123,9 +123,9 @@ def _eval_op(op: str, lhs: Any, rhs: Any) -> bool:
if op == "endswith":
return isinstance(lhs, str) and isinstance(rhs, str) and lhs.endswith(rhs)
if op == "in":
- return lhs in rhs if isinstance(rhs, (list, tuple, set)) else False
+ return lhs in rhs if isinstance(rhs, list | tuple | set) else False
if op == "not_in":
- return lhs not in rhs if isinstance(rhs, (list, tuple, set)) else False
+ return lhs not in rhs if isinstance(rhs, list | tuple | set) else False
return False
@@ -217,12 +217,8 @@ class EngineSnapshot:
return tuple(r for r in self.rules if r.enabled)
-def _compile_snapshot(
- tenant_id: UUID, version: int, rules: Iterable[BusinessContextRule]
-) -> EngineSnapshot:
- sorted_rules = tuple(
- sorted(rules, key=lambda r: (r.priority, r.id))
- )
+def _compile_snapshot(tenant_id: UUID, version: int, rules: Iterable[BusinessContextRule]) -> EngineSnapshot:
+ sorted_rules = tuple(sorted(rules, key=lambda r: (r.priority, r.id)))
idx: dict[str, list[str]] = {}
for r in sorted_rules:
for f in r.when.fields_referenced():
diff --git a/services/api/app/services/business_context/models.py b/services/api/app/services/business_context/models.py
index 9cdf5710d..c19857269 100644
--- a/services/api/app/services/business_context/models.py
+++ b/services/api/app/services/business_context/models.py
@@ -19,7 +19,8 @@ language the editor speaks.
from __future__ import annotations
import re
-from dataclasses import dataclass, field as dc_field
+from dataclasses import dataclass
+from dataclasses import field as dc_field
from typing import Any, Literal
import yaml
@@ -151,12 +152,7 @@ class RuleAction:
suppress: bool = False # if true, alert is dropped before triage
def is_noop(self) -> bool:
- return (
- self.set_severity is None
- and self.route_to is None
- and self.tag is None
- and not self.suppress
- )
+ return self.set_severity is None and self.route_to is None and self.tag is None and not self.suppress
# ---------------------------------------------------------------------------
@@ -206,34 +202,23 @@ def _parse_condition(raw: Any, *, path: str) -> RuleCondition:
children_raw = raw[key]
if key == "not":
if not isinstance(children_raw, dict):
- raise RuleParseError(
- f"{path}.not: expected a mapping for the negated condition"
- )
+ raise RuleParseError(f"{path}.not: expected a mapping for the negated condition")
child = _parse_condition(children_raw, path=f"{path}.not")
return RuleCondition(logical="not", children=(child,))
if not isinstance(children_raw, list) or not children_raw:
- raise RuleParseError(
- f"{path}.{key}: must be a non-empty list of conditions"
- )
- children = tuple(
- _parse_condition(c, path=f"{path}.{key}[{i}]")
- for i, c in enumerate(children_raw)
- )
+ raise RuleParseError(f"{path}.{key}: must be a non-empty list of conditions")
+ children = tuple(_parse_condition(c, path=f"{path}.{key}[{i}]") for i, c in enumerate(children_raw))
return RuleCondition(logical=key, children=children)
# Leaf form
field_name = raw.get("field")
op = raw.get("op")
if field_name is None or op is None:
- raise RuleParseError(
- f"{path}: leaf condition must include 'field' and 'op' (got {sorted(raw.keys())})"
- )
+ raise RuleParseError(f"{path}: leaf condition must include 'field' and 'op' (got {sorted(raw.keys())})")
if not isinstance(field_name, str) or not field_name:
raise RuleParseError(f"{path}.field: must be a non-empty string")
if op not in ALLOWED_OPS:
- raise RuleParseError(
- f"{path}.op: {op!r} is not one of {sorted(ALLOWED_OPS)}"
- )
+ raise RuleParseError(f"{path}.op: {op!r} is not one of {sorted(ALLOWED_OPS)}")
# ``exists`` / ``not_exists`` are unary — value is ignored if present.
if op in {"exists", "not_exists"}:
@@ -245,48 +230,36 @@ def _parse_condition(raw: Any, *, path: str) -> RuleCondition:
# ``in`` / ``not_in`` require a sequence; coerce single string to a
# one-element list to be analyst-friendly.
if op in {"in", "not_in"}:
- if isinstance(value, (str, bytes)):
+ if isinstance(value, str | bytes):
value = [value]
- if not isinstance(value, (list, tuple)) or not value:
- raise RuleParseError(
- f"{path}.value: op={op!r} requires a non-empty list"
- )
+ if not isinstance(value, list | tuple) or not value:
+ raise RuleParseError(f"{path}.value: op={op!r} requires a non-empty list")
value = list(value)
return RuleCondition(field=field_name, op=op, value=value)
def _parse_action(raw: Any, *, rule_id: str) -> RuleAction:
if not isinstance(raw, dict):
- raise RuleParseError(
- f"rule {rule_id!r}: 'then' must be a mapping (got {type(raw).__name__})"
- )
+ raise RuleParseError(f"rule {rule_id!r}: 'then' must be a mapping (got {type(raw).__name__})")
sev = raw.get("set_severity")
if sev is not None:
if not isinstance(sev, str) or sev not in ALLOWED_SEVERITIES:
- raise RuleParseError(
- f"rule {rule_id!r}: 'set_severity' must be one of {ALLOWED_SEVERITIES}"
- )
+ raise RuleParseError(f"rule {rule_id!r}: 'set_severity' must be one of {ALLOWED_SEVERITIES}")
route = raw.get("route_to")
if route is not None:
if not isinstance(route, str) or route not in ALLOWED_ROUTES:
- raise RuleParseError(
- f"rule {rule_id!r}: 'route_to' must be one of {sorted(ALLOWED_ROUTES)}"
- )
+ raise RuleParseError(f"rule {rule_id!r}: 'route_to' must be one of {sorted(ALLOWED_ROUTES)}")
tag = raw.get("tag")
if tag is not None:
if not isinstance(tag, str) or not _TAG_RE.match(tag):
- raise RuleParseError(
- f"rule {rule_id!r}: 'tag' must be a kebab-case slug (got {tag!r})"
- )
+ raise RuleParseError(f"rule {rule_id!r}: 'tag' must be a kebab-case slug (got {tag!r})")
suppress = raw.get("suppress", False)
if not isinstance(suppress, bool):
- raise RuleParseError(
- f"rule {rule_id!r}: 'suppress' must be a boolean (got {type(suppress).__name__})"
- )
+ raise RuleParseError(f"rule {rule_id!r}: 'suppress' must be a boolean (got {type(suppress).__name__})")
return RuleAction(
set_severity=sev,
@@ -298,15 +271,11 @@ def _parse_action(raw: Any, *, rule_id: str) -> RuleAction:
def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
if not isinstance(raw, dict):
- raise RuleParseError(
- f"top-level rule must be a mapping, got {type(raw).__name__}"
- )
+ raise RuleParseError(f"top-level rule must be a mapping, got {type(raw).__name__}")
rid = raw.get("id")
if not isinstance(rid, str) or not _RULE_ID_RE.match(rid):
- raise RuleParseError(
- "rule.id must be a kebab-case slug 3-63 chars (e.g. 'prod-iam-critical')"
- )
+ raise RuleParseError("rule.id must be a kebab-case slug 3-63 chars (e.g. 'prod-iam-critical')")
description = raw.get("description", "") or ""
if not isinstance(description, str):
@@ -322,10 +291,7 @@ def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
raise RuleParseError(f"rule {rid!r}: 'then' clause is required")
then = _parse_action(then_raw, rule_id=rid)
if then.is_noop():
- raise RuleParseError(
- f"rule {rid!r}: 'then' clause must set at least one of "
- "set_severity / route_to / tag / suppress"
- )
+ raise RuleParseError(f"rule {rid!r}: 'then' clause must set at least one of " "set_severity / route_to / tag / suppress")
enabled = raw.get("enabled", True)
if not isinstance(enabled, bool):
@@ -333,9 +299,7 @@ def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
priority = raw.get("priority", 100)
if not isinstance(priority, int) or not 0 <= priority <= 1000:
- raise RuleParseError(
- f"rule {rid!r}: 'priority' must be an int in [0, 1000]"
- )
+ raise RuleParseError(f"rule {rid!r}: 'priority' must be an int in [0, 1000]")
return BusinessContextRule(
id=rid,
@@ -392,18 +356,14 @@ def load_rules_from_yaml(source: str) -> list[BusinessContextRule]:
# Single-rule shorthand.
rules_raw = [data]
else:
- raise RuleParseError(
- f"top-level YAML must be a list or mapping, got {type(data).__name__}"
- )
+ raise RuleParseError(f"top-level YAML must be a list or mapping, got {type(data).__name__}")
parsed: list[BusinessContextRule] = []
seen_ids: set[str] = set()
for raw in rules_raw:
rule = _parse_one_rule(raw, source_yaml=text)
if rule.id in seen_ids:
- raise RuleParseError(
- f"duplicate rule id {rule.id!r} (rule ids must be unique)"
- )
+ raise RuleParseError(f"duplicate rule id {rule.id!r} (rule ids must be unique)")
seen_ids.add(rule.id)
parsed.append(rule)
diff --git a/services/api/app/services/effective_permissions/aws.py b/services/api/app/services/effective_permissions/aws.py
index 94e823ca7..30691a3b9 100644
--- a/services/api/app/services/effective_permissions/aws.py
+++ b/services/api/app/services/effective_permissions/aws.py
@@ -121,9 +121,7 @@ def _resource_matches(statement_resource: Any, resource_arn: str) -> bool:
return False
-def _condition_matches(
- condition: dict[str, Any] | None, context: dict[str, Any]
-) -> bool:
+def _condition_matches(condition: dict[str, Any] | None, context: dict[str, Any]) -> bool:
"""Evaluate the subset of IAM condition operators the resolver models.
Returns ``True`` when no condition is present. Supports
@@ -206,30 +204,20 @@ class AwsIamResolver(Resolver):
) -> ResolverResult:
snap = snapshot if snapshot is not None else self._snapshot
if snap is None:
- raise ResolverError(
- "AwsIamResolver.resolve called without a snapshot"
- )
+ raise ResolverError("AwsIamResolver.resolve called without a snapshot")
principals_by_id = {p["id"]: p for p in snap.get("principals", [])}
- principals_by_arn = {
- p["arn"]: p for p in snap.get("principals", []) if "arn" in p
- }
- principal = principals_by_id.get(principal_id) or principals_by_arn.get(
- principal_id
- )
+ principals_by_arn = {p["arn"]: p for p in snap.get("principals", []) if "arn" in p}
+ principal = principals_by_id.get(principal_id) or principals_by_arn.get(principal_id)
if principal is None:
- raise ResolverError(
- f"principal {principal_id!r} not present in snapshot"
- )
+ raise ResolverError(f"principal {principal_id!r} not present in snapshot")
policies_by_id = {p["id"]: p for p in snap.get("policies", [])}
groups_by_id = {g["id"]: g for g in snap.get("groups", [])}
scp_ids = list(snap.get("scps", []))
action_catalogue: dict[str, list[str]] = snap.get("action_catalogue", {})
- identity_policy_refs = self._collect_identity_policies(
- principal, groups_by_id
- )
+ identity_policy_refs = self._collect_identity_policies(principal, groups_by_id)
notes: list[str] = []
decisions: list[ResolvedPermission] = []
@@ -246,10 +234,7 @@ class AwsIamResolver(Resolver):
decisions.append(decision)
if any(p.get("permissions_boundary") for p in [principal]):
- notes.append(
- "permissions-boundary present on principal — not modelled; "
- "deny-side may over-permit"
- )
+ notes.append("permissions-boundary present on principal — not modelled; " "deny-side may over-permit")
return ResolverResult(
provider=self.provider,
@@ -300,9 +285,7 @@ class AwsIamResolver(Resolver):
) -> ResolvedPermission | None:
resource_arn = resource["arn"]
resource_service = resource.get("service") or resource_arn.split(":")[2]
- service_catalogue = (
- resource.get("service_actions") or action_catalogue.get(resource_service, [])
- )
+ service_catalogue = resource.get("service_actions") or action_catalogue.get(resource_service, [])
context = resource.get("context", {})
chain: list[PolicyChainStep] = []
@@ -359,9 +342,7 @@ class AwsIamResolver(Resolver):
kind="policy",
id=resource_policy_id,
name=resource_policy.get("name", resource_policy_id),
- effect="deny"
- if resource_deny and not resource_allow
- else "allow",
+ effect="deny" if resource_deny and not resource_allow else "allow",
)
)
@@ -455,9 +436,7 @@ class AwsIamResolver(Resolver):
if not isinstance(statement, dict):
continue
if principal_match_required:
- if not _principal_matches(
- statement.get("Principal"), principal_arn
- ):
+ if not _principal_matches(statement.get("Principal"), principal_arn):
continue
if not _resource_matches(statement.get("Resource", "*"), resource_arn):
continue
diff --git a/services/api/app/services/effective_permissions/base.py b/services/api/app/services/effective_permissions/base.py
index 1298d155c..aefeabeed 100644
--- a/services/api/app/services/effective_permissions/base.py
+++ b/services/api/app/services/effective_permissions/base.py
@@ -111,9 +111,7 @@ class ResolverResult:
provider: str
principal_id: str
coverage: Coverage
- last_resolved: datetime = field(
- default_factory=lambda: datetime.now(tz=UTC)
- )
+ last_resolved: datetime = field(default_factory=lambda: datetime.now(tz=UTC))
decisions: list[ResolvedPermission] = field(default_factory=list)
resolver_version: str = RESOLVER_VERSION
notes: list[str] = field(default_factory=list)
diff --git a/services/api/app/services/effective_permissions/service.py b/services/api/app/services/effective_permissions/service.py
index 422e587cb..a478d6fb3 100644
--- a/services/api/app/services/effective_permissions/service.py
+++ b/services/api/app/services/effective_permissions/service.py
@@ -119,10 +119,7 @@ def resolve_effective_permissions(
resolver_cls = SUPPORTED_PROVIDERS.get(provider)
if resolver_cls is None:
- raise ValueError(
- f"unknown provider {provider!r}; supported: "
- f"{sorted(SUPPORTED_PROVIDERS)}"
- )
+ raise ValueError(f"unknown provider {provider!r}; supported: " f"{sorted(SUPPORTED_PROVIDERS)}")
resolver = resolver_cls()
if snapshot is None:
diff --git a/services/api/app/services/email_approval.py b/services/api/app/services/email_approval.py
index e14309e17..c79083dc0 100644
--- a/services/api/app/services/email_approval.py
+++ b/services/api/app/services/email_approval.py
@@ -324,7 +324,7 @@ def render_approval_email(
f"<tr><td><strong>Rationale</strong></td><td>{rationale}</td></tr>"
f"</table>"
f"<p style='margin-top:16px'>"
- f"<a href='{approve_url}' style='background:#16a34a;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none;margin-right:8px'>Approve</a>"
+ f"<a href='{approve_url}' style='background:#16a34a;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none;margin-right:8px'>Approve</a>" # noqa: E501
f"<a href='{reject_url}' style='background:#dc2626;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none'>Deny</a>"
f"</p>"
f"<p style='color:#6b7280;font-size:12px'>This link expires in 60 minutes.</p>"
@@ -384,9 +384,7 @@ async def send_approval_email(
reject_url=reject,
web_base_url=web_base_url,
)
- response = await mailer.send(
- to=recipients, subject=subject, html=html_body, text=text_body
- )
+ response = await mailer.send(to=recipients, subject=subject, html=html_body, text=text_body)
log.info(
"email_approval.sent",
action_id=action_id,
diff --git a/services/api/app/services/event_sanitiser.py b/services/api/app/services/event_sanitiser.py
index 7e3f798c9..1ee722b08 100644
--- a/services/api/app/services/event_sanitiser.py
+++ b/services/api/app/services/event_sanitiser.py
@@ -229,7 +229,7 @@ def _redact_value(value: Any, *, depth: int, counters: dict[str, int]) -> Any:
out[k] = _redact_value(v, depth=depth + 1, counters=counters)
return out
- if isinstance(value, (list, tuple)):
+ if isinstance(value, list | tuple):
# Always emit a list — JSONB doesn't preserve tuple-ness anyway and
# the alerts schema is typed ``JSONB``. Preserve order.
return [_redact_value(v, depth=depth + 1, counters=counters) for v in value]
diff --git a/services/api/app/services/lake_sql.py b/services/api/app/services/lake_sql.py
index 64abbf165..6e74642f2 100644
--- a/services/api/app/services/lake_sql.py
+++ b/services/api/app/services/lake_sql.py
@@ -189,7 +189,7 @@ def rewrite_for_tenant(
if isinstance(root, _FORBIDDEN_ROOTS):
raise LakeSqlForbiddenError(f"only SELECT statements are allowed (got {type(root).__name__.upper()})")
- if not isinstance(root, (exp.Select, exp.Union, exp.With)):
+ if not isinstance(root, exp.Select | exp.Union | exp.With):
raise LakeSqlSyntaxError(f"expected a SELECT / WITH / UNION statement; got {type(root).__name__}")
# ── Step 3: collect CTE aliases ──────────────────────────────────
@@ -390,7 +390,7 @@ def _is_table_function(table: exp.Table) -> bool:
untrusted endpoints, or read foreign databases.
"""
inner = table.this
- if isinstance(inner, (exp.Anonymous, exp.Func)):
+ if isinstance(inner, exp.Anonymous | exp.Func):
return True
# Some dialects parse ``url(…)`` with an empty Table.name and a
# function-shaped child elsewhere. Catch those by scanning direct
@@ -428,10 +428,10 @@ def _clamp_outer_limit(node: exp.Expression, cap: int) -> None:
replace it with the cap.
"""
target: exp.Expression = node
- if isinstance(node, exp.With) and isinstance(node.this, (exp.Select, exp.Union)):
+ if isinstance(node, exp.With) and isinstance(node.this, exp.Select | exp.Union):
target = node.this
- if not isinstance(target, (exp.Select, exp.Union)):
+ if not isinstance(target, exp.Select | exp.Union):
# Defensive: caller already validated the root, but if a future
# expansion misses a case we'd rather leave the SQL alone than
# corrupt it.
diff --git a/services/api/app/services/narrative_projection.py b/services/api/app/services/narrative_projection.py
index 9323f912a..abe1f4c4d 100644
--- a/services/api/app/services/narrative_projection.py
+++ b/services/api/app/services/narrative_projection.py
@@ -154,7 +154,7 @@ def _rba_promotion(enrichment: Any) -> tuple[str | None, float | None]:
score = rba.get("score")
if not isinstance(entity, str) or not entity.strip():
entity = None
- if isinstance(score, (int, float)):
+ if isinstance(score, int | float):
score_f: float | None = float(score)
else:
score_f = None
diff --git a/services/api/app/services/tenant_provision/__init__.py b/services/api/app/services/tenant_provision/__init__.py
index c7c102df9..ecf69610d 100644
--- a/services/api/app/services/tenant_provision/__init__.py
+++ b/services/api/app/services/tenant_provision/__init__.py
@@ -17,8 +17,8 @@ from __future__ import annotations
from app.services.tenant_provision.provisioner import (
AdminInvite,
InitialAdminUser,
- ProvisionResult,
ProvisioningError,
+ ProvisionResult,
SlugCollisionError,
WaitlistEntryNotFoundError,
WaitlistEntryNotPromotableError,
diff --git a/services/api/app/services/tenant_provision/provisioner.py b/services/api/app/services/tenant_provision/provisioner.py
index a06b65182..3ea80a10b 100644
--- a/services/api/app/services/tenant_provision/provisioner.py
+++ b/services/api/app/services/tenant_provision/provisioner.py
@@ -53,9 +53,10 @@ import logging
import re
import secrets
import uuid
+from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Any, Callable
+from typing import Any
from cryptography.fernet import Fernet
from sqlalchemy import select, text
@@ -216,10 +217,7 @@ async def _allocate_slug(
if await _slug_is_available(db, candidate):
return candidate
- raise SlugCollisionError(
- f"could not allocate a unique slug for '{company_name}' after "
- f"{_SLUG_RETRY_LIMIT} attempts"
- )
+ raise SlugCollisionError(f"could not allocate a unique slug for '{company_name}' after " f"{_SLUG_RETRY_LIMIT} attempts")
def generate_credential_key() -> tuple[str, str]:
@@ -330,15 +328,11 @@ async def provision_from_waitlist(
)
if entry.status == "declined":
- raise WaitlistEntryNotPromotableError(
- f"waitlist entry {entry.id} is declined; refusing to promote"
- )
+ raise WaitlistEntryNotPromotableError(f"waitlist entry {entry.id} is declined; refusing to promote")
bundle = templates or get_default_template_bundle()
- slug = await _allocate_slug(
- db, company_name=entry.company, shard_factory=shard_factory
- )
+ slug = await _allocate_slug(db, company_name=entry.company, shard_factory=shard_factory)
credential_key, key_fingerprint = generate_credential_key()
provisioned_at = datetime.now(UTC)
@@ -430,9 +424,7 @@ async def provision_from_waitlist(
exc,
)
- invite = _build_admin_invite(
- tenant_slug=tenant.slug, invite_base_url=invite_base_url
- )
+ invite = _build_admin_invite(tenant_slug=tenant.slug, invite_base_url=invite_base_url)
# Patch the waitlist row last so the entry's stamped timestamps
# only flip after every dependent write has succeeded.
@@ -460,9 +452,7 @@ async def provision_from_waitlist(
tenant_name=tenant.name,
waitlist_entry_id=entry.id,
admin_invite=invite,
- admin_user=InitialAdminUser(
- id=admin_user.id, email=admin_user.email, role=admin_user.role
- ),
+ admin_user=InitialAdminUser(id=admin_user.id, email=admin_user.email, role=admin_user.role),
demo_seeded=demo_seeded,
aisoc_credential_key_fingerprint=key_fingerprint,
)
@@ -491,12 +481,7 @@ async def _persist_provisioning_columns(
"""
try:
await db.execute(
- text(
- "UPDATE tenants "
- "SET provisioned_from_waitlist_id = :wl_id, "
- " provisioned_at = :pa "
- "WHERE id = :tid"
- ),
+ text("UPDATE tenants " "SET provisioned_from_waitlist_id = :wl_id, " " provisioned_at = :pa " "WHERE id = :tid"),
{
"wl_id": waitlist_entry_id,
"pa": provisioned_at,
@@ -514,16 +499,10 @@ async def _persist_provisioning_columns(
)
-async def _load_waitlist_entry(
- db: AsyncSession, entry_id: uuid.UUID
-) -> WaitlistEntry:
- row = (
- await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))
- ).scalar_one_or_none()
+async def _load_waitlist_entry(db: AsyncSession, entry_id: uuid.UUID) -> WaitlistEntry:
+ row = (await db.execute(select(WaitlistEntry).where(WaitlistEntry.id == entry_id))).scalar_one_or_none()
if row is None:
- raise WaitlistEntryNotFoundError(
- f"waitlist entry {entry_id} not found"
- )
+ raise WaitlistEntryNotFoundError(f"waitlist entry {entry_id} not found")
return row
@@ -539,42 +518,30 @@ async def _result_for_existing(
entry; instead the API surfaces the existing tenant id + a fresh
invite link the operator can email out if the first one was lost.
"""
- tenant = (
- await db.execute(
- select(Tenant).where(Tenant.id == entry.provisioned_tenant_id)
- )
- ).scalar_one_or_none()
+ tenant = (await db.execute(select(Tenant).where(Tenant.id == entry.provisioned_tenant_id))).scalar_one_or_none()
if tenant is None:
# The waitlist row claims it's provisioned but the tenant is
# gone. Treat as if it was never provisioned so the operator
# can recover.
entry.provisioned_tenant_id = None
- raise WaitlistEntryNotPromotableError(
- f"waitlist entry {entry.id} pointed at a deleted tenant; cleared the pointer"
- )
+ raise WaitlistEntryNotPromotableError(f"waitlist entry {entry.id} pointed at a deleted tenant; cleared the pointer")
admin_row = (
- await db.execute(
- select(User)
- .where(User.tenant_id == tenant.id, User.email == entry.email)
- .order_by(User.created_at.asc())
- )
- ).scalars().first()
+ (await db.execute(select(User).where(User.tenant_id == tenant.id, User.email == entry.email).order_by(User.created_at.asc())))
+ .scalars()
+ .first()
+ )
admin_email = admin_row.email if admin_row else entry.email
admin_role = admin_row.role if admin_row else "tenant_admin"
admin_id = admin_row.id if admin_row else uuid.uuid4()
- fingerprint = (
- (tenant.settings or {}).get("aisoc_credential_key_fingerprint", "") or ""
- )
+ fingerprint = (tenant.settings or {}).get("aisoc_credential_key_fingerprint", "") or ""
return ProvisionResult(
tenant_id=tenant.id,
tenant_slug=tenant.slug,
tenant_name=tenant.name,
waitlist_entry_id=entry.id,
- admin_invite=_build_admin_invite(
- tenant_slug=tenant.slug, invite_base_url=invite_base_url
- ),
+ admin_invite=_build_admin_invite(tenant_slug=tenant.slug, invite_base_url=invite_base_url),
admin_user=InitialAdminUser(id=admin_id, email=admin_email, role=admin_role),
demo_seeded=False,
aisoc_credential_key_fingerprint=fingerprint,
diff --git a/services/api/app/services/tenant_provision/templates.py b/services/api/app/services/tenant_provision/templates.py
index 708f8fc2b..7ce9a67d4 100644
--- a/services/api/app/services/tenant_provision/templates.py
+++ b/services/api/app/services/tenant_provision/templates.py
@@ -38,7 +38,6 @@ from __future__ import annotations
from dataclasses import dataclass, field
-
# ---------------------------------------------------------------------------
# RBAC seed roles
# ---------------------------------------------------------------------------
diff --git a/services/api/app/services/timestamp_bounds.py b/services/api/app/services/timestamp_bounds.py
index 31982305f..14345fa89 100644
--- a/services/api/app/services/timestamp_bounds.py
+++ b/services/api/app/services/timestamp_bounds.py
@@ -133,7 +133,7 @@ def _parse_one(value: Any) -> datetime | None:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=UTC)
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
try:
if value > 1e12: # almost certainly milliseconds
value = value / 1000.0
diff --git a/services/api/app/services/waitlist/rate_limit.py b/services/api/app/services/waitlist/rate_limit.py
index cfb37b5cb..56204c726 100644
--- a/services/api/app/services/waitlist/rate_limit.py
+++ b/services/api/app/services/waitlist/rate_limit.py
@@ -104,13 +104,9 @@ class SignupRateLimiter:
capacity: float | None = None,
refill_per_hour: float | None = None,
) -> None:
- cap = capacity if capacity is not None else _env_float(
- "AISOC_WAITLIST_RATE_CAPACITY", _DEFAULT_CAPACITY
- )
+ cap = capacity if capacity is not None else _env_float("AISOC_WAITLIST_RATE_CAPACITY", _DEFAULT_CAPACITY)
per_hour = (
- refill_per_hour
- if refill_per_hour is not None
- else _env_float("AISOC_WAITLIST_RATE_REFILL_PER_HOUR", _DEFAULT_REFILL_PER_HOUR)
+ refill_per_hour if refill_per_hour is not None else _env_float("AISOC_WAITLIST_RATE_REFILL_PER_HOUR", _DEFAULT_REFILL_PER_HOUR)
)
if cap <= 0:
raise ValueError("capacity must be positive")
@@ -126,9 +122,7 @@ class SignupRateLimiter:
if cost <= 0:
raise ValueError("cost must be positive")
if cost > self._capacity:
- raise ValueError(
- f"cost {cost} exceeds capacity {self._capacity}; would never succeed"
- )
+ raise ValueError(f"cost {cost} exceeds capacity {self._capacity}; would never succeed")
bucket = await self._get_bucket(source)
async with bucket.lock:
diff --git a/services/api/app/services/waitlist/slack_notify.py b/services/api/app/services/waitlist/slack_notify.py
index 1ecf6ed74..e2970ab94 100644
--- a/services/api/app/services/waitlist/slack_notify.py
+++ b/services/api/app/services/waitlist/slack_notify.py
@@ -128,9 +128,7 @@ class SlackNotifier:
return False
webhook = self._resolve_webhook()
if not webhook:
- logger.info(
- "waitlist slack notification skipped: %s not configured", _WEBHOOK_ENV_VAR
- )
+ logger.info("waitlist slack notification skipped: %s not configured", _WEBHOOK_ENV_VAR)
return False
try:
body = json.dumps(payload).encode("utf-8")
@@ -143,9 +141,7 @@ class SlackNotifier:
with urllib_request.urlopen(req, timeout=self._timeout) as resp: # noqa: S310
if 200 <= resp.status < 300:
return True
- logger.warning(
- "waitlist slack webhook returned non-2xx: %s", resp.status
- )
+ logger.warning("waitlist slack webhook returned non-2xx: %s", resp.status)
return False
except urllib_error.URLError as exc:
logger.warning("waitlist slack webhook URLError: %s", exc)
diff --git a/services/api/app/workers/hunt_scheduler.py b/services/api/app/workers/hunt_scheduler.py
index 0ab44ab09..8b7c3eb93 100644
--- a/services/api/app/workers/hunt_scheduler.py
+++ b/services/api/app/workers/hunt_scheduler.py
@@ -165,8 +165,7 @@ async def _open_case_for_hits(db: AsyncSession, hunt: SavedHunt, hit_count: int)
case_number=f"HUNT-{hunt.id.hex[:8].upper()}-{int(datetime.now(UTC).timestamp())}",
title=f"Scheduled hunt fired: {hunt.name}",
description=(
- f"Saved hunt {hunt.name!r} returned {hit_count} hit(s) on its "
- f"scheduled run.\n\nOriginal NL question: {hunt.nl_query}"
+ f"Saved hunt {hunt.name!r} returned {hit_count} hit(s) on its " f"scheduled run.\n\nOriginal NL question: {hunt.nl_query}"
),
case_type="hunt_finding",
priority="medium",
@@ -244,11 +243,7 @@ async def run_once(
# tenant before each per-hunt write to keep RLS enforcement intact
# for the case insert.
await db.execute(text("SET LOCAL row_security = off"))
- rows = (
- (await db.execute(select(SavedHunt).where(SavedHunt.schedule.is_not(None))))
- .scalars()
- .all()
- )
+ rows = (await db.execute(select(SavedHunt).where(SavedHunt.schedule.is_not(None)))).scalars().all()
for hunt in rows:
if not _is_due(hunt, now):
continue
@@ -263,11 +258,7 @@ async def run_once(
hits = await runner(db, hunt)
await callback(db, hunt, hits)
# Stamp last_run_at so we don't re-fire on the next tick.
- await db.execute(
- update(SavedHunt)
- .where(SavedHunt.id == hunt.id)
- .values(last_run_at=now, updated_at=now)
- )
+ await db.execute(update(SavedHunt).where(SavedHunt.id == hunt.id).values(last_run_at=now, updated_at=now))
fired += 1
except Exception as exc: # pragma: no cover - defensive
logger.exception(
diff --git a/services/api/app/workers/oauth_refresh.py b/services/api/app/workers/oauth_refresh.py
index 8398823e9..9965e27fb 100644
--- a/services/api/app/workers/oauth_refresh.py
+++ b/services/api/app/workers/oauth_refresh.py
@@ -376,7 +376,7 @@ async def _refresh_one(
auth_payload["token_type"] = token_payload["token_type"]
expires_in = token_payload.get("expires_in")
- if isinstance(expires_in, (int, float)) and expires_in > 0:
+ if isinstance(expires_in, int | float) and expires_in > 0:
auth_payload["expires_at"] = (datetime.now(UTC) + timedelta(seconds=int(expires_in))).isoformat()
else:
# Provider didn't tell us — drop the stale value so we refresh
diff --git a/services/api/tests/test_attack_chain.py b/services/api/tests/test_attack_chain.py
index c9141dab6..1be13469a 100644
--- a/services/api/tests/test_attack_chain.py
+++ b/services/api/tests/test_attack_chain.py
@@ -32,7 +32,6 @@ from collections.abc import Iterable
from datetime import datetime, timedelta
import pytest
-
from app.services.attack_chain import (
DEFAULT_WINDOW,
CandidateAlert,
@@ -44,7 +43,6 @@ from app.services.attack_chain import (
score_candidate,
)
-
# ---------------------------------------------------------------------------
# Fixture: the 5-alert LockBit chain
# ---------------------------------------------------------------------------
@@ -142,9 +140,7 @@ class _InMemoryLoader:
self._by_id = {a.id: a for a in alerts}
self._all = alerts
- async def load_seed(
- self, alert_id: uuid.UUID, tenant_id: uuid.UUID
- ) -> CandidateAlert | None:
+ async def load_seed(self, alert_id: uuid.UUID, tenant_id: uuid.UUID) -> CandidateAlert | None:
row = self._by_id.get(alert_id)
if row is None or row.tenant_id != tenant_id:
return None
diff --git a/services/api/tests/test_business_context.py b/services/api/tests/test_business_context.py
index 70b7c3a37..b5aea4252 100644
--- a/services/api/tests/test_business_context.py
+++ b/services/api/tests/test_business_context.py
@@ -80,7 +80,6 @@ from app.services.business_context.models import (
)
from fastapi import HTTPException
-
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -153,7 +152,8 @@ class TestParser:
assert load_rules_from_yaml(" \n ") == []
def test_single_rule_shorthand(self) -> None:
- rules = load_rules_from_yaml(_yaml("""
+ rules = load_rules_from_yaml(
+ _yaml("""
id: prod-iam-critical
description: Critical for prod IAM
when:
@@ -162,7 +162,8 @@ class TestParser:
value: prod
then:
set_severity: critical
- """))
+ """)
+ )
assert len(rules) == 1
rule = rules[0]
assert rule.id == "prod-iam-critical"
@@ -172,7 +173,8 @@ class TestParser:
assert rule.when.value == "prod"
def test_rules_list_form(self) -> None:
- rules = load_rules_from_yaml(_yaml("""
+ rules = load_rules_from_yaml(
+ _yaml("""
rules:
- id: rule-a
when: { field: alert.severity, op: eq, value: high }
@@ -180,12 +182,14 @@ class TestParser:
- id: rule-b
when: { field: alert.source, op: eq, value: aws }
then: { route_to: cloud }
- """))
+ """)
+ )
assert [r.id for r in rules] == ["rule-a", "rule-b"]
assert rules[1].then.route_to == "cloud"
def test_aggregator_all_any_not(self) -> None:
- rules = load_rules_from_yaml(_yaml("""
+ rules = load_rules_from_yaml(
+ _yaml("""
id: nested
when:
all:
@@ -198,7 +202,8 @@ class TestParser:
value: dev
then:
tag: cloud-prod
- """))
+ """)
+ )
when = rules[0].when
assert when.logical == "all"
assert when.children[0].logical == "any"
@@ -208,11 +213,13 @@ class TestParser:
assert when.fields_referenced() == {"alert.source", "alert.target.tag"}
def test_in_op_coerces_single_string_to_list(self) -> None:
- rules = load_rules_from_yaml(_yaml("""
+ rules = load_rules_from_yaml(
+ _yaml("""
id: route-aws
when: { field: alert.source, op: in, value: aws }
then: { route_to: cloud }
- """))
+ """)
+ )
assert rules[0].when.value == ["aws"]
@pytest.mark.parametrize(
@@ -220,25 +227,22 @@ class TestParser:
[
("id: BAD\nwhen: { field: x, op: eq, value: y }\nthen: { tag: t }", "kebab-case"),
("id: ok-id\nthen: { set_severity: high }", "'when' clause is required"),
- ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { set_severity: nope }",
- "set_severity"),
+ ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { set_severity: nope }", "set_severity"),
("id: ok-id\nwhen: { field: x, op: like, value: y }\nthen: { tag: t }", "is not one of"),
("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: {}", "must set at least one"),
("id: ok-id\nwhen: { field: x, op: in }\nthen: { tag: t }", "required for op="),
- ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { route_to: nope }",
- "route_to"),
+ ("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { route_to: nope }", "route_to"),
],
)
- def test_invalid_inputs_raise_with_actionable_messages(
- self, yaml_text: str, marker: str
- ) -> None:
+ def test_invalid_inputs_raise_with_actionable_messages(self, yaml_text: str, marker: str) -> None:
with pytest.raises(RuleParseError) as exc_info:
load_rules_from_yaml(yaml_text)
assert marker in str(exc_info.value)
def test_duplicate_ids_rejected(self) -> None:
with pytest.raises(RuleParseError, match="duplicate rule id"):
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
rules:
- id: dup-rule
when: { field: a, op: eq, value: 1 }
@@ -246,7 +250,8 @@ class TestParser:
- id: dup-rule
when: { field: b, op: eq, value: 2 }
then: { set_severity: high }
- """))
+ """)
+ )
def test_constants_are_locked_down(self) -> None:
# Catches accidental edits that broaden the action vocabulary —
@@ -267,11 +272,13 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
id: prod-critical
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)),
+ """)
+ ),
)
result = engine.evaluate(tenant, _alert(severity="medium", target_tag="prod"))
assert result.before["severity"] == "medium"
@@ -284,11 +291,13 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
id: prod-only
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)),
+ """)
+ ),
)
result = engine.evaluate(tenant, _alert(target_tag="dev", severity="medium"))
assert result.before == result.after
@@ -300,7 +309,8 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
rules:
- id: maintenance-window
priority: 1
@@ -310,7 +320,8 @@ class TestEvaluation:
priority: 50
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """)),
+ """)
+ ),
)
result = engine.evaluate(tenant, _alert(target_tag="prod", severity="medium"))
assert result.suppressed is True
@@ -323,7 +334,8 @@ class TestEvaluation:
tenant = uuid.uuid4()
engine.replace(
tenant,
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
rules:
- id: aws-baseline
priority: 10
@@ -333,7 +345,8 @@ class TestEvaluation:
priority: 50
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical, tag: prod }
- """)),
+ """)
+ ),
)
result = engine.evaluate(tenant, _alert(source="aws", target_tag="prod"))
assert result.matched_rule_ids == ["aws-baseline", "prod-bump"]
@@ -382,7 +395,8 @@ class TestSnapshots:
tenant = uuid.uuid4()
snap = engine.replace(
tenant,
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
rules:
- id: zzz
priority: 5
@@ -396,7 +410,8 @@ class TestSnapshots:
priority: 5
when: { field: z, op: eq, value: 1 }
then: { tag: mmm }
- """)),
+ """)
+ ),
)
assert [r.id for r in snap.rules] == ["mmm", "zzz", "aaa"]
# Field reverse-index records all leaf paths.
@@ -414,11 +429,13 @@ class TestSnapshots:
a, b = uuid.uuid4(), uuid.uuid4()
engine.replace(
a,
- load_rules_from_yaml(_yaml("""
+ load_rules_from_yaml(
+ _yaml("""
id: only-a
when: { field: x, op: eq, value: 1 }
then: { tag: a }
- """)),
+ """)
+ ),
)
engine.replace(b, [])
assert engine.snapshot_for(a).rules[0].id == "only-a"
@@ -442,11 +459,13 @@ class TestPreview:
# Register an empty rule set.
engine.replace(tenant, [])
# Preview a rule that would, if registered, mutate severity.
- candidate = load_rules_from_yaml(_yaml("""
+ candidate = load_rules_from_yaml(
+ _yaml("""
id: would-bump
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """))
+ """)
+ )
results = engine.preview_against(
tenant,
[_alert(target_tag="prod", severity="medium")],
@@ -459,11 +478,13 @@ class TestPreview:
def test_preview_returns_one_row_per_alert(self) -> None:
engine = BusinessContextEngine()
tenant = uuid.uuid4()
- rules = load_rules_from_yaml(_yaml("""
+ rules = load_rules_from_yaml(
+ _yaml("""
id: prod-critical
when: { field: alert.target.tag, op: eq, value: prod }
then: { set_severity: critical }
- """))
+ """)
+ )
alerts = [
_alert("a", target_tag="prod"),
_alert("b", target_tag="dev"),
@@ -563,11 +584,7 @@ class TestEndpoints:
endpoint.update_rule(
"rule-a",
endpoint.UpdateRuleRequest(
- yaml=(
- "id: rule-a\n"
- "when: { field: alert.severity, op: eq, value: high }\n"
- "then: { route_to: tier3 }\n"
- )
+ yaml=("id: rule-a\n" "when: { field: alert.severity, op: eq, value: high }\n" "then: { route_to: tier3 }\n")
),
user,
MagicMock(),
@@ -585,13 +602,7 @@ class TestEndpoints:
_run(
endpoint.update_rule(
"rule-a",
- endpoint.UpdateRuleRequest(
- yaml=(
- "id: rule-other\n"
- "when: { field: x, op: eq, value: 1 }\n"
- "then: { tag: t }\n"
- )
- ),
+ endpoint.UpdateRuleRequest(yaml=("id: rule-other\n" "when: { field: x, op: eq, value: 1 }\n" "then: { tag: t }\n")),
user,
MagicMock(),
)
@@ -631,11 +642,7 @@ class TestEndpoints:
def test_preview_against_supplied_alerts(self) -> None:
user = _user()
req = endpoint.PreviewRequest(
- yaml=(
- "id: prod-critical\n"
- "when: { field: alert.target.tag, op: eq, value: prod }\n"
- "then: { set_severity: critical }\n"
- ),
+ yaml=("id: prod-critical\n" "when: { field: alert.target.tag, op: eq, value: prod }\n" "then: { set_severity: critical }\n"),
alerts=[
_alert("a", target_tag="prod", severity="medium"),
_alert("b", target_tag="dev", severity="medium"),
@@ -673,11 +680,7 @@ class TestEndpoints:
db = MagicMock()
db.execute = AsyncMock(side_effect=RuntimeError("no schema"))
req = endpoint.PreviewRequest(
- yaml=(
- "id: noop-tag\n"
- "when: { field: alert.target.tag, op: eq, value: prod }\n"
- "then: { tag: noop }\n"
- ),
+ yaml=("id: noop-tag\n" "when: { field: alert.target.tag, op: eq, value: prod }\n" "then: { tag: noop }\n"),
alerts=[],
)
resp = _run(endpoint.preview_rules(req, user, db))
@@ -704,11 +707,7 @@ class TestEndpoints:
when: { field: alert.source, op: eq, value: aws }
then: { route_to: cloud, tag: aws }
""")
- alerts = [
- _alert(f"alert-{i}", target_tag="prod" if i % 2 else "dev",
- source="aws" if i % 3 == 0 else "okta")
- for i in range(100)
- ]
+ alerts = [_alert(f"alert-{i}", target_tag="prod" if i % 2 else "dev", source="aws" if i % 3 == 0 else "okta") for i in range(100)]
start = time.perf_counter()
_run(
@@ -723,8 +722,7 @@ class TestEndpoints:
elapsed = time.perf_counter() - start
assert elapsed < 1.0, (
- f"save → evaluate round-trip took {elapsed:.3f}s, exceeds 1s budget "
- f"(eval slice = {elapsed_eval:.3f}s for 100 alerts)"
+ f"save → evaluate round-trip took {elapsed:.3f}s, exceeds 1s budget " f"(eval slice = {elapsed_eval:.3f}s for 100 alerts)"
)
# Sanity check: at least the prod alerts got bumped.
diff --git a/services/api/tests/test_demo_seed.py b/services/api/tests/test_demo_seed.py
index b8ccd9c11..b5eb89d32 100644
--- a/services/api/tests/test_demo_seed.py
+++ b/services/api/tests/test_demo_seed.py
@@ -37,7 +37,6 @@ import uuid
from typing import Any
import pytest
-
from app.scripts.seed_demo import (
_DEMO_QUICK_DEFAULT_CLOCK_ISO,
_DEMO_QUICK_INCIDENTS,
@@ -105,10 +104,7 @@ def test_demo_quick_connector_sources_match_contract() -> None:
key = incident["key"]
actual = set(incident["connector_sources"])
expected = EXPECTED_CONNECTOR_SOURCES[key]
- assert actual == expected, (
- f"{key}: connector_sources drifted. "
- f"expected {sorted(expected)}, got {sorted(actual)}"
- )
+ assert actual == expected, f"{key}: connector_sources drifted. " f"expected {sorted(expected)}, got {sorted(actual)}"
def test_demo_quick_alerts_reference_declared_connectors() -> None:
@@ -192,11 +188,10 @@ def test_demo_quick_seed_persists_four_cases() -> None:
# Local import so the heavy SQLAlchemy + asyncpg dependency chain
# doesn't load when the integration test is skipped (which is the
# common case on a developer laptop).
- from sqlalchemy import select
-
from app.db.database import AsyncSessionLocal
from app.models.case import Case
from app.scripts.seed_demo import _parse_clock, _run_quick_seed
+ from sqlalchemy import select
async def _run_and_count() -> list[Case]:
await _run_quick_seed(clock=_parse_clock(None))
@@ -208,8 +203,7 @@ def test_demo_quick_seed_persists_four_cases() -> None:
cases = asyncio.run(_run_and_count())
by_key: dict[str, Case] = {c.key: c for c in cases}
assert set(by_key.keys()) == set(EXPECTED_DEMO_KEYS), (
- f"Quick seed did not produce exactly the four DEMO-* cases. "
- f"Got keys: {sorted(by_key.keys())}"
+ f"Quick seed did not produce exactly the four DEMO-* cases. " f"Got keys: {sorted(by_key.keys())}"
)
# Walk the persisted metadata to confirm connector_sources made it
@@ -220,6 +214,5 @@ def test_demo_quick_seed_persists_four_cases() -> None:
meta: dict[str, Any] = case.case_metadata or {}
sources = set(meta.get("connector_sources") or [])
assert sources == EXPECTED_CONNECTOR_SOURCES[key], (
- f"{key}: persisted connector_sources={sorted(sources)} "
- f"does not match contract={sorted(EXPECTED_CONNECTOR_SOURCES[key])}"
+ f"{key}: persisted connector_sources={sorted(sources)} " f"does not match contract={sorted(EXPECTED_CONNECTOR_SOURCES[key])}"
)
diff --git a/services/api/tests/test_effective_permissions_aws.py b/services/api/tests/test_effective_permissions_aws.py
index e5b5049ee..605c4a19e 100644
--- a/services/api/tests/test_effective_permissions_aws.py
+++ b/services/api/tests/test_effective_permissions_aws.py
@@ -106,9 +106,7 @@ def _action_match(stmt_actions: Any, action: str) -> bool:
return False
-def _gather_identity_policies(
- principal: dict[str, Any], snap: dict[str, Any]
-) -> list[dict[str, Any]]:
+def _gather_identity_policies(principal: dict[str, Any], snap: dict[str, Any]) -> list[dict[str, Any]]:
policies_by_id = {p["id"]: p for p in snap["policies"]}
groups_by_id = {g["id"]: g for g in snap.get("groups", [])}
refs: list[str] = []
@@ -143,9 +141,7 @@ def reference_is_allowed(
resource_arn = resource["arn"]
# 1. Explicit deny across identity / resource / SCP wins outright.
- deny_sources: list[dict[str, Any]] = list(
- _gather_identity_policies(principal, snapshot)
- )
+ deny_sources: list[dict[str, Any]] = list(_gather_identity_policies(principal, snapshot))
rp_id = resource.get("resource_policy_id")
if rp_id and rp_id in policies_by_id:
deny_sources.append(policies_by_id[rp_id])
@@ -158,9 +154,7 @@ def reference_is_allowed(
for stmt in _as_list(policy.get("document", {}).get("Statement")):
if stmt.get("Effect") != "Deny":
continue
- if is_resource_policy and not _principal_match(
- stmt.get("Principal"), principal["arn"]
- ):
+ if is_resource_policy and not _principal_match(stmt.get("Principal"), principal["arn"]):
continue
if not _resource_match(stmt.get("Resource", "*"), resource_arn):
continue
@@ -228,11 +222,7 @@ def reference_decision(
resource = next(r for r in snapshot["resources"] if r["id"] == resource_id)
catalogue = resource.get("service_actions") or []
- return {
- action
- for action in catalogue
- if reference_is_allowed(snapshot, principal_id, resource_id, action)
- }
+ return {action for action in catalogue if reference_is_allowed(snapshot, principal_id, resource_id, action)}
# ---------------------------------------------------------------------------
@@ -249,11 +239,7 @@ def snapshot() -> dict[str, Any]:
def _all_pairs(snapshot: dict[str, Any]) -> list[tuple[str, str]]:
"""Generate the cartesian product of principals × resources."""
- return [
- (p["id"], r["id"])
- for p in snapshot["principals"]
- for r in snapshot["resources"]
- ]
+ return [(p["id"], r["id"]) for p in snapshot["principals"] for r in snapshot["resources"]]
# ---------------------------------------------------------------------------
@@ -288,10 +274,7 @@ def reference_pairs(snapshot: dict[str, Any]) -> list[tuple[str, str, set[str]]]
]
pairs = base + extras
assert len(pairs) >= 50, f"expected ≥50 pairs, got {len(pairs)}"
- return [
- (pid, rid, reference_decision(snapshot, pid, rid))
- for pid, rid in pairs[:50]
- ]
+ return [(pid, rid, reference_decision(snapshot, pid, rid)) for pid, rid in pairs[:50]]
def test_resolver_matches_reference_simulator_on_50_pairs(
@@ -314,15 +297,11 @@ def test_resolver_matches_reference_simulator_on_50_pairs(
)
actual = set(match.actions) if match is not None else set()
if actual != expected:
- mismatches.append(
- f"{principal_id} ↔ {resource_id}: "
- f"resolver={sorted(actual)} simulator={sorted(expected)}"
- )
+ mismatches.append(f"{principal_id} ↔ {resource_id}: " f"resolver={sorted(actual)} simulator={sorted(expected)}")
assert not mismatches, (
f"resolver disagreed with the reference simulator on "
- f"{len(mismatches)} of {len(reference_pairs)} pairs:\n"
- + "\n".join(mismatches)
+ f"{len(mismatches)} of {len(reference_pairs)} pairs:\n" + "\n".join(mismatches)
)
@@ -335,9 +314,7 @@ def test_resolver_carries_policy_chain_for_every_decision(
for principal in snapshot["principals"]:
result = resolver.resolve(principal["id"])
for decision in result.decisions:
- assert decision.policy_chain, (
- f"missing chain for {principal['id']} → {decision.resource_id}"
- )
+ assert decision.policy_chain, f"missing chain for {principal['id']} → {decision.resource_id}"
def test_resolver_surfaces_shadowed_denies_on_kms_key(
@@ -350,19 +327,11 @@ def test_resolver_surfaces_shadowed_denies_on_kms_key(
"""
resolver = AwsIamResolver(snapshot=snapshot)
- alice = next(
- d
- for d in resolver.resolve("u-alice").decisions
- if d.resource_id == "res-key-finance"
- )
+ alice = next(d for d in resolver.resolve("u-alice").decisions if d.resource_id == "res-key-finance")
assert "kms:ScheduleKeyDeletion" not in alice.actions
assert "kms:ScheduleKeyDeletion" not in alice.deny_actions
- dave = next(
- d
- for d in resolver.resolve("u-dave").decisions
- if d.resource_id == "res-key-finance"
- )
+ dave = next(d for d in resolver.resolve("u-dave").decisions if d.resource_id == "res-key-finance")
assert "kms:ScheduleKeyDeletion" not in dave.actions
assert "kms:ScheduleKeyDeletion" in dave.deny_actions
@@ -372,11 +341,7 @@ def test_scp_caps_dave_admin_on_iam_writes(snapshot: dict[str, Any]) -> None:
Role / iam:DeleteRole / iam:AttachRolePolicy must still cap him."""
resolver = AwsIamResolver(snapshot=snapshot)
- dave_iam = next(
- d
- for d in resolver.resolve("u-dave").decisions
- if d.resource_id == "res-iam-role-readonly"
- )
+ dave_iam = next(d for d in resolver.resolve("u-dave").decisions if d.resource_id == "res-iam-role-readonly")
assert "iam:CreateRole" not in dave_iam.actions
assert "iam:DeleteRole" not in dave_iam.actions
assert "iam:AttachRolePolicy" not in dave_iam.actions
@@ -390,11 +355,7 @@ def test_resource_policy_unlocks_pipeline_on_artifacts(
the bucket policy allows ``s3:GetObject`` for ``Principal: *``."""
resolver = AwsIamResolver(snapshot=snapshot)
- pipeline = next(
- d
- for d in resolver.resolve("r-pipeline").decisions
- if d.resource_id == "res-bucket-artifacts"
- )
+ pipeline = next(d for d in resolver.resolve("r-pipeline").decisions if d.resource_id == "res-bucket-artifacts")
assert "s3:GetObject" in pipeline.actions
@@ -406,11 +367,7 @@ def test_condition_blocks_erin_in_other_region(
Flipping the context to a different region must drop her access."""
resolver = AwsIamResolver(snapshot=snapshot)
- erin = next(
- d
- for d in resolver.resolve("u-erin").decisions
- if d.resource_id == "res-bucket-reports"
- )
+ erin = next(d for d in resolver.resolve("u-erin").decisions if d.resource_id == "res-bucket-reports")
assert "s3:GetObject" in erin.actions
altered = json.loads(json.dumps(snapshot))
diff --git a/services/api/tests/test_insights_endpoint.py b/services/api/tests/test_insights_endpoint.py
index 529c9e1b4..85e2347ca 100644
--- a/services/api/tests/test_insights_endpoint.py
+++ b/services/api/tests/test_insights_endpoint.py
@@ -37,7 +37,6 @@ from app.api.v1.endpoints.insights import (
)
from fastapi import HTTPException
-
# ---------------------------------------------------------------------------
# Pure helpers
# ---------------------------------------------------------------------------
@@ -186,7 +185,7 @@ async def test_get_soc_insights_returns_seven_tiles_with_expected_keys() -> None
# ``Number(...)`` so an int would also pass, but locking the
# type prevents accidental Decimal leakage.
for point in tile.sparkline.points:
- assert isinstance(point, (int, float))
+ assert isinstance(point, int | float)
@pytest.mark.asyncio
diff --git a/services/api/tests/test_saved_hunts_endpoint.py b/services/api/tests/test_saved_hunts_endpoint.py
index d9559687c..c4017b903 100644
--- a/services/api/tests/test_saved_hunts_endpoint.py
+++ b/services/api/tests/test_saved_hunts_endpoint.py
@@ -56,7 +56,6 @@ from app.api.v1.endpoints.saved_hunts import (
from fastapi import HTTPException
from sqlalchemy.exc import IntegrityError
-
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -107,8 +106,7 @@ def _saved_hunt_row(
created_by=created_by,
name=name,
nl_query=nl_query,
- translated_query=translated
- or {"esql": "FROM logs-* | LIMIT 10", "kql": "", "spl": "", "explanation": ""},
+ translated_query=translated or {"esql": "FROM logs-* | LIMIT 10", "kql": "", "spl": "", "explanation": ""},
language=language,
schedule=schedule,
last_run_at=last_run_at,
@@ -223,7 +221,9 @@ def test_create_request_rejects_unknown_language() -> None:
"""Language is restricted to ``esql | kql | spl``."""
with pytest.raises(pydantic.ValidationError):
CreateSavedHuntRequest(
- name="x", nl_query="failed logins", language="xquery" # type: ignore[arg-type]
+ name="x",
+ nl_query="failed logins",
+ language="xquery", # type: ignore[arg-type]
)
@@ -331,14 +331,12 @@ def test_create_saved_hunt_translates_and_persists(monkeypatch: pytest.MonkeyPat
# Stub the translator so the test doesn't depend on the live grammar
# (the actual translator is exercised separately in nl_query tests).
fake_envelope = TranslatedQueryEnvelope(
- esql="FROM logs-* | WHERE source.geo.country_iso_code == \"IR\" | LIMIT 500",
- kql="SecurityEvent | where source_geo_country_iso_code == \"IR\" | take 500",
+ esql='FROM logs-* | WHERE source.geo.country_iso_code == "IR" | LIMIT 500',
+ kql='SecurityEvent | where source_geo_country_iso_code == "IR" | take 500',
spl='index=* source_geo_country_iso_code="IR"',
explanation="Translates the question by filtering on country code IR.",
)
- monkeypatch.setattr(
- "app.api.v1.endpoints.saved_hunts._translate", lambda _q: fake_envelope
- )
+ monkeypatch.setattr("app.api.v1.endpoints.saved_hunts._translate", lambda _q: fake_envelope)
captured: dict[str, Any] = {}
@@ -424,9 +422,7 @@ def test_create_saved_hunt_with_invalid_schedule_422s_before_db(
monkeypatch.setattr("app.api.v1.endpoints.saved_hunts._translate", _spy)
db = _mock_scalar_db(None)
- payload = CreateSavedHuntRequest(
- name="Iran inbound", nl_query="failed logins", schedule="not a cron"
- )
+ payload = CreateSavedHuntRequest(name="Iran inbound", nl_query="failed logins", schedule="not a cron")
with pytest.raises(HTTPException) as exc:
asyncio.run(create_saved_hunt(payload, user, db))
assert exc.value.status_code == 422
@@ -508,7 +504,7 @@ def test_run_saved_hunt_re_translates_and_stamps(monkeypatch: pytest.MonkeyPatch
row = _saved_hunt_row(tenant_id=user.tenant_id)
db = _mock_scalar_db(row)
fresh = TranslatedQueryEnvelope(
- esql="FROM logs-* | WHERE source.geo.country_iso_code == \"IR\" | LIMIT 500",
+ esql='FROM logs-* | WHERE source.geo.country_iso_code == "IR" | LIMIT 500',
)
monkeypatch.setattr("app.api.v1.endpoints.saved_hunts._translate", lambda _q: fresh)
@@ -556,9 +552,7 @@ def test_scheduler_picks_up_due_hunt_and_fires_callback() -> None:
captured: dict[str, Any] = {"executor": [], "callback": []}
- async def _fake_executor(
- _db: Any, hunt: Any
- ) -> int: # noqa: ANN401
+ async def _fake_executor(_db: Any, hunt: Any) -> int: # noqa: ANN401
captured["executor"].append(hunt.id)
return 7
diff --git a/services/api/tests/test_seed_demo_confidence_synth.py b/services/api/tests/test_seed_demo_confidence_synth.py
index 15f5a8d79..d469c319e 100644
--- a/services/api/tests/test_seed_demo_confidence_synth.py
+++ b/services/api/tests/test_seed_demo_confidence_synth.py
@@ -63,8 +63,8 @@ def test_each_rationale_entry_carries_confidence_factor_keys() -> None:
for entry in rationale:
missing = _REQUIRED_KEYS - entry.keys()
assert not missing, f"missing keys in rationale: {missing}"
- assert isinstance(entry["contribution"], (int, float))
- assert isinstance(entry["weight"], (int, float))
+ assert isinstance(entry["contribution"], int | float)
+ assert isinstance(entry["weight"], int | float)
# Weights are normalised in [0, 1]; contributions in [-1, +1].
assert 0 <= entry["weight"] <= 1
assert -1.0 <= entry["contribution"] <= 1.0
diff --git a/services/api/tests/test_tenant_provision.py b/services/api/tests/test_tenant_provision.py
index d0b4bf6a8..7bdd97e26 100644
--- a/services/api/tests/test_tenant_provision.py
+++ b/services/api/tests/test_tenant_provision.py
@@ -26,8 +26,6 @@ from types import SimpleNamespace
from typing import Any
import pytest
-from fastapi import HTTPException
-
from app.api.v1.endpoints import tenant_provision as endpoint
from app.models.tenant import Tenant, User
from app.models.waitlist import (
@@ -57,7 +55,7 @@ from app.services.tenant_provision.templates import (
TenantTemplateBundle,
get_default_template_bundle,
)
-
+from fastapi import HTTPException
# ---------------------------------------------------------------------------
# Test helpers
@@ -196,7 +194,7 @@ class _MockExecuteResult:
def scalar_one_or_none(self) -> Any:
return self._rows[0] if self._rows else None
- def scalars(self) -> "_MockExecuteResult":
+ def scalars(self) -> _MockExecuteResult:
return self
def all(self) -> list[Any]:
@@ -326,9 +324,7 @@ class TestAdminInviteBuilder:
def test_zero_ttl_rejected(self) -> None:
with pytest.raises(ValueError):
- _build_admin_invite(
- tenant_slug="x", invite_base_url="x", ttl_hours=0
- )
+ _build_admin_invite(tenant_slug="x", invite_base_url="x", ttl_hours=0)
# ---------------------------------------------------------------------------
@@ -385,9 +381,7 @@ class TestProvisionFromWaitlist:
)
tenant = session.tenants[result.tenant_id]
- assert tenant.settings["aisoc_credential_key_fingerprint"] == (
- result.aisoc_credential_key_fingerprint
- )
+ assert tenant.settings["aisoc_credential_key_fingerprint"] == (result.aisoc_credential_key_fingerprint)
# The plaintext key must NEVER land in the settings blob.
for value in tenant.settings.values():
if isinstance(value, str):
@@ -591,9 +585,7 @@ class TestProvisionEndpoint:
response = _run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(
- waitlist_entry_id=entry.id, seed_demo=False
- ),
+ endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id, seed_demo=False),
session, # type: ignore[arg-type]
user,
)
@@ -613,9 +605,7 @@ class TestProvisionEndpoint:
with pytest.raises(HTTPException) as exc_info:
_run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(
- waitlist_entry_id=entry.id, seed_demo=False
- ),
+ endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id, seed_demo=False),
session, # type: ignore[arg-type]
user,
)
@@ -628,9 +618,7 @@ class TestProvisionEndpoint:
with pytest.raises(HTTPException) as exc_info:
_run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(
- waitlist_entry_id=uuid.uuid4(), seed_demo=False
- ),
+ endpoint.TenantProvisionRequest(waitlist_entry_id=uuid.uuid4(), seed_demo=False),
session, # type: ignore[arg-type]
user,
)
@@ -646,9 +634,7 @@ class TestProvisionEndpoint:
with pytest.raises(HTTPException) as exc_info:
_run(
endpoint.provision_tenant(
- endpoint.TenantProvisionRequest(
- waitlist_entry_id=entry.id, seed_demo=False
- ),
+ endpoint.TenantProvisionRequest(waitlist_entry_id=entry.id, seed_demo=False),
session, # type: ignore[arg-type]
user,
)
@@ -672,9 +658,7 @@ class TestProvisionEndpoint:
user,
)
)
- assert response.admin_invite.url.startswith(
- "https://staging.tryaisoc.com/invite/"
- )
+ assert response.admin_invite.url.startswith("https://staging.tryaisoc.com/invite/")
class TestListTenantsEndpoint:
diff --git a/services/api/tests/test_threat_intel_rbac.py b/services/api/tests/test_threat_intel_rbac.py
index b96508106..0ca2cf3f8 100644
--- a/services/api/tests/test_threat_intel_rbac.py
+++ b/services/api/tests/test_threat_intel_rbac.py
@@ -87,9 +87,9 @@ def test_all_known_roles_can_read_threat_intel(role: str) -> None:
inline. If we ever drop :read from a role we should know about it
here, not from a 403 in the browser.
"""
- assert has_permission(role, "threat_intel:read"), (
- f"Role {role!r} lost threat_intel:read — this would break the alerts UI (IOC enrichment renders inline)."
- )
+ assert has_permission(
+ role, "threat_intel:read"
+ ), f"Role {role!r} lost threat_intel:read — this would break the alerts UI (IOC enrichment renders inline)."
def test_role_permissions_map_covers_every_role_under_test() -> None:
@@ -102,9 +102,9 @@ def test_role_permissions_map_covers_every_role_under_test() -> None:
real_roles = set(ROLE_PERMISSIONS) - {"admin", "platform_admin"}
audited_roles = set(WRITE_ROLES + READ_ONLY_ROLES) - {"admin", "platform_admin"}
missing = real_roles - audited_roles
- assert not missing, (
- f"New role(s) {missing} added to ROLE_PERMISSIONS without RBAC test coverage. Add them to WRITE_ROLES or READ_ONLY_ROLES."
- )
+ assert (
+ not missing
+ ), f"New role(s) {missing} added to ROLE_PERMISSIONS without RBAC test coverage. Add them to WRITE_ROLES or READ_ONLY_ROLES."
# ─── CurrentUser.require_permission integration ──────────────────────────
@@ -202,9 +202,9 @@ def test_threat_intel_endpoint_module_uses_require_permission() -> None:
from app.api.v1.endpoints import threat_intel
src = inspect.getsource(threat_intel)
- assert "require_permission" in src, (
- "threat_intel.py no longer references require_permission — the MSSP RBAC gate has been removed. See Issue #13."
- )
+ assert (
+ "require_permission" in src
+ ), "threat_intel.py no longer references require_permission — the MSSP RBAC gate has been removed. See Issue #13."
assert 'require_permission("threat_intel:write")' in src, (
"threat_intel.py no longer gates on threat_intel:write. "
"Write endpoints (POST/DELETE on /iocs, /actors, /feeds) must "
diff --git a/services/api/tests/test_waitlist.py b/services/api/tests/test_waitlist.py
index d13a46343..cd18cd809 100644
--- a/services/api/tests/test_waitlist.py
+++ b/services/api/tests/test_waitlist.py
@@ -41,8 +41,6 @@ from types import SimpleNamespace
from typing import Any
import pytest
-from fastapi import HTTPException, Request, Response
-
from app.api.v1.endpoints import waitlist as endpoint
from app.models.waitlist import (
WAITLIST_STATUS_CONTACTED,
@@ -56,7 +54,8 @@ from app.services.waitlist import (
SlackNotifier,
build_signup_message,
)
-
+from fastapi import HTTPException, Request, Response
+from pydantic import ValidationError
# ---------------------------------------------------------------------------
# Test helpers
@@ -87,7 +86,7 @@ def _admin_user(*, allow: bool = True) -> SimpleNamespace:
user_id=uuid.uuid4(),
tenant_id=uuid.uuid4(),
role="tenant_admin",
has_permission_db=_check,
)
@@ -133,7 +132,7 @@ class _MockSession:
rows = list(self.rows.values())
# WHERE id = :id
- for clause in getattr(stmt, "whereclause", None) and [stmt.whereclause] or []:
+ for _clause in getattr(stmt, "whereclause", None) and [stmt.whereclause] or []:
pass # SQLAlchemy compiled expressions don't easily yield bind values
# Easier: walk the stmt._where_criteria.
# We'll just inspect the compiled clause string.
@@ -186,7 +185,7 @@ class _MockExecuteResult:
def scalar_one_or_none(self) -> WaitlistEntry | None:
return self._rows[0] if self._rows else None
- def scalars(self) -> "_MockExecuteResult":
+ def scalars(self) -> _MockExecuteResult:
return self
def all(self) -> list[WaitlistEntry]:
@@ -228,7 +227,7 @@ class TestSignupRequestValidation:
assert payload.role == "SOC Manager"
def test_invalid_email_rejected(self) -> None:
- with pytest.raises(Exception):
+ with pytest.raises(ValidationError):
endpoint.WaitlistSignupRequest(
email="not-an-email",
company="Acme",
@@ -257,7 +256,7 @@ class TestSignupRequestValidation:
assert len(payload.soc_stack) <= 20
def test_blank_motivation_rejected(self) -> None:
- with pytest.raises(Exception):
+ with pytest.raises(ValidationError):
endpoint.WaitlistSignupRequest(
company="Acme",
@@ -590,7 +589,7 @@ class TestAdminPatchEndpoint:
assert exc_info.value.status_code == 404
def test_patch_invalid_status_rejected_at_payload_layer(self) -> None:
- with pytest.raises(Exception):
+ with pytest.raises(ValidationError):
endpoint.WaitlistPatchRequest(status="nope")
diff --git a/services/connectors/app/connectors/abnormal_security.py b/services/connectors/app/connectors/abnormal_security.py
index ad7e6cee1..492807386 100644
--- a/services/connectors/app/connectors/abnormal_security.py
+++ b/services/connectors/app/connectors/abnormal_security.py
@@ -134,7 +134,7 @@ class AbnormalSecurityConnector(BaseConnector):
next_page = payload.get("nextPageNumber") or payload.get("next")
if not next_page or len(items) < _PER_PAGE:
break
- page_number = int(next_page) if isinstance(next_page, (int, str)) else page_number + 1
+ page_number = int(next_page) if isinstance(next_page, int | str) else page_number + 1
return out
_HIGH_THREAT_TYPES = (
diff --git a/services/connectors/app/connectors/aws_security_hub.py b/services/connectors/app/connectors/aws_security_hub.py
index 0286fce07..2e5674ec1 100644
--- a/services/connectors/app/connectors/aws_security_hub.py
+++ b/services/connectors/app/connectors/aws_security_hub.py
@@ -182,9 +182,7 @@ class AWSSecurityHubConnector(BaseConnector):
return {"error": "trail not found"}
trail = trails[0]
try:
- selectors = ct.get_event_selectors(TrailName=trail_arn).get(
- "EventSelectors", []
- )
+ selectors = ct.get_event_selectors(TrailName=trail_arn).get("EventSelectors", [])
except Exception: # noqa: BLE001
selectors = []
return {
@@ -238,9 +236,7 @@ class AWSSecurityHubConnector(BaseConnector):
break
if not chosen:
return {"error": "no policy versions"}
- doc = iam.get_policy_version(
- PolicyArn=policy_arn, VersionId=chosen["VersionId"]
- ).get("PolicyVersion", {}).get("Document", {})
+ doc = iam.get_policy_version(PolicyArn=policy_arn, VersionId=chosen["VersionId"]).get("PolicyVersion", {}).get("Document", {})
return {
"resource_type": "AWS::IAM::ManagedPolicy",
"policy_arn": policy_arn,
@@ -257,9 +253,10 @@ class AWSSecurityHubConnector(BaseConnector):
# and let it parse. If Config isn't recording the resource we get
# an empty configurationItems list and surface that cleanly.
try:
- import boto3
from datetime import datetime as _dt
+ import boto3
+
kwargs: dict[str, Any] = {"region_name": self._region}
if self._access_key and self._secret_key:
kwargs["aws_access_key_id"] = self._access_key
@@ -282,9 +279,7 @@ class AWSSecurityHubConnector(BaseConnector):
params["resourceType"] = "AWS::" + arn_parts[2].capitalize() + "::Resource"
if target:
params["laterTime"] = target
- items = cfgc.get_resource_config_history(**params).get(
- "configurationItems", []
- )
+ items = cfgc.get_resource_config_history(**params).get("configurationItems", [])
if not items:
return {"error": "not recorded"}
return {
diff --git a/services/connectors/app/connectors/cloudflare_zt.py b/services/connectors/app/connectors/cloudflare_zt.py
index 3e38fb1d3..d99a35fe3 100644
--- a/services/connectors/app/connectors/cloudflare_zt.py
+++ b/services/connectors/app/connectors/cloudflare_zt.py
@@ -71,10 +71,7 @@ class CloudflareZTConnector(BaseConnector):
{"value": "waf", "label": "WAF / firewall events"},
{"value": "access", "label": "Zero Trust Access audit"},
],
- help_text=(
- "Pick which stream this instance pulls. Run two "
- "instances side-by-side for full coverage."
- ),
+ help_text=("Pick which stream this instance pulls. Run two " "instances side-by-side for full coverage."),
),
Field(
"account_id",
@@ -96,9 +93,7 @@ class CloudflareZTConnector(BaseConnector):
"secret",
"API Token",
help_text=(
- "Account-scoped token with Zone:Firewall "
- "Services:Read (WAF) AND Account:Access "
- "Audit Logs:Read (Zero Trust)."
+ "Account-scoped token with Zone:Firewall " "Services:Read (WAF) AND Account:Access " "Audit Logs:Read (Zero Trust)."
),
),
],
@@ -169,10 +164,7 @@ class CloudflareZTConnector(BaseConnector):
return {
"success": False,
"connector": self.connector_id,
- "error": (
- f"token verified but {self._mode} probe HTTP "
- f"{probe.status_code}: {probe.text[:200]}"
- ),
+ "error": (f"token verified but {self._mode} probe HTTP " f"{probe.status_code}: {probe.text[:200]}"),
}
return {
"success": True,
diff --git a/services/connectors/app/connectors/datadog.py b/services/connectors/app/connectors/datadog.py
index 8c33d2db7..b13acf477 100644
--- a/services/connectors/app/connectors/datadog.py
+++ b/services/connectors/app/connectors/datadog.py
@@ -95,10 +95,7 @@ class DatadogConnector(BaseConnector):
"Filter query",
required=False,
default="status:error OR status:critical",
- help_text=(
- "Logs Search query (logs mode) or tag filter "
- "(events mode, e.g. 'priority:all')."
- ),
+ help_text=("Logs Search query (logs mode) or tag filter " "(events mode, e.g. 'priority:all')."),
),
Field("api_key", "secret", "API Key"),
Field("application_key", "secret", "Application Key"),
diff --git a/services/connectors/app/connectors/dropbox.py b/services/connectors/app/connectors/dropbox.py
index 7942c53b5..c2e7a95b4 100644
--- a/services/connectors/app/connectors/dropbox.py
+++ b/services/connectors/app/connectors/dropbox.py
@@ -49,9 +49,7 @@ class DropboxConnector(BaseConnector):
connector_name=cls.connector_name,
category=cls.connector_category,
description=(
- "Dropbox Business team event log: sharing, sign-in, "
- "member role changes, OAuth-app authorisations, "
- "policy edits."
+ "Dropbox Business team event log: sharing, sign-in, " "member role changes, OAuth-app authorisations, " "policy edits."
),
docs_url="/docs/connectors/dropbox",
fields=[
@@ -110,7 +108,8 @@ class DropboxConnector(BaseConnector):
return {"success": False, "connector": self.connector_id, "error": str(exc)}
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
- from datetime import datetime, timedelta, UTC
+ from datetime import UTC, datetime, timedelta
+
since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
out: list[dict[str, Any]] = []
cursor: str | None = None
@@ -172,7 +171,9 @@ class DropboxConnector(BaseConnector):
event_type = (raw.get("event_type") or {}).get(".tag") or raw.get("event_type", "")
if isinstance(event_type, dict):
event_type = event_type.get(".tag", "")
- category = (raw.get("event_category") or {}).get(".tag") if isinstance(raw.get("event_category"), dict) else raw.get("event_category", "")
+ category = (
+ (raw.get("event_category") or {}).get(".tag") if isinstance(raw.get("event_category"), dict) else raw.get("event_category", "")
+ ) # noqa: E501
actor = raw.get("actor") or {}
# actor is a tagged-union; flatten
actor_user = (actor.get("user") or {}) if isinstance(actor, dict) else {}
@@ -191,10 +192,7 @@ class DropboxConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("event_id") or "",
"title": event_type or "Dropbox event",
- "description": (
- f"event={event_type}; category={category}; "
- f"actor={actor_email}"
- ),
+ "description": (f"event={event_type}; category={category}; " f"actor={actor_email}"),
"severity": severity,
"actor": actor_email or actor_user.get("display_name"),
"actor_email": actor_email,
diff --git a/services/connectors/app/connectors/email_inbox.py b/services/connectors/app/connectors/email_inbox.py
index 48df0b0bd..433c3edcc 100644
--- a/services/connectors/app/connectors/email_inbox.py
+++ b/services/connectors/app/connectors/email_inbox.py
@@ -262,7 +262,7 @@ class EmailInboxConnector(BaseConnector):
if typ != "OK" or not fetched or not fetched[0]:
continue
raw_bytes = fetched[0][1]
- if not isinstance(raw_bytes, (bytes, bytearray)):
+ if not isinstance(raw_bytes, bytes | bytearray):
continue
msg = email.message_from_bytes(raw_bytes)
out.append(self._to_event(msg))
diff --git a/services/connectors/app/connectors/falco.py b/services/connectors/app/connectors/falco.py
index cb48ec7c9..cae9f80d7 100644
--- a/services/connectors/app/connectors/falco.py
+++ b/services/connectors/app/connectors/falco.py
@@ -94,7 +94,9 @@ class FalcoConnector(BaseConnector):
{"value": "ALERT", "label": "ALERT"},
{"value": "EMERGENCY", "label": "EMERGENCY"},
],
- help_text=("Drop events whose Falco priority is below this threshold. Defaults to DEBUG so nothing is filtered server-side."),
+ help_text=(
+ "Drop events whose Falco priority is below this threshold. Defaults to DEBUG so nothing is filtered server-side."
+ ), # noqa: E501
),
],
oauth=OAuthHints(supported_in_hosted=False),
diff --git a/services/connectors/app/connectors/fleetdm.py b/services/connectors/app/connectors/fleetdm.py
index 8defc5d9f..65a940037 100644
--- a/services/connectors/app/connectors/fleetdm.py
+++ b/services/connectors/app/connectors/fleetdm.py
@@ -340,7 +340,7 @@ class FleetDMConnector(BaseConnector):
def _parse_iso(value: Any) -> float | None:
if value is None:
return None
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return float(value)
if isinstance(value, str):
try:
diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.py
index a86f4946e..905286496 100644
--- a/services/connectors/app/connectors/github.py
+++ b/services/connectors/app/connectors/github.py
@@ -380,9 +380,7 @@ class GitHubConnector(BaseConnector):
async with httpx.AsyncClient(timeout=15.0) as client:
try:
- repo_resp = await client.get(
- f"{_BASE}/repos/{owner_repo}", headers=self._headers()
- )
+ repo_resp = await client.get(f"{_BASE}/repos/{owner_repo}", headers=self._headers())
except Exception as exc: # noqa: BLE001
return {"error": str(exc), "snapshot_freshness": "unavailable"}
if repo_resp.status_code != 200:
diff --git a/services/connectors/app/connectors/lacework.py b/services/connectors/app/connectors/lacework.py
index a7a7a2c88..d56846afc 100644
--- a/services/connectors/app/connectors/lacework.py
+++ b/services/connectors/app/connectors/lacework.py
@@ -168,9 +168,7 @@ class LaceworkConnector(BaseConnector):
"startTime": start.strftime("%Y-%m-%dT%H:%M:%SZ"),
"endTime": end.strftime("%Y-%m-%dT%H:%M:%SZ"),
},
- "filters": [
- {"field": "status", "expression": "eq", "value": "NonCompliant"}
- ],
+ "filters": [{"field": "status", "expression": "eq", "value": "NonCompliant"}],
},
)
if ce_resp.status_code == 200:
diff --git a/services/connectors/app/connectors/osctrl.py b/services/connectors/app/connectors/osctrl.py
index a5ef9107e..4f1164507 100644
--- a/services/connectors/app/connectors/osctrl.py
+++ b/services/connectors/app/connectors/osctrl.py
@@ -305,7 +305,7 @@ def _parse_epoch(value: Any) -> float | None:
"""Best-effort conversion of osctrl's `created_at` to epoch seconds."""
if value is None:
return None
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return float(value)
if isinstance(value, str):
try:
diff --git a/services/connectors/app/connectors/pagerduty.py b/services/connectors/app/connectors/pagerduty.py
index acffa8310..b6c619bce 100644
--- a/services/connectors/app/connectors/pagerduty.py
+++ b/services/connectors/app/connectors/pagerduty.py
@@ -66,7 +66,9 @@ class PagerDutyConnector(BaseConnector):
"Subdomain (optional)",
required=False,
placeholder="acme",
- help_text=("Your acme.pagerduty.com subdomain. Used to build clickable links in normalised events; not required for ingestion."),
+ help_text=(
+ "Your acme.pagerduty.com subdomain. Used to build clickable links in normalised events; not required for ingestion."
+ ), # noqa: E501
),
],
oauth=OAuthHints(
@@ -286,15 +288,21 @@ class PagerDutyConnector(BaseConnector):
assignees = raw.get("assignments") or []
assignee_email = None
if assignees and isinstance(assignees[0], dict):
- assignee_email = ((assignees[0].get("assignee") or {}).get("summary")) if isinstance(assignees[0].get("assignee"), dict) else None
+ assignee_email = (
+ ((assignees[0].get("assignee") or {}).get("summary")) if isinstance(assignees[0].get("assignee"), dict) else None
+ ) # noqa: E501
- link = raw.get("html_url") or (f"https://{self._subdomain}.pagerduty.com/incidents/{raw.get('id')}" if self._subdomain and raw.get("id") else None)
+ link = raw.get("html_url") or (
+ f"https://{self._subdomain}.pagerduty.com/incidents/{raw.get('id')}" if self._subdomain and raw.get("id") else None
+ ) # noqa: E501
return {
"source": self.connector_id,
"external_id": f"pagerduty-incident-{raw.get('id', raw.get('incident_number', ''))}",
"title": raw.get("title") or raw.get("description") or "PagerDuty incident",
- "description": (f"service={service or 'unknown'}; status={status}; urgency={urgency}; priority={priority_name or 'none'}; url={link or 'n/a'}"),
+ "description": (
+ f"service={service or 'unknown'}; status={status}; urgency={urgency}; priority={priority_name or 'none'}; url={link or 'n/a'}" # noqa: E501
+ ), # noqa: E501
"severity": severity,
"actor": assignee_email,
"actor_email": assignee_email,
@@ -320,7 +328,9 @@ class PagerDutyConnector(BaseConnector):
"source": self.connector_id,
"external_id": f"pagerduty-audit-{raw.get('id', '')}",
"title": f"PagerDuty audit: {action}",
- "description": (f"actor={actor_email or 'unknown'}; action={action}; method={raw.get('method', {}).get('type', '') if isinstance(raw.get('method'), dict) else ''}"),
+ "description": (
+ f"actor={actor_email or 'unknown'}; action={action}; method={raw.get('method', {}).get('type', '') if isinstance(raw.get('method'), dict) else ''}" # noqa: E501
+ ), # noqa: E501
"severity": severity,
"actor": actor_email,
"actor_email": actor_email,
diff --git a/services/connectors/app/connectors/snowflake.py b/services/connectors/app/connectors/snowflake.py
index 0d0767957..239f6e60a 100644
--- a/services/connectors/app/connectors/snowflake.py
+++ b/services/connectors/app/connectors/snowflake.py
@@ -141,9 +141,10 @@ class SnowflakeConnector(BaseConnector):
run without a real key."""
try:
from cryptography.hazmat.primitives.serialization import (
+ Encoding,
+ PublicFormat,
load_pem_private_key,
)
- from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
priv = load_pem_private_key(self._private_key_pem.encode(), password=None)
der = priv.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
@@ -169,9 +170,7 @@ class SnowflakeConnector(BaseConnector):
"exp": now + 3600,
}
signing_input = (
- _b64url(json.dumps(header, separators=(",", ":")).encode())
- + "."
- + _b64url(json.dumps(payload, separators=(",", ":")).encode())
+ _b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + _b64url(json.dumps(payload, separators=(",", ":")).encode())
).encode()
priv = serialization.load_pem_private_key(self._private_key_pem.encode(), password=None)
signature = priv.sign(signing_input, padding.PKCS1v15(), hashes.SHA256())
@@ -203,7 +202,7 @@ class SnowflakeConnector(BaseConnector):
payload = resp.json() or {}
cols = [c.get("name") for c in payload.get("resultSetMetaData", {}).get("rowType") or []]
rows = payload.get("data") or []
- return [dict(zip(cols, row)) for row in rows]
+ return [dict(zip(cols, row, strict=False)) for row in rows]
async def test_connection(self) -> dict[str, Any]:
try:
@@ -307,10 +306,7 @@ class SnowflakeConnector(BaseConnector):
"source": self.connector_id,
"stream": "login_history",
"external_id": raw.get("EVENT_ID") or "",
- "title": (
- f"Snowflake login {'success' if is_success else 'failure'} "
- f"({raw.get('USER_NAME')})"
- ),
+ "title": (f"Snowflake login {'success' if is_success else 'failure'} " f"({raw.get('USER_NAME')})"),
"description": raw.get("ERROR_MESSAGE") or raw.get("REPORTED_CLIENT_TYPE"),
"severity": severity,
"actor": raw.get("USER_NAME"),
diff --git a/services/connectors/app/connectors/sublime_security.py b/services/connectors/app/connectors/sublime_security.py
index 6d5bea73b..0486155e5 100644
--- a/services/connectors/app/connectors/sublime_security.py
+++ b/services/connectors/app/connectors/sublime_security.py
@@ -168,10 +168,7 @@ class SublimeSecurityConnector(BaseConnector):
"source": self.connector_id,
"external_id": raw.get("id") or raw.get("message_id") or "",
"title": raw.get("subject") or rule_name or "Sublime Security message",
- "description": (
- f"verdict={verdict}; rule={rule_name}; "
- f"from={sender.get('email')}; to={recipient}"
- ),
+ "description": (f"verdict={verdict}; rule={rule_name}; " f"from={sender.get('email')}; to={recipient}"),
"severity": severity,
"actor": sender.get("email"),
"actor_email": sender.get("email"),
diff --git a/services/connectors/app/connectors/sysdig.py b/services/connectors/app/connectors/sysdig.py
index 25e3a676c..4fe385165 100644
--- a/services/connectors/app/connectors/sysdig.py
+++ b/services/connectors/app/connectors/sysdig.py
@@ -76,10 +76,7 @@ class SysdigConnector(BaseConnector):
"api_token",
"secret",
"API Token",
- help_text=(
- "Sysdig Secure API token. Settings → API → Tokens. "
- "Needs read access to Secure Events."
- ),
+ help_text=("Sysdig Secure API token. Settings → API → Tokens. " "Needs read access to Secure Events."),
),
],
)
@@ -214,12 +211,7 @@ class SysdigConnector(BaseConnector):
# canonical Falco "you do not want to see this in prod" signals and
# are never benign once they fire.
rule_lower = rule.lower()
- if (
- "drift" in rule_lower
- or "tampering" in rule_lower
- or "terminal shell" in rule_lower
- or "shell in container" in rule_lower
- ):
+ if "drift" in rule_lower or "tampering" in rule_lower or "terminal shell" in rule_lower or "shell in container" in rule_lower:
sev = "high"
host = labels.get("host.hostname") or labels.get("kubernetes.node.name") or raw.get("hostname")
ns = labels.get("kubernetes.namespace.name")
diff --git a/services/connectors/app/connectors/tines.py b/services/connectors/app/connectors/tines.py
index bc642cc56..f3dc9bb4f 100644
--- a/services/connectors/app/connectors/tines.py
+++ b/services/connectors/app/connectors/tines.py
@@ -69,8 +69,7 @@ class TinesConnector(BaseConnector):
"Tines tenant URL",
placeholder="https://acme.tines.com",
help_text=(
- "Your Tines tenant URL, including scheme. For self-hosted "
- "deployments use the full HTTPS URL of the Rails app."
+ "Your Tines tenant URL, including scheme. For self-hosted " "deployments use the full HTTPS URL of the Rails app."
),
),
Field(
@@ -333,7 +332,9 @@ class TinesConnector(BaseConnector):
"source": self.connector_id,
"external_id": f"tines-case-{raw.get('id', '')}",
"title": f"Tines case: {case_name}",
- "description": (f"status={status}; record_severity={record_sev}; story_id={raw.get('story_id', '')}; assignee={assignee or 'unassigned'}"),
+ "description": (
+ f"status={status}; record_severity={record_sev}; story_id={raw.get('story_id', '')}; assignee={assignee or 'unassigned'}"
+ ), # noqa: E501
"severity": severity,
"actor": assignee or "unassigned",
"actor_email": assignee,
diff --git a/services/connectors/app/connectors/vault.py b/services/connectors/app/connectors/vault.py
index abdbe2f2c..189ba345d 100644
--- a/services/connectors/app/connectors/vault.py
+++ b/services/connectors/app/connectors/vault.py
@@ -198,11 +198,12 @@ class VaultConnector(BaseConnector):
if isinstance(ts, str):
try:
from datetime import datetime
+
parsed = datetime.fromisoformat(ts.replace("Z", "+00:00"))
ts_epoch = parsed.timestamp()
except Exception:
ts_epoch = cutoff
- elif isinstance(ts, (int, float)):
+ elif isinstance(ts, int | float):
ts_epoch = float(ts)
else:
ts_epoch = cutoff
diff --git a/services/connectors/app/federated/query.py b/services/connectors/app/federated/query.py
index 023e6b5cb..aba128570 100644
--- a/services/connectors/app/federated/query.py
+++ b/services/connectors/app/federated/query.py
@@ -81,7 +81,7 @@ class Indicator:
if self.operator not in _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:
+ if not isinstance(self.value, list | tuple) or not self.value:
raise QueryError("indicator with operator='in' requires a non-empty list value")
elif self.value is None:
raise QueryError(f"indicator.value must not be None for operator '{self.operator}'")
diff --git a/services/connectors/app/federated/translators/esql.py b/services/connectors/app/federated/translators/esql.py
index 219f8ecbf..1241cfc2e 100644
--- a/services/connectors/app/federated/translators/esql.py
+++ b/services/connectors/app/federated/translators/esql.py
@@ -23,7 +23,7 @@ from app.federated.query import Indicator, QueryError, UnifiedQuery
def _esql_quote(value: Any) -> str:
if isinstance(value, bool):
return "true" if value else "false"
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return str(value)
text = str(value)
escaped = text.replace("\\", "\\\\").replace('"', '\\"')
diff --git a/services/connectors/app/federated/translators/kql.py b/services/connectors/app/federated/translators/kql.py
index 09e158ebf..5c0c1d549 100644
--- a/services/connectors/app/federated/translators/kql.py
+++ b/services/connectors/app/federated/translators/kql.py
@@ -25,7 +25,7 @@ from app.federated.query import Indicator, QueryError, UnifiedQuery
def _kql_quote(value: Any) -> str:
if isinstance(value, bool):
return "true" if value else "false"
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return str(value)
text = str(value)
escaped = text.replace("\\", "\\\\").replace('"', '\\"')
diff --git a/services/connectors/app/federated/translators/spl.py b/services/connectors/app/federated/translators/spl.py
index 338dd32f4..019786154 100644
--- a/services/connectors/app/federated/translators/spl.py
+++ b/services/connectors/app/federated/translators/spl.py
@@ -28,7 +28,7 @@ def _spl_quote(value: Any) -> str:
"""
if isinstance(value, bool):
return "true" if value else "false"
- if isinstance(value, (int, float)):
+ if isinstance(value, int | float):
return str(value)
text = str(value)
escaped = text.replace("\\", "\\\\").replace('"', '\\"')
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 795c8fd87..2fcb305fe 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -754,7 +754,7 @@ def _extract_last_event_at(events: list[dict[str, Any]]) -> datetime | None:
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
except ValueError:
parsed = None
- elif isinstance(raw, (int, float)):
+ elif isinstance(raw, int | float):
try:
parsed = datetime.fromtimestamp(float(raw), tz=UTC)
except (OverflowError, OSError, ValueError):
diff --git a/services/connectors/app/security/credential_vault.py b/services/connectors/app/security/credential_vault.py
index 0d05133be..6d3f1ed98 100644
--- a/services/connectors/app/security/credential_vault.py
+++ b/services/connectors/app/security/credential_vault.py
@@ -113,7 +113,7 @@ class CredentialVault:
if isinstance(payload, Mapping):
out: dict[str, Any] = {}
for k, v in payload.items():
- if secret_keys is not None and k not in secret_keys and not isinstance(v, (Mapping, list)):
+ if secret_keys is not None and k not in secret_keys and not isinstance(v, Mapping | list):
out[k] = v
else:
out[k] = self._walk(v, encrypt=encrypt, secret_keys=secret_keys, _key=k)
diff --git a/services/connectors/tests/connectors/test_cloudflare_zt.py b/services/connectors/tests/connectors/test_cloudflare_zt.py
index dbbee4a12..ba2d98ed3 100644
--- a/services/connectors/tests/connectors/test_cloudflare_zt.py
+++ b/services/connectors/tests/connectors/test_cloudflare_zt.py
@@ -108,12 +108,8 @@ async def test_fetch_alerts_uses_pagination(fixture):
@respx.mock
async def test_test_connection_success():
c = CloudflareZTConnector(mode="access", account_id="a", api_token="t")
- respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(
- 200, json={"result": {"status": "active"}}
- )
- respx.get(
- "https://api.cloudflare.com/client/v4/accounts/a/access/logs/access_requests"
- ).respond(200, json={"result": []})
+ respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(200, json={"result": {"status": "active"}})
+ respx.get("https://api.cloudflare.com/client/v4/accounts/a/access/logs/access_requests").respond(200, json={"result": []})
res = await c.test_connection()
assert res["success"] is True
assert res["mode"] == "access"
@@ -123,9 +119,7 @@ async def test_test_connection_success():
@respx.mock
async def test_test_connection_token_inactive():
c = CloudflareZTConnector(mode="access", account_id="a", api_token="t")
- respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(
- 200, json={"result": {"status": "disabled"}}
- )
+ respx.get("https://api.cloudflare.com/client/v4/user/tokens/verify").respond(200, json={"result": {"status": "disabled"}})
res = await c.test_connection()
assert res["success"] is False
assert "disabled" in res["error"]
diff --git a/services/connectors/tests/connectors/test_sysdig.py b/services/connectors/tests/connectors/test_sysdig.py
index 13214173f..aa95e2416 100644
--- a/services/connectors/tests/connectors/test_sysdig.py
+++ b/services/connectors/tests/connectors/test_sysdig.py
@@ -75,6 +75,7 @@ async def test_fetch_alerts_uses_pagination(fixture):
# Pad page-1 to exactly _PER_PAGE=100 to force a second iteration via
# the cursor branch. _PER_PAGE is the connector's internal pagination size.
from app.connectors.sysdig import _PER_PAGE
+
fat_page = (fixture * 50)[:_PER_PAGE]
page1 = {"data": fat_page, "page": {"next": "cursor-2"}}
page2 = {"data": fixture[:1], "page": {}}
diff --git a/services/connectors/tests/test_azure_connectors.py b/services/connectors/tests/test_azure_connectors.py
index 73ea04fca..1baa9ca2b 100644
--- a/services/connectors/tests/test_azure_connectors.py
+++ b/services/connectors/tests/test_azure_connectors.py
@@ -43,9 +43,9 @@ def test_azure_entra_schema_has_required_fields():
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"
- )
+ assert (
+ "subscription_id" in field_names
+ ), "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"
@@ -393,9 +393,7 @@ async def test_azure_defender_get_resource_config_non_200_returns_empty():
respx.post(f"https://login.microsoftonline.com/{_TENANT}/oauth2/v2.0/token").mock(
return_value=httpx.Response(200, json={"access_token": "abc", "expires_in": 3600})
)
- respx.get("https://graph.microsoft.com/v1.0/security/alerts_v2/missing").mock(
- return_value=httpx.Response(404, text="not found")
- )
+ respx.get("https://graph.microsoft.com/v1.0/security/alerts_v2/missing").mock(return_value=httpx.Response(404, text="not found"))
connector = AzureDefenderConnector(_TENANT, _CLIENT, _SECRET)
assert await connector.get_resource_config("missing") == {}
diff --git a/services/connectors/tests/test_gcp_connectors.py b/services/connectors/tests/test_gcp_connectors.py
index 7779c5a45..6cd4a56f3 100644
--- a/services/connectors/tests/test_gcp_connectors.py
+++ b/services/connectors/tests/test_gcp_connectors.py
@@ -446,9 +446,7 @@ async def test_scc_get_resource_config_non_200_returns_empty(fake_sa_json):
return_value=httpx.Response(200, json={"access_token": "tok-abc", "expires_in": 3600})
)
finding_name = f"organizations/{_ORG}/sources/888/findings/gone"
- respx.get(f"https://securitycenter.googleapis.com/v1/{finding_name}").mock(
- return_value=httpx.Response(404, text="not found")
- )
+ respx.get(f"https://securitycenter.googleapis.com/v1/{finding_name}").mock(return_value=httpx.Response(404, text="not found"))
connector = GCPSCCConnector(_ORG, fake_sa_json)
assert await connector.get_resource_config(finding_name) == {}
diff --git a/services/connectors/tests/test_schemas.py b/services/connectors/tests/test_schemas.py
index 032d65b61..4582dcc5a 100644
--- a/services/connectors/tests/test_schemas.py
+++ b/services/connectors/tests/test_schemas.py
@@ -38,9 +38,9 @@ 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 schema.connector_id == connector_id, (
- f"{cls.__name__}.schema().connector_id ({schema.connector_id!r}) does not match registry key ({connector_id!r})"
- )
+ assert (
+ schema.connector_id == connector_id
+ ), f"{cls.__name__}.schema().connector_id ({schema.connector_id!r}) does not match registry key ({connector_id!r})"
def test_schema_metadata_is_well_formed(registry):
@@ -93,6 +93,6 @@ def test_secret_fields_are_marked_secret(registry):
for cls in registry.values():
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 {field.type!r}, expected 'secret'"
- )
+ assert (
+ field.type == "secret"
+ ), f"{cls.__name__}.{field.name}: looks like a credential but type is {field.type!r}, expected 'secret'"
diff --git a/services/fusion/app/services/entity_risk.py b/services/fusion/app/services/entity_risk.py
index 7126a9b6b..341ddccf5 100644
--- a/services/fusion/app/services/entity_risk.py
+++ b/services/fusion/app/services/entity_risk.py
@@ -164,7 +164,7 @@ class EntityRiskEngine:
raw = await self._redis.zrevrange(key, 0, max(0, limit - 1), withscores=True)
records: list[EntityRiskRecord] = []
for member, _zscore in raw:
- entity = member.decode() if isinstance(member, (bytes, bytearray)) else member
+ entity = member.decode() if isinstance(member, bytes | bytearray) else member
entity_type, _, entity_value = entity.partition("::")
rec = await self._load(str(tenant_id), entity_type, entity_value)
if rec is None:
@@ -335,7 +335,7 @@ class EntityRiskEngine:
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/slack-bot/tests/test_approval_audit.py b/services/slack-bot/tests/test_approval_audit.py
index 016363435..f9ee2d913 100644
--- a/services/slack-bot/tests/test_approval_audit.py
+++ b/services/slack-bot/tests/test_approval_audit.py
@@ -29,9 +29,7 @@ def test_event_as_dict_includes_required_fields():
def test_event_as_dict_omits_optional_fields_when_unset():
- event = ApprovalAuditEvent(
- case_id="c", action_id="a", approver_id="u", decision="approved"
- )
+ event = ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved")
d = event.as_dict()
assert "error" not in d
assert "metadata" not in d
@@ -49,9 +47,7 @@ async def test_in_memory_sink_records_events():
@pytest.mark.asyncio
async def test_null_sink_no_op():
- await NullAuditSink().record(
- ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved")
- )
+ await NullAuditSink().record(ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved"))
@pytest.mark.asyncio
@@ -98,6 +94,4 @@ async def test_structlog_sink_swallows_logger_failure():
sink = StructlogAuditSink(logger=_BrokenLogger())
# Should not raise.
- await sink.record(
- ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved")
- )
+ await sink.record(ApprovalAuditEvent(case_id="c", action_id="a", approver_id="u", decision="approved"))
diff --git a/services/slack-bot/tests/test_approval_timeout.py b/services/slack-bot/tests/test_approval_timeout.py
index 54157e010..701812feb 100644
--- a/services/slack-bot/tests/test_approval_timeout.py
+++ b/services/slack-bot/tests/test_approval_timeout.py
@@ -46,9 +46,7 @@ class _RecordingClient:
async def test_timer_fires_safe_default_reject_and_writes_audit():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(
- approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
- )
+ scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
task = scheduler.schedule(
"action-1",
@@ -76,13 +74,9 @@ async def test_timer_fires_safe_default_reject_and_writes_audit():
async def test_timer_safe_default_approve_invokes_approve():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(
- approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
- )
+ scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
- task = scheduler.schedule(
- "action-2", timeout_seconds=0.01, safe_default="approved", case_id="case-2"
- )
+ task = scheduler.schedule("action-2", timeout_seconds=0.01, safe_default="approved", case_id="case-2")
_ = await task
assert client.approve_calls == ["action-2"]
@@ -93,13 +87,9 @@ async def test_timer_safe_default_approve_invokes_approve():
async def test_cancel_before_fire_suppresses_fallback():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(
- approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
- )
+ scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
- task = scheduler.schedule(
- "action-3", timeout_seconds=5.0, safe_default="rejected", case_id="case-3"
- )
+ task = scheduler.schedule("action-3", timeout_seconds=5.0, safe_default="rejected", case_id="case-3")
assert scheduler.cancel("action-3") is True
# Subsequent cancel is a no-op.
assert scheduler.cancel("action-3") is False
@@ -116,16 +106,10 @@ async def test_cancel_before_fire_suppresses_fallback():
async def test_reschedule_replaces_existing_timer():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(
- approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
- )
+ scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
- first = scheduler.schedule(
- "action-4", timeout_seconds=5.0, safe_default="rejected", case_id="case-4"
- )
- second = scheduler.schedule(
- "action-4", timeout_seconds=0.01, safe_default="rejected", case_id="case-4"
- )
+ first = scheduler.schedule("action-4", timeout_seconds=5.0, safe_default="rejected", case_id="case-4")
+ second = scheduler.schedule("action-4", timeout_seconds=0.01, safe_default="rejected", case_id="case-4")
assert first.cancelled() or first is not second
_ = await second
@@ -138,13 +122,9 @@ async def test_reschedule_replaces_existing_timer():
async def test_fallback_call_failure_still_audits_with_error():
client = _RecordingClient(fail=True)
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(
- approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
- )
+ scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
- task = scheduler.schedule(
- "action-5", timeout_seconds=0.01, safe_default="rejected", case_id="case-5"
- )
+ task = scheduler.schedule("action-5", timeout_seconds=0.01, safe_default="rejected", case_id="case-5")
_ = await task
assert client.reject_calls == []
@@ -158,9 +138,7 @@ async def test_fallback_call_failure_still_audits_with_error():
async def test_aclose_cancels_all_pending_timers():
client = _RecordingClient()
audit = InMemoryAuditSink()
- scheduler = ApprovalTimeoutScheduler(
- approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit
- )
+ scheduler = ApprovalTimeoutScheduler(approve_fn=client.approve, reject_fn=client.reject, audit_sink=audit)
scheduler.schedule("a-1", timeout_seconds=5.0, safe_default="rejected")
scheduler.schedule("a-2", timeout_seconds=5.0, safe_default="rejected")
diff --git a/services/slack-bot/tests/test_hmac_verify.py b/services/slack-bot/tests/test_hmac_verify.py
index da9b63bcd..ad52a59f6 100644
--- a/services/slack-bot/tests/test_hmac_verify.py
+++ b/services/slack-bot/tests/test_hmac_verify.py
@@ -18,7 +18,6 @@ import time
import pytest
from app.services.hmac_verify import HmacVerificationError, sign, verify
-
SECRET = "test-secret-not-real"
diff --git a/services/teams-bot/app/callbacks.py b/services/teams-bot/app/callbacks.py
index e68f006e8..1c6b7d6c0 100644
--- a/services/teams-bot/app/callbacks.py
+++ b/services/teams-bot/app/callbacks.py
@@ -115,9 +115,7 @@ async def handle_card_action(
return CallbackResult(
decision="rejected_unknown_verb",
ok=False,
- card=decision_card(
- decision="rejected", action_id=action_id, decided_by=approver_id
- ),
+ card=decision_card(decision="rejected", action_id=action_id, decided_by=approver_id),
error=f"unknown verb {verb!r}",
)
@@ -167,9 +165,7 @@ async def handle_card_action(
decision=decision_label,
ok=False,
error=str(exc),
- card=decision_card(
- decision=decision_label, action_id=action_id, decided_by=approver_id
- ),
+ card=decision_card(decision=decision_label, action_id=action_id, decided_by=approver_id),
)
if audit_sink is not None:
@@ -186,9 +182,7 @@ async def handle_card_action(
return CallbackResult(
decision=decision_label,
ok=True,
- card=decision_card(
- decision=decision_label, action_id=action_id, decided_by=approver_id
- ),
+ card=decision_card(decision=decision_label, action_id=action_id, decided_by=approver_id),
)
diff --git a/services/teams-bot/app/main.py b/services/teams-bot/app/main.py
index 130cdf79b..be3fa3ac3 100644
--- a/services/teams-bot/app/main.py
+++ b/services/teams-bot/app/main.py
@@ -32,8 +32,7 @@ from app.callbacks import callback_max_age_seconds, handle_card_action
app = FastAPI(
title="AiSOC Teams Bot",
description=(
- "ChatOps adapter for Microsoft Teams. Renders Adaptive Card "
- "approval prompts and verifies the signed callback payload."
+ "ChatOps adapter for Microsoft Teams. Renders Adaptive Card " "approval prompts and verifies the signed callback payload."
),
version="0.1.0",
)
@@ -53,11 +52,7 @@ def _resolve_approver(activity: dict[str, Any]) -> str:
identifier (guest users, anon links).
"""
sender = activity.get("from") or {}
- return (
- str(sender.get("aadObjectId") or "").strip()
- or str(sender.get("id") or "").strip()
- or "unknown"
- )
+ return str(sender.get("aadObjectId") or "").strip() or str(sender.get("id") or "").strip() or "unknown"
@app.post("/teams/messages")
diff --git a/services/teams-bot/app/services/aisoc_clients.py b/services/teams-bot/app/services/aisoc_clients.py
index 2109347fb..a65c23e16 100644
--- a/services/teams-bot/app/services/aisoc_clients.py
+++ b/services/teams-bot/app/services/aisoc_clients.py
@@ -77,13 +77,7 @@ class _FallbackActionsClient:
def _try_import_slack_bot_client():
"""Best-effort import of the Slack bot's actions client."""
- candidate = (
- Path(__file__).resolve().parents[3]
- / "slack-bot"
- / "app"
- / "services"
- / "aisoc_clients.py"
- )
+ candidate = Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "aisoc_clients.py"
if not candidate.exists():
return None
spec = importlib.util.spec_from_file_location("_aisoc_slack_bot_clients", candidate)
@@ -116,13 +110,7 @@ class _NullAuditSink:
def build_audit_sink() -> _AuditSink:
"""Construct the shared audit sink if available; null sink otherwise."""
- candidate = (
- Path(__file__).resolve().parents[3]
- / "slack-bot"
- / "app"
- / "services"
- / "approval_audit.py"
- )
+ candidate = Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "approval_audit.py"
if not candidate.exists():
return _NullAuditSink()
spec = importlib.util.spec_from_file_location("_aisoc_audit", candidate)
diff --git a/services/teams-bot/app/services/hmac_signer.py b/services/teams-bot/app/services/hmac_signer.py
index 225510746..c79f35bd0 100644
--- a/services/teams-bot/app/services/hmac_signer.py
+++ b/services/teams-bot/app/services/hmac_signer.py
@@ -32,9 +32,7 @@ from typing import Any
# We resolve the module by absolute path so the Teams bot can be unit-
# tested in isolation (it doesn't share a pyproject with the Slack bot
# but the two repos co-evolve — see the README).
-_SLACK_BOT_HMAC_PATH = (
- Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "hmac_verify.py"
-)
+_SLACK_BOT_HMAC_PATH = Path(__file__).resolve().parents[3] / "slack-bot" / "app" / "services" / "hmac_verify.py"
_module_name = "_aisoc_hmac_verify"
_spec = importlib.util.spec_from_file_location(_module_name, _SLACK_BOT_HMAC_PATH)
@@ -74,9 +72,7 @@ def sign_card_data(
Mint the ``data`` payload attached to an Adaptive Card
``Action.Submit`` button.
"""
- payload = canonical_payload(
- verb=verb, action_id=action_id, case_id=case_id, issued_at=issued_at
- )
+ payload = canonical_payload(verb=verb, action_id=action_id, case_id=case_id, issued_at=issued_at)
return {
"verb": verb,
"action_id": action_id,
@@ -100,9 +96,7 @@ def verify_card_data(payload: dict[str, Any], *, secret: str, max_age_seconds: i
signature = str(payload.get("signature") or "")
if not verb or not action_id or issued_at is None:
raise HmacVerificationError("Missing required fields on signed payload")
- canonical = canonical_payload(
- verb=verb, action_id=action_id, case_id=case_id, issued_at=int(issued_at)
- )
+ canonical = canonical_payload(verb=verb, action_id=action_id, case_id=case_id, issued_at=int(issued_at))
verify(
canonical,
signature,