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.

chore(security): resolve all open CodeQL alerts (#133)

Beenu Arora424a0956830e
diff --git a/services/agents/app/context/bundle.py b/services/agents/app/context/bundle.py
index aeb28c346..530cdfcfe 100644
--- a/services/agents/app/context/bundle.py
+++ b/services/agents/app/context/bundle.py
@@ -237,8 +237,10 @@ class ThreatIntelMatch(BaseModel):
# Allowed top-level keys in ``summary_for_llm`` — kept here (not in
# ``app/llm/contract.py``) so the model is the source of truth and the
-# contract validator can import this whitelist.
-_LLM_SAFE_KEYS = (
+# contract validator can import this whitelist. Public (no leading
+# underscore) because the contract tests and downstream validators
+# import this tuple directly.
+LLM_SAFE_KEYS = (
"incident_id",
"alert_summary",
"entity_count",
@@ -341,7 +343,7 @@ class ContextBundle(BaseModel):
def summary_for_llm(self) -> dict[str, Any]:
"""Pre-digested, contract-safe summary for LLM prompts.
- Every key returned here is on ``_LLM_SAFE_KEYS`` and contains either
+ Every key returned here is on ``LLM_SAFE_KEYS`` and contains either
a scalar, a small list of scalars, or a list of short string summaries
— never raw OCSF / log payloads. ``LLMInputContract`` (T2.3) treats
the output of this method as the canonical safe shape.
diff --git a/services/agents/tests/test_context_bundle.py b/services/agents/tests/test_context_bundle.py
index dab629292..7a6bfa20a 100644
--- a/services/agents/tests/test_context_bundle.py
+++ b/services/agents/tests/test_context_bundle.py
@@ -44,7 +44,7 @@ from app.context import ( # noqa: E402
EntityRef,
extract_entities,
)
-from app.context.bundle import _LLM_SAFE_KEYS # noqa: E402
+from app.context.bundle import LLM_SAFE_KEYS # noqa: E402
from app.models.state import InvestigationState # noqa: E402
_DATASET_PATH = _TESTS_DIR / "eval_data" / "synthetic_incidents.json"
@@ -197,7 +197,7 @@ class ContextBundleSummaryTests(unittest.TestCase):
)
summary = bundle.summary_for_llm()
for key in summary:
- self.assertIn(key, _LLM_SAFE_KEYS, f"unexpected key in summary_for_llm: {key}")
+ self.assertIn(key, LLM_SAFE_KEYS, f"unexpected key in summary_for_llm: {key}")
def test_prompt_context_lines_empty_when_bundle_empty(self) -> None:
bundle = ContextBundle(incident_id=uuid4())
diff --git a/services/agents/tests/test_fidelity_harness.py b/services/agents/tests/test_fidelity_harness.py
index 5a38217c8..6f4aa1417 100644
--- a/services/agents/tests/test_fidelity_harness.py
+++ b/services/agents/tests/test_fidelity_harness.py
@@ -67,8 +67,11 @@ def _load_expected() -> dict[str, object]:
def test_cicids_micro_fixture_present() -> None:
assert MICRO_FIXTURE.exists(), MICRO_FIXTURE
- # 100 flows + 1 header row.
- assert sum(1 for _ in MICRO_FIXTURE.open("r", encoding="utf-8")) == 101
+ # 100 flows + 1 header row. Read the file outside the assert so the file
+ # handle is properly closed (CodeQL ``py/side-effect-in-assert``).
+ with MICRO_FIXTURE.open("r", encoding="utf-8") as handle:
+ line_count = sum(1 for _ in handle)
+ assert line_count == 101
def test_cicids_loader_normalises_features() -> None:
diff --git a/services/agents/tests/test_graph_freshness.py b/services/agents/tests/test_graph_freshness.py
index 2fde85121..45a34f714 100644
--- a/services/agents/tests/test_graph_freshness.py
+++ b/services/agents/tests/test_graph_freshness.py
@@ -59,11 +59,17 @@ def _import_or_skip(mod_name: str, hint: str) -> Any:
The integration test should be invisible on a developer laptop that
hasn't installed the stack yet — skip beats fail.
+
+ ``pytest.skip()`` raises ``Skipped`` and never returns, but CodeQL
+ (``py/mixed-returns``) does not model it as ``NoReturn``, so we add
+ an explicit ``return None`` after it to make every control-flow path
+ end in an explicit ``return``.
"""
try:
return __import__(mod_name)
except ImportError:
pytest.skip(f"{mod_name} not installed locally — install {hint} to run this integration test")
+ return None
def _build_event(idx: int) -> dict:
@@ -119,6 +125,7 @@ def _ingest_event(httpx: Any, event: dict, tenant: str) -> None:
)
except Exception as exc: # noqa: BLE001
pytest.skip(f"ingest service unreachable at {INGEST_BASE_URL}: {exc}")
+ return # pytest.skip raises; this satisfies static analysers that ``resp`` is always bound below
if resp.status_code >= 500:
pytest.skip(f"ingest service unhealthy: {resp.status_code} {resp.text}")
assert resp.status_code < 400, resp.text
@@ -203,6 +210,7 @@ def test_graph_writer_does_not_block_fusion_on_failure() -> None:
)
except Exception as exc: # noqa: BLE001
pytest.skip(f"ingest service unreachable at {INGEST_BASE_URL}: {exc}")
+ return # pytest.skip raises; satisfies static analysers that ``resp`` is bound below
assert resp.status_code < 400, f"ingest returned {resp.status_code} — fusion should never block on graph: {resp.text}"
diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.py
index 1035c0696..4ee761ece 100644
--- a/services/api/app/api/v1/endpoints/alerts.py
+++ b/services/api/app/api/v1/endpoints/alerts.py
@@ -501,7 +501,7 @@ async def submit_alert(
extra={
"alert_id": str(cached.id),
"tenant_id": str(cached.tenant_id),
- "idempotency_key": idempotency_key,
+ "idempotency_key": _log_safe(idempotency_key),
},
)
return AlertResponse.model_validate(cached)
@@ -576,7 +576,7 @@ async def submit_alert(
"alert.submit.idempotency_race_no_row",
extra={
"tenant_id": str(current_user.tenant_id),
- "idempotency_key": idempotency_key,
+ "idempotency_key": _log_safe(idempotency_key),
},
)
raise HTTPException(
@@ -589,7 +589,7 @@ async def submit_alert(
extra={
"alert_id": str(cached.id),
"tenant_id": str(cached.tenant_id),
- "idempotency_key": idempotency_key,
+ "idempotency_key": _log_safe(idempotency_key),
},
)
return AlertResponse.model_validate(cached)
@@ -604,7 +604,7 @@ async def submit_alert(
"severity": alert.severity,
"events": len(sanitised_events),
"connector_type": _log_safe(payload.connector_type),
- "idempotency_key": idempotency_key,
+ "idempotency_key": _log_safe(idempotency_key),
"timestamps_clamped": "ts-clamped" in (alert.tags or []),
"redacted_keys": sanitise_stats.get("redacted", 0),
"truncated_events": sanitise_stats.get("truncated", 0),
diff --git a/services/api/app/api/v1/endpoints/waitlist.py b/services/api/app/api/v1/endpoints/waitlist.py
index b6e5bc14a..c11a8dbab 100644
--- a/services/api/app/api/v1/endpoints/waitlist.py
+++ b/services/api/app/api/v1/endpoints/waitlist.py
@@ -200,6 +200,22 @@ class WaitlistPatchRequest(BaseModel):
# ---------------------------------------------------------------------------
+def _log_safe(value: str | None) -> str | None:
+ """Strip CR/LF from a user-supplied string before it enters a log record.
+
+ The waitlist status fields are validated upstream (Pydantic
+ ``field_validator`` against ``ALLOWED_WAITLIST_STATUSES``) and cannot in
+ practice contain newlines, but static analysis (CodeQL
+ ``py/log-injection``) does not recognise the validator as a sanitiser.
+ This helper makes the cleansing explicit so the taint tracker treats the
+ value as safe, while remaining a no-op for any well-formed input.
+ """
+
+ if value is None:
+ return None
+ return value.replace("\r", "").replace("\n", " ")
+
+
def _client_ip(request: Request) -> str:
"""Resolve the source IP, trusting the proxy chain in front of us.
@@ -424,8 +440,8 @@ async def patch_entry(
"waitlist_status_transition",
extra={
"entry_id": str(entry_id),
- "previous": previous,
- "next": payload.status,
+ "previous": _log_safe(previous),
+ "next": _log_safe(payload.status),
"actor": str(user.user_id),
},
)
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index 3f8fe5c41..d131b4418 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -2410,10 +2410,13 @@ _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")
-# Per-invocation deterministic jitter source. Used sparingly — alert
-# offsets and tiny `ai_score` perturbations only — so re-runs stay
-# byte-identical even when the underlying random sequence is touched.
-_quick_rng = random.Random(20260513)
+# Per-invocation deterministic jitter source was previously declared here
+# (``_quick_rng = random.Random(20260513)``) for alert offset and ``ai_score``
+# perturbations. It has been removed because no call site reads from it any
+# more — keeping a global, never-used RNG drew a CodeQL
+# ``py/unused-global-variable`` warning and provided no behavioural value.
+# If deterministic jitter is reintroduced, declare the RNG inside the helper
+# that actually consumes it so it stays scoped and analysable.
def _parse_clock(value: str | None) -> datetime:
diff --git a/services/api/app/services/attack_chain.py b/services/api/app/services/attack_chain.py
index 4955988f0..d398c06c6 100644
--- a/services/api/app/services/attack_chain.py
+++ b/services/api/app/services/attack_chain.py
@@ -223,7 +223,8 @@ 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:
+ """Return the seed alert if it exists in the given tenant, else None."""
async def load_candidates_for_entities(
self,
@@ -232,7 +233,8 @@ class AttackChainLoader(Protocol):
start: datetime,
end: datetime,
exclude_ids: set[uuid.UUID],
- ) -> list[CandidateAlert]: ...
+ ) -> list[CandidateAlert]:
+ """Return candidate alerts sharing entities with the seed in ``[start, end]``."""
# ---------------------------------------------------------------------------
diff --git a/services/api/app/services/effective_permissions/service.py b/services/api/app/services/effective_permissions/service.py
index e6a759b64..330ad7aa9 100644
--- a/services/api/app/services/effective_permissions/service.py
+++ b/services/api/app/services/effective_permissions/service.py
@@ -63,9 +63,14 @@ def _default_snapshot_loader(provider: str) -> dict[str, Any]:
surfaces a 412 Precondition Failed ("no policy snapshot ingested yet").
"""
+ # ``provider`` is validated against ``SUPPORTED_PROVIDERS`` upstream, but
+ # CodeQL's ``py/log-injection`` taint analysis does not recognise the
+ # membership check as a sanitiser. Strip CR/LF explicitly so the value
+ # entering the log record cannot forge log lines.
+ safe_provider = provider.replace("\r", "").replace("\n", " ")
logger.warning(
"no production snapshot loader wired for provider=%s — returning {}",
- provider,
+ safe_provider,
)
return {}
diff --git a/services/api/app/services/email_approval.py b/services/api/app/services/email_approval.py
index 5f37fe2f7..293dcf72f 100644
--- a/services/api/app/services/email_approval.py
+++ b/services/api/app/services/email_approval.py
@@ -221,7 +221,8 @@ class MailDeliveryClient(Protocol):
html: str,
text: str,
from_addr: str | None = None,
- ) -> dict[str, Any]: ...
+ ) -> dict[str, Any]:
+ """Deliver an email and return a provider-specific response payload."""
class MailgunClient:
diff --git a/services/api/app/services/tenant_provision/provisioner.py b/services/api/app/services/tenant_provision/provisioner.py
index bcdb3786f..cff968748 100644
--- a/services/api/app/services/tenant_provision/provisioner.py
+++ b/services/api/app/services/tenant_provision/provisioner.py
@@ -272,8 +272,11 @@ def _build_admin_invite(
# Type alias for the seed-demo callback so tests can pass in a stub
-# that doesn't need a real database session.
-DemoSeederCallable = Callable[[AsyncSession, Tenant], "Any"]
+# that doesn't need a real database session. ``Any`` is referenced
+# unquoted so CodeQL (``py/unused-import``) sees the import as used —
+# the surrounding ``Callable[...]`` is a runtime expression, not a
+# stringified annotation, so the name must resolve at evaluation time.
+DemoSeederCallable = Callable[[AsyncSession, Tenant], Any]
async def provision_from_waitlist(
diff --git a/services/connectors/app/connectors/datadog.py b/services/connectors/app/connectors/datadog.py
index 05cce334c..b29eae301 100644
--- a/services/connectors/app/connectors/datadog.py
+++ b/services/connectors/app/connectors/datadog.py
@@ -43,7 +43,13 @@ _REGION_HOSTS: dict[str, str] = {
}
_LOGS_PER_PAGE = 100
-_EVENTS_PER_PAGE = 500
+# Note: the Datadog Events v1 API (``GET /api/v1/events``) is windowed by
+# ``start``/``end`` epoch seconds, not by an explicit page-size knob, so we
+# do not pass a ``limit`` here. Previously this module also declared an
+# ``_EVENTS_PER_PAGE`` constant that was never read — CodeQL flagged it as
+# ``py/unused-global-variable`` and it has been removed. If pagination is
+# added later, wire it into ``_fetch_events`` rather than reintroducing an
+# unused global.
_MAX_PAGES = 25
diff --git a/services/connectors/tests/connectors/test_confluence_audit.py b/services/connectors/tests/connectors/test_confluence_audit.py
index 065f5b24a..a39db03ca 100644
--- a/services/connectors/tests/connectors/test_confluence_audit.py
+++ b/services/connectors/tests/connectors/test_confluence_audit.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from pathlib import Path
+import app.connectors.confluence_audit as confluence_audit_module
import httpx
import pytest
import respx
@@ -93,15 +94,15 @@ async def test_fetch_alerts_uses_pagination(fixture):
respx.get(f"{_SITE}/wiki/rest/api/audit").mock(side_effect=handler)
connector = ConfluenceAuditConnector(_SITE, _EMAIL, _TOKEN)
- # Lower the page size to match the fixture.
- import app.connectors.confluence_audit as mod
-
- monkey_orig = mod._PAGE_SIZE # noqa: SLF001
+ # Lower the page size to match the fixture. We reuse the module-level
+ # ``confluence_audit_module`` alias rather than re-importing inline so
+ # CodeQL (``py/import-and-import-from``) sees a single import style.
+ monkey_orig = confluence_audit_module._PAGE_SIZE # noqa: SLF001
try:
- mod._PAGE_SIZE = 4 # type: ignore[assignment]
+ confluence_audit_module._PAGE_SIZE = 4 # type: ignore[assignment]
events = await connector.fetch_alerts(since_seconds=10**9)
finally:
- mod._PAGE_SIZE = monkey_orig # type: ignore[assignment]
+ confluence_audit_module._PAGE_SIZE = monkey_orig # type: ignore[assignment]
# First page returned 4 items, second page returned []; pagination
# terminated cleanly.
diff --git a/services/slack-bot/app/services/approval_audit.py b/services/slack-bot/app/services/approval_audit.py
index 6b48a20bc..b77db67d4 100644
--- a/services/slack-bot/app/services/approval_audit.py
+++ b/services/slack-bot/app/services/approval_audit.py
@@ -58,7 +58,7 @@ class ApprovalAuditEvent:
actor_ip: str | None = None
source: str = "slack" # "slack" | "teams" | "email" | "scheduler"
error: str | None = None
- timestamp: float = field(default_factory=lambda: time.time())
+ timestamp: float = field(default_factory=time.time)
metadata: dict[str, Any] | None = None
def as_dict(self) -> dict[str, Any]:
@@ -84,7 +84,7 @@ class ApprovalAuditSink(Protocol):
"""Anything that can swallow an :class:`ApprovalAuditEvent`."""
async def record(self, event: ApprovalAuditEvent) -> None: # pragma: no cover - protocol
- ...
+ """Persist an approval-audit event."""
class NullAuditSink:
diff --git a/services/slack-bot/app/services/approval_timeout.py b/services/slack-bot/app/services/approval_timeout.py
index 8e26c03b8..d3fa07a36 100644
--- a/services/slack-bot/app/services/approval_timeout.py
+++ b/services/slack-bot/app/services/approval_timeout.py
@@ -180,5 +180,5 @@ class ApprovalTimeoutScheduler:
# here — that's the whole point of the shutdown path — so
# suppress it explicitly alongside any tear-down errors.
with contextlib.suppress(asyncio.CancelledError, Exception):
- await task
+ _ = await task
self._timers.clear()
diff --git a/services/slack-bot/tests/test_approval_timeout.py b/services/slack-bot/tests/test_approval_timeout.py
index e8e91fdea..701812feb 100644
--- a/services/slack-bot/tests/test_approval_timeout.py
+++ b/services/slack-bot/tests/test_approval_timeout.py
@@ -55,7 +55,7 @@ async def test_timer_fires_safe_default_reject_and_writes_audit():
case_id="case-1",
channel="C7",
)
- await task
+ _ = await task
assert client.reject_calls == ["action-1"]
assert client.approve_calls == []
@@ -77,7 +77,7 @@ async def test_timer_safe_default_approve_invokes_approve():
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")
- await task
+ _ = await task
assert client.approve_calls == ["action-2"]
assert audit.events[0].metadata == {"safe_default": "approved"}
@@ -96,7 +96,7 @@ async def test_cancel_before_fire_suppresses_fallback():
# Let the cancellation propagate.
await asyncio.sleep(0)
with pytest.raises(asyncio.CancelledError):
- await task
+ _ = await task
assert client.reject_calls == []
assert audit.events == []
@@ -112,7 +112,7 @@ async def test_reschedule_replaces_existing_timer():
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
+ _ = await second
# Only the second timer's firing should produce a fallback call.
assert client.reject_calls == ["action-4"]
assert len(audit.events) == 1
@@ -125,7 +125,7 @@ async def test_fallback_call_failure_still_audits_with_error():
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")
- await task
+ _ = await task
assert client.reject_calls == []
assert len(audit.events) == 1
diff --git a/services/teams-bot/app/callbacks.py b/services/teams-bot/app/callbacks.py
index dd89247e0..dc95d5eeb 100644
--- a/services/teams-bot/app/callbacks.py
+++ b/services/teams-bot/app/callbacks.py
@@ -35,8 +35,13 @@ log = structlog.get_logger(__name__)
class _ActionsClient(Protocol):
- async def approve_action(self, action_id: str) -> dict[str, Any]: ...
- async def reject_action(self, action_id: str) -> dict[str, Any]: ...
+ # Protocol bodies are documentation-only. Using docstrings instead of
+ # ``...`` avoids CodeQL ``py/ineffectual-statement`` warnings on stub bodies.
+ async def approve_action(self, action_id: str) -> dict[str, Any]:
+ """Approve the action identified by ``action_id``."""
+
+ async def reject_action(self, action_id: str) -> dict[str, Any]:
+ """Reject the action identified by ``action_id``."""
@dataclass(slots=True, frozen=True)
@@ -52,7 +57,8 @@ class _AuditEvent:
class _AuditSink(Protocol):
- async def record(self, event: _AuditEvent) -> None: ...
+ async def record(self, event: _AuditEvent) -> None:
+ """Persist an approval-audit event."""
class CallbackResult(dict):
diff --git a/services/teams-bot/app/services/aisoc_clients.py b/services/teams-bot/app/services/aisoc_clients.py
index 16e134bc3..abce21aee 100644
--- a/services/teams-bot/app/services/aisoc_clients.py
+++ b/services/teams-bot/app/services/aisoc_clients.py
@@ -25,13 +25,22 @@ log = structlog.get_logger(__name__)
class _ActionsClient(Protocol):
- async def approve_action(self, action_id: str) -> dict[str, Any]: ...
- async def reject_action(self, action_id: str) -> dict[str, Any]: ...
- async def aclose(self) -> None: ...
+ # Protocol method bodies are documentation-only. We use docstrings (rather
+ # than ``...``) so static analysers don't flag the bodies as ineffectual
+ # statements (CodeQL ``py/ineffectual-statement``).
+ async def approve_action(self, action_id: str) -> dict[str, Any]:
+ """Approve the action identified by ``action_id``."""
+
+ async def reject_action(self, action_id: str) -> dict[str, Any]:
+ """Reject the action identified by ``action_id``."""
+
+ async def aclose(self) -> None:
+ """Release underlying network resources."""
class _AuditSink(Protocol):
- async def record(self, event: Any) -> None: ...
+ async def record(self, event: Any) -> None:
+ """Persist an approval-audit event."""
class _FallbackActionsClient:
diff --git a/services/teams-bot/tests/test_cards.py b/services/teams-bot/tests/test_cards.py
index 53a309548..5f3eb6dd7 100644
--- a/services/teams-bot/tests/test_cards.py
+++ b/services/teams-bot/tests/test_cards.py
@@ -33,7 +33,9 @@ def test_case_context_card_has_required_envelope():
{"id": "case-1", "case_number": "CASE-0001", "title": "EDR detection"},
web_base="https://app.aisoc.test",
)
- assert card["$schema"].startswith("http://adaptivecards.io")
+ # Pinned to the exact canonical schema URL — avoids CodeQL ``py/incomplete-url-substring-sanitization``
+ # by checking the full string rather than a substring prefix.
+ assert card["$schema"] == "http://adaptivecards.io/schemas/adaptive-card.json"
assert card["type"] == "AdaptiveCard"
assert card["version"] == "1.5"
assert isinstance(card["body"], list) and len(card["body"]) >= 2