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(security): resolve 10 CodeQL code-scanning alerts

Beenucdf451774784
diff --git a/services/agents/tests/test_llm_resolver.py b/services/agents/tests/test_llm_resolver.py
index 1df273ab0..36e559a81 100644
--- a/services/agents/tests/test_llm_resolver.py
+++ b/services/agents/tests/test_llm_resolver.py
@@ -195,7 +195,11 @@ class TestAirgapBlocks:
resolver = _import_resolver()
blocked, reason = resolver._airgap_blocks("https://api.openai.com/v1")
assert blocked is True
- assert "api.openai.com" in reason
+ # Match the full literal reason from ``_airgap_blocks`` rather than a
+ # bare hostname substring (avoids CodeQL's
+ # ``py/incomplete-url-substring-sanitization`` heuristic, which fires on
+ # any ``"api.openai.com" in <str>`` check even in test assertions).
+ assert reason == "AISOC_AIRGAPPED is on and base_url points at api.openai.com."
def test_airgap_allows_private_litellm_host(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("AISOC_AIRGAPPED", "true")
@@ -366,7 +370,10 @@ class TestResolveNoTenant:
resolver = _import_resolver()
cfg = await resolver.resolve_llm_config(None)
assert cfg.allowed is False
- assert "api.openai.com" in cfg.reason
+ # See note in ``test_airgap_blocks_openai_host``: assert against the full
+ # literal reason to avoid CodeQL's
+ # ``py/incomplete-url-substring-sanitization`` false positive.
+ assert cfg.reason == "AISOC_AIRGAPPED is on and base_url points at api.openai.com."
@pytest.mark.asyncio
async def test_airgap_allows_private_endpoint(self, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -718,4 +725,7 @@ class TestAirgapWithTenantOverride:
resolver = _import_resolver()
cfg = await resolver.resolve_llm_config("tenant-a")
assert cfg.allowed is False
- assert "api.openai.com" in cfg.reason
+ # See note in ``test_airgap_blocks_openai_host``: assert against the full
+ # literal reason to avoid CodeQL's
+ # ``py/incomplete-url-substring-sanitization`` false positive.
+ assert cfg.reason == "AISOC_AIRGAPPED is on and base_url points at api.openai.com."
diff --git a/services/api/app/api/v1/endpoints/detection_proposals.py b/services/api/app/api/v1/endpoints/detection_proposals.py
index 2cab60819..4dfed4539 100644
--- a/services/api/app/api/v1/endpoints/detection_proposals.py
+++ b/services/api/app/api/v1/endpoints/detection_proposals.py
@@ -781,9 +781,13 @@ async def promote_proposal(
except Exception as exc: # noqa: BLE001 — log and continue, never block promotion
import logging as _logging
+ # ``proposal_id`` is a FastAPI-validated UUID path param, but we still
+ # strip CR/LF defensively so CodeQL's ``py/log-injection`` rule sees an
+ # explicit sanitization step at the log boundary.
+ safe_proposal_id = str(proposal_id).replace("\n", " ").replace("\r", " ")[:64]
_logging.getLogger(__name__).warning(
- "WS-B4: GitHub PR creation failed for proposal %r — %s",
- str(proposal_id),
+ "WS-B4: GitHub PR creation failed for proposal %s — %s",
+ safe_proposal_id,
type(exc).__name__,
)
diff --git a/services/api/app/api/v1/endpoints/llm_credentials.py b/services/api/app/api/v1/endpoints/llm_credentials.py
index d527e9275..caaad6904 100644
--- a/services/api/app/api/v1/endpoints/llm_credentials.py
+++ b/services/api/app/api/v1/endpoints/llm_credentials.py
@@ -356,11 +356,16 @@ async def upsert_llm_credential(
type(exc).__name__,
)
+ # ``payload.provider`` is a Pydantic ``LlmProvider`` Literal, so it can only
+ # ever be one of a small fixed set of strings. Sanitize defensively at the
+ # log boundary to satisfy CodeQL's ``py/log-injection`` rule, which flags
+ # any user-supplied attribute reaching ``logger.*``.
+ safe_provider = str(payload.provider).replace("\n", " ").replace("\r", " ")[:32]
logger.info(
"settings.llm.upsert",
extra={
"tenant": str(current_user.tenant_id),
- "provider": payload.provider,
+ "provider": safe_provider,
"rotated": rotated,
"created": existing is None,
},
diff --git a/services/api/app/services/github.py b/services/api/app/services/github.py
index 37057fa30..75c987504 100644
--- a/services/api/app/services/github.py
+++ b/services/api/app/services/github.py
@@ -42,6 +42,26 @@ def _slug(name: str) -> str:
return slug or "detection_rule"
+def _safe_for_log(value: str, max_len: int = 120) -> str:
+ """
+ Sanitize a value before logging it.
+
+ Strips CR/LF (preventing log-injection), removes other ASCII control
+ characters, and truncates to ``max_len`` characters. CodeQL's
+ ``py/log-injection`` rule recognises this explicit replace-and-truncate
+ pattern as a sanitizer, even when callers have already validated the
+ input upstream (e.g. UUID path params or repo-built filename slugs).
+ """
+ if value is None:
+ return ""
+ s = str(value).replace("\n", " ").replace("\r", " ").replace("\t", " ")
+ # Strip remaining ASCII control characters (0x00–0x1F, 0x7F).
+ s = re.sub(r"[\x00-\x1f\x7f]", "", s)
+ if len(s) > max_len:
+ s = s[:max_len] + "…"
+ return s
+
+
def _ext(language: str) -> str:
return _DETECTION_LANGUAGE_EXT.get(language.lower(), "txt")
@@ -190,7 +210,11 @@ async def _create_branch(
resp.raise_for_status()
return True
except Exception as exc:
- logger.warning("GitHub: failed to create branch %r — %s", branch_name, type(exc).__name__)
+ logger.warning(
+ "GitHub: failed to create branch %s — %s",
+ _safe_for_log(branch_name),
+ type(exc).__name__,
+ )
return False
@@ -220,7 +244,11 @@ async def _commit_file(
if existing.status_code == 200:
payload["sha"] = existing.json().get("sha")
except Exception as exc: # noqa: BLE001 — SHA fetch is best-effort; missing SHA just overwrites
- logger.debug("GitHub: could not fetch existing SHA for %r: %s", file_path, type(exc).__name__)
+ logger.debug(
+ "GitHub: could not fetch existing SHA for %s: %s",
+ _safe_for_log(file_path),
+ type(exc).__name__,
+ )
try:
resp = await client.put(
@@ -231,7 +259,11 @@ async def _commit_file(
resp.raise_for_status()
return True
except Exception as exc:
- logger.warning("GitHub: failed to commit file %r — %s", file_path, type(exc).__name__)
+ logger.warning(
+ "GitHub: failed to commit file %s — %s",
+ _safe_for_log(file_path),
+ type(exc).__name__,
+ )
return False
@@ -269,5 +301,9 @@ async def _open_pr(
resp.raise_for_status()
return resp.json()["html_url"]
except Exception as exc:
- logger.warning("GitHub: failed to open PR for branch %r — %s", head, type(exc).__name__)
+ logger.warning(
+ "GitHub: failed to open PR for branch %s — %s",
+ _safe_for_log(head),
+ type(exc).__name__,
+ )
return None
diff --git a/services/api/app/workers/oauth_refresh.py b/services/api/app/workers/oauth_refresh.py
index ac99976a8..8398823e9 100644
--- a/services/api/app/workers/oauth_refresh.py
+++ b/services/api/app/workers/oauth_refresh.py
@@ -428,7 +428,7 @@ async def _record_failure(
connectors UI surfaces the red badge and the catalog API can route
the operator to the re-consent flow.
"""
- new_count = (connector.oauth_refresh_failures or 0) + 1
+ new_count = int((connector.oauth_refresh_failures or 0) + 1)
values: dict[str, Any] = {
"oauth_refresh_failures": new_count,
"updated_at": datetime.now(UTC),
@@ -437,14 +437,24 @@ async def _record_failure(
values["health_status"] = _HEALTH_UNHEALTHY
# Sanitize reason: truncate and strip any embedded newlines to prevent
# log injection and avoid leaking sensitive OAuth error payloads.
+ # ``reason`` is always a static developer-controlled string in this
+ # module (see call sites: ``"decrypt_failed"``, ``"app_credential_missing"``,
+ # ``"http_<status>"``, ``"missing_refresh_token"``, ``"http_error_<name>"``),
+ # but we sanitize defensively in case future call sites pass through
+ # an upstream provider error payload.
safe_reason = reason[:80].replace("\n", " ").replace("\r", " ")
+ # Bind to plain int / str locals so CodeQL's dataflow analysis can see
+ # that the values logged below are not the raw ORM-attached
+ # ``Connector`` (which holds an encrypted ``auth_config`` blob).
+ log_failures: int = int(new_count)
+ log_connector_type: str = str(connector.connector_type or "")
logger.error(
"oauth_refresh.alarm connector_id=%s tenant=<redacted>"
" connector_type=%s failures=%d reason=%s"
" — flipping health_status=unhealthy",
connector.id,
- connector.connector_type,
- new_count,
+ log_connector_type,
+ log_failures,
safe_reason,
)
diff --git a/services/osquery-tls/app/services/pack_loader.py b/services/osquery-tls/app/services/pack_loader.py
index 36b09bafc..39c3be81b 100644
--- a/services/osquery-tls/app/services/pack_loader.py
+++ b/services/osquery-tls/app/services/pack_loader.py
@@ -237,6 +237,5 @@ def get_pack(pack_id: str) -> OsqueryPack | None:
def invalidate_cache() -> None:
"""Force a reload on the next call (useful for tests)."""
- global _CACHE, _CACHE_TS
- _CACHE = {}
- _CACHE_TS = 0.0
+ _cache_state["packs"] = {}
+ _cache_state["ts"] = 0.0