Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
security(codeql): close py/log-injection, py/url-redirection, and note-level alerts
Beenu Arorab0f48143a57e
diff --git a/apps/web/src/app/(app)/purple-team/page.tsx b/apps/web/src/app/(app)/purple-team/page.tsxindex 8de5045a8..605f17914 100644--- a/apps/web/src/app/(app)/purple-team/page.tsx+++ b/apps/web/src/app/(app)/purple-team/page.tsx@@ -177,14 +177,6 @@ const MOCK_COVERAGE: CoverageMatrix = {summary: { total_techniques: 201, tested_techniques: 14, detected_techniques: 10, overall_coverage: 0.71 },}-const MOCK_EXECUTIONS: Execution[] = [- { id: 'ex-1', source: 'atomic', technique_id: 'T1059.001', test_name: 'PowerShell Download Cradle', status: 'success', started_at: '2026-05-06T10:00:00Z', completed_at: '2026-05-06T10:01:30Z', detected: true, detection_latency_seconds: 45, created_at: '2026-05-06T10:00:00Z' },- { id: 'ex-2', source: 'caldera', technique_id: 'T1003.001', test_name: 'Mimikatz Credential Dump', status: 'success', started_at: '2026-05-06T10:05:00Z', completed_at: '2026-05-06T10:06:00Z', detected: true, detection_latency_seconds: 12, created_at: '2026-05-06T10:05:00Z' },- { id: 'ex-3', source: 'atomic', technique_id: 'T1566.001', test_name: 'Spearphishing Attachment', status: 'failed', started_at: '2026-05-06T10:10:00Z', completed_at: '2026-05-06T10:10:45Z', detected: false, detection_latency_seconds: null, created_at: '2026-05-06T10:10:00Z' },- { id: 'ex-4', source: 'atomic', technique_id: 'T1053.005', test_name: 'Scheduled Task via schtasks', status: 'success', started_at: '2026-05-06T10:15:00Z', completed_at: '2026-05-06T10:16:00Z', detected: null, detection_latency_seconds: null, created_at: '2026-05-06T10:15:00Z' },- { id: 'ex-5', source: 'caldera', technique_id: 'T1021.001', test_name: 'Remote Desktop Protocol', status: 'running', started_at: '2026-05-06T10:20:00Z', completed_at: null, detected: null, detection_latency_seconds: null, created_at: '2026-05-06T10:20:00Z' },-]-// Visual ring around a technique cell that reflects how it changed since the// previous snapshot. Kept subtle so the underlying coverage color still reads.function driftRing(status: DriftStatus | undefined): string {@@ -212,7 +204,7 @@ function driftDeltaLabel(d: number, suffix = ''): string {// --------------------------------------------------------------------------function CoverageHeatmap() {- const { data, error, isLoading } = useSWR<CoverageMatrix>(+ const { data } = useSWR<CoverageMatrix>(`${API}/api/v1/purple-team/coverage?tenant_id=${TENANT_ID}`,fetcher,{ refreshInterval: 30000, fallbackData: MOCK_COVERAGE }diff --git a/apps/web/src/components/alerts/EntityRiskQueue.tsx b/apps/web/src/components/alerts/EntityRiskQueue.tsxindex 4d6216d58..04ad483b0 100644--- a/apps/web/src/components/alerts/EntityRiskQueue.tsx+++ b/apps/web/src/components/alerts/EntityRiskQueue.tsx@@ -483,9 +483,6 @@ export function EntityRiskQueue() {const total = stats?.total ?? entities.length;const alertCount = stats?.alert_count ?? entities.reduce((sum, e) => sum + e.alert_count, 0);- const fusionUnavailable =- queueError instanceof Error && /503|404|fetch/i.test(queueError.message);-return (<div className="space-y-4">{/* Stats strip — anchored on the 2026 KPI bar */}diff --git a/apps/web/src/components/connectors/ConnectorsView.tsx b/apps/web/src/components/connectors/ConnectorsView.tsxindex 1061ea706..6e2a97248 100644--- a/apps/web/src/components/connectors/ConnectorsView.tsx+++ b/apps/web/src/components/connectors/ConnectorsView.tsx@@ -25,7 +25,6 @@ import {type Connector,type ConnectorHealthSummary,} from '@/lib/api';-import { ErrorState } from '@/components/ui/ErrorState';import { AddConnectorModal } from './AddConnectorModal';import { ConnectorInstanceList } from './ConnectorInstanceList';import { InboxTokensPanel } from './InboxTokensPanel';diff --git a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsxindex 772b64a96..4609cf34e 100644--- a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx+++ b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx@@ -208,7 +208,7 @@ function AttackHeatmap({ cells }: { cells: AttackHeatmapCell[] }) {}export function SOCMetricsDashboard() {- const { data, error, isLoading, mutate } = useSWR<SOCMetrics>(+ const { data, mutate } = useSWR<SOCMetrics>("/api/v1/metrics/soc",safeFetcher<SOCMetrics>,{@@ -354,7 +354,7 @@ export function SOCMetricsDashboard() {}function CostTelemetryPanel() {- const { data, error, isLoading } = useSWR<CostAggregate>(+ const { data, isLoading } = useSWR<CostAggregate>("/api/v1/investigations/costs/aggregate?window_days=30",safeFetcher<CostAggregate>,{diff --git a/apps/web/src/components/detections/ContributorLeaderboard.tsx b/apps/web/src/components/detections/ContributorLeaderboard.tsxindex bbabfb954..9c4a02c47 100644--- a/apps/web/src/components/detections/ContributorLeaderboard.tsx+++ b/apps/web/src/components/detections/ContributorLeaderboard.tsx@@ -14,13 +14,6 @@ interface Contributor {badge: 'platinum' | 'gold' | 'silver' | 'bronze';}-function badgeFor(count: number): Contributor['badge'] {- if (count >= 50) return 'platinum';- if (count >= 20) return 'gold';- if (count >= 10) return 'silver';- return 'bronze';-}-const BADGE_STYLES: Record<Contributor['badge'], { bg: string; text: string; border: string; label: string }> = {platinum: { bg: 'bg-violet-500/10', text: 'text-violet-300', border: 'border-violet-500/30', label: 'Platinum' },gold: { bg: 'bg-amber-500/10', text: 'text-amber-300', border: 'border-amber-500/30', label: 'Gold' },diff --git a/services/agents/app/agents/attack_path_agent.py b/services/agents/app/agents/attack_path_agent.pyindex b9f9b218c..a112d7b94 100644--- a/services/agents/app/agents/attack_path_agent.py+++ b/services/agents/app/agents/attack_path_agent.py@@ -31,7 +31,6 @@ _SERVICE_TOKEN = os.getenv("AGENTS_API_TOKEN")# Score thresholds (0.0–1.0) that mirror the buckets in graph_service.py._BLAST_HIGH = 0.7-_BLAST_MED = 0.4# Cap how many entities we run blast-radius on per run to keep tail latency# bounded — the graph traversal is the most expensive part of the workflow.diff --git a/services/agents/tests/test_memory_recall.py b/services/agents/tests/test_memory_recall.pyindex d1103dac5..d7b9e9c08 100644--- a/services/agents/tests/test_memory_recall.py+++ b/services/agents/tests/test_memory_recall.py@@ -29,7 +29,6 @@ Metrics:from __future__ import annotationsimport asyncio-import jsonimport osimport sysfrom pathlib import Path@@ -43,7 +42,7 @@ sys.path.insert(0, str(_AGENTS_ROOT))os.environ.setdefault("DATABASE_URL", "")os.environ.setdefault("REDIS_URL", "")-from app.memory import MemoryManager, MemoryTier # noqa: E402+from app.memory import MemoryManager # noqa: E402from app.memory.models import OverrideFeedback # noqa: E402from app.memory.session import _session_caches # noqa: E402from app.memory.working import _FALLBACK as _WORKING_FALLBACK # noqa: E402diff --git a/services/agents/tests/test_override_accuracy.py b/services/agents/tests/test_override_accuracy.pyindex 7038a45a5..611eff86e 100644--- a/services/agents/tests/test_override_accuracy.py+++ b/services/agents/tests/test_override_accuracy.py@@ -30,7 +30,6 @@ from __future__ import annotationsimport asyncioimport osimport sys-from datetime import datetimefrom pathlib import Pathfrom typing import Anydiff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex bbc38e07f..99d31641b 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -33,6 +33,7 @@ from pydantic import BaseModel, Fieldfrom sqlalchemy import textfrom app.api.v1.deps import AuthUser, DBSession+from app.core.logging import safe_log_valuefrom app.services.case_fanout import (FanoutResult,fanout_create_case,@@ -936,7 +937,13 @@ async def _agents_proxy(method: str, path: str, **kwargs: Any) -> httpx.Responseasync with httpx.AsyncClient(timeout=timeout) as client:return await client.request(method, url, **kwargs)except httpx.HTTPError as exc:- logger.exception("Agents service request failed: %s %s", method, safe_path)+ logger.exception(+ "agents_proxy.request_failed",+ extra={+ "method": safe_log_value(method),+ "path": safe_log_value(safe_path),+ },+ )raise HTTPException(status_code=503,detail=f"Agents service unavailable: {exc}",diff --git a/services/api/app/api/v1/endpoints/connectors.py b/services/api/app/api/v1/endpoints/connectors.pyindex bbab7aa65..0d6b6d69c 100644--- a/services/api/app/api/v1/endpoints/connectors.py+++ b/services/api/app/api/v1/endpoints/connectors.py@@ -787,11 +787,13 @@ async def update_connector_capabilities(await db.refresh(connector)logger.info(- "connector.capabilities.updated tenant_id=%s connector_id=%s connector_type=%s allowed=%s",- current_user.tenant_id,- connector_id,- _safe_log_val(connector.connector_type),- request.allowed_capabilities,+ "connector.capabilities.updated",+ extra={+ "tenant_id": current_user.tenant_id,+ "connector_id": str(connector_id),+ "connector_type": _safe_log_val(connector.connector_type),+ "allowed": request.allowed_capabilities,+ },)return _build_connector_response(connector)@@ -1106,10 +1108,12 @@ async def troubleshoot_connection()safe_type = _safe_connector_type(request.connector_type)logger.info(- "connectors.troubleshoot type=%s keys=%s err_len=%d",- _safe_log_val(safe_type),- sorted(request.auth_config_keys)[:8], # cap to avoid log spam- len(request.error),+ "connectors.troubleshoot",+ extra={+ "type": _safe_log_val(safe_type),+ "keys": sorted(request.auth_config_keys)[:8], # cap to avoid log spam+ "err_len": len(request.error),+ },)return _troubleshoot(request.error, safe_type)diff --git a/services/api/app/api/v1/endpoints/fusion.py b/services/api/app/api/v1/endpoints/fusion.pyindex 73f7a8110..c6780c6fd 100644--- a/services/api/app/api/v1/endpoints/fusion.py+++ b/services/api/app/api/v1/endpoints/fusion.py@@ -34,6 +34,8 @@ from uuid import UUIDimport httpxfrom fastapi import APIRouter, HTTPException, Query+from app.core.logging import safe_log_value+logger = logging.getLogger(__name__)router = APIRouter(prefix="/fusion", tags=["fusion"])@@ -77,9 +79,11 @@ async def _proxy_get(path: str, params: dict[str, Any] | None = None) -> dict[stresp = await client.get(f"{_FUSION_URL}{safe_path}", params=params or {})if resp.status_code >= 500:logger.warning(- "Fusion upstream returned %s for %s; falling back to stub",- resp.status_code,- safe_path,+ "fusion.upstream_error",+ extra={+ "status_code": resp.status_code,+ "path": safe_log_value(safe_path),+ },)return Noneif resp.status_code == 404:@@ -91,7 +95,10 @@ async def _proxy_get(path: str, params: dict[str, Any] | None = None) -> dict[stexcept HTTPException:raiseexcept httpx.HTTPError as exc:- logger.warning("Fusion service unreachable (%s); using stub fallback", exc)+ logger.warning(+ "fusion.unreachable",+ extra={"err": safe_log_value(str(exc))},+ )return Nonediff --git a/services/api/app/api/v1/endpoints/inbox.py b/services/api/app/api/v1/endpoints/inbox.pyindex 65d6641d7..c3bb19b66 100644--- a/services/api/app/api/v1/endpoints/inbox.py+++ b/services/api/app/api/v1/endpoints/inbox.py@@ -29,7 +29,6 @@ from __future__ import annotationsimport loggingimport reimport secrets-import uuidfrom datetime import UTC, datetimefrom typing import Annotated@@ -39,6 +38,7 @@ from sqlalchemy import select, updatefrom app.api.v1.deps import AuthUser, require_permissionfrom app.core.config import settings+from app.core.logging import safe_log_valuefrom app.db.rls import TenantDBSessionfrom app.models.inbox import TenantInboxToken@@ -408,10 +408,10 @@ async def mint_token(await db.refresh(row)logger.info(- "tenant_inbox_token minted",+ "tenant_inbox_token.minted",extra={"tenant_id": str(current_user.tenant_id),- "template_id": body.template_id,+ "template_id": safe_log_value(body.template_id),"token_fingerprint": _fingerprint(token),"has_hmac": body.hmac_secret is not None,},diff --git a/services/api/app/api/v1/endpoints/inbox_itsm.py b/services/api/app/api/v1/endpoints/inbox_itsm.pyindex 1ca853d84..9699e9d91 100644--- a/services/api/app/api/v1/endpoints/inbox_itsm.py+++ b/services/api/app/api/v1/endpoints/inbox_itsm.py@@ -87,6 +87,7 @@ from pydantic import BaseModelfrom sqlalchemy import textfrom app.api.v1.deps import DBSession+from app.core.logging import safe_log_valuelogger = logging.getLogger(__name__)@@ -383,7 +384,9 @@ async def _fetch_token_and_connector(# carries the fingerprint for ops debugging.logger.info("inbox_itsm.token_not_found",- extra={"token_fingerprint": f"...{tenant_token[-8:]}"},+ extra={+ "token_fingerprint": safe_log_value(f"...{tenant_token[-8:]}")+ },)raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,@@ -426,9 +429,9 @@ async def _fetch_token_and_connector(logger.warning("inbox_itsm.cross_tenant_attempt",extra={- "token_tenant_id": str(token_row.tenant_id),- "connector_tenant_id": str(connector_row.tenant_id),- "connector_id": str(connector_instance_id),+ "token_tenant_id": safe_log_value(token_row.tenant_id),+ "connector_tenant_id": safe_log_value(connector_row.tenant_id),+ "connector_id": safe_log_value(connector_instance_id),},)raise HTTPException(@@ -649,9 +652,9 @@ async def inbound_itsm_webhook(logger.info("inbox_itsm.payload_missing_external_id",extra={- "vendor": vendor,- "connector_id": str(connector_instance_id),- "tenant_id": str(token_row.tenant_id),+ "vendor": safe_log_value(vendor),+ "connector_id": safe_log_value(connector_instance_id),+ "tenant_id": safe_log_value(token_row.tenant_id),},)return InboundResult(@@ -693,10 +696,10 @@ async def inbound_itsm_webhook(logger.info("inbox_itsm.unlinked_external_id",extra={- "vendor": vendor,- "external_id": external_id,- "connector_id": str(connector_instance_id),- "tenant_id": str(token_row.tenant_id),+ "vendor": safe_log_value(vendor),+ "external_id": safe_log_value(external_id),+ "connector_id": safe_log_value(connector_instance_id),+ "tenant_id": safe_log_value(token_row.tenant_id),},)return InboundResult(@@ -794,9 +797,9 @@ async def inbound_itsm_webhook(logger.exception("inbox_itsm.apply_failed",extra={- "vendor": vendor,- "external_id": external_id,- "case_id": str(ref_row.aisoc_case_id),+ "vendor": safe_log_value(vendor),+ "external_id": safe_log_value(external_id),+ "case_id": safe_log_value(ref_row.aisoc_case_id),},)raise HTTPException(@@ -807,11 +810,11 @@ async def inbound_itsm_webhook(logger.info("inbox_itsm.status_applied",extra={- "vendor": vendor,- "external_id": external_id,- "case_id": str(ref_row.aisoc_case_id),- "old_status": ref_row.status,- "new_status": new_status,+ "vendor": safe_log_value(vendor),+ "external_id": safe_log_value(external_id),+ "case_id": safe_log_value(ref_row.aisoc_case_id),+ "old_status": safe_log_value(ref_row.status),+ "new_status": safe_log_value(new_status),},)return InboundResult(diff --git a/services/api/app/api/v1/endpoints/lake.py b/services/api/app/api/v1/endpoints/lake.pyindex 9bdff6cac..33de6b876 100644--- a/services/api/app/api/v1/endpoints/lake.py+++ b/services/api/app/api/v1/endpoints/lake.py@@ -40,6 +40,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, Response, statusfrom pydantic import BaseModel, Fieldfrom app.api.v1.deps import AuthUser, DBSession, require_permission+from app.core.logging import safe_log_valuefrom app.db.clickhouse import (LakeQueryError,LakeQueryNotConfiguredError,@@ -274,11 +275,13 @@ async def execute_lake_sql(# non-allowlisted table, table function). 403 conveys that# this is an authorisation outcome, not a typo.logger.info(- "lake.sql.forbidden tenant_id=%s user=%s reason=%s sql=%r",- current_user.tenant_id,- current_user.email,- exc,- _scrub_sql_for_log(body.sql),+ "lake.sql.forbidden",+ extra={+ "tenant_id": current_user.tenant_id,+ "user": safe_log_value(current_user.email),+ "reason": safe_log_value(str(exc)),+ "sql": safe_log_value(_scrub_sql_for_log(body.sql)),+ },)# Best-effort audit: failed access attempt is worth a row.await _audit_query_attempt(@@ -296,10 +299,12 @@ async def execute_lake_sql() from excexcept LakeSqlSyntaxError as exc:logger.info(- "lake.sql.syntax_error tenant_id=%s user=%s reason=%s",- current_user.tenant_id,- current_user.email,- exc,+ "lake.sql.syntax_error",+ extra={+ "tenant_id": current_user.tenant_id,+ "user": safe_log_value(current_user.email),+ "reason": safe_log_value(str(exc)),+ },)raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,diff --git a/services/api/app/api/v1/endpoints/oauth.py b/services/api/app/api/v1/endpoints/oauth.pyindex 424fd3eaa..4c7f1d2ca 100644--- a/services/api/app/api/v1/endpoints/oauth.py+++ b/services/api/app/api/v1/endpoints/oauth.py@@ -65,7 +65,7 @@ import secretsimport uuidfrom datetime import UTC, datetime, timedeltafrom typing import Annotated, Any-from urllib.parse import urlencode+from urllib.parse import urlencode, urlparseimport httpxfrom fastapi import APIRouter, Depends, HTTPException, Query, status@@ -76,6 +76,7 @@ from sqlalchemy import delete, selectfrom app.api.v1.deps import AuthUser, DBSession, require_permissionfrom app.api.v1.endpoints.connectors import _validate_connector_typefrom app.core.config import settings+from app.core.logging import safe_log_valuefrom app.models.connector import Connectorfrom app.models.oauth import OAuthAppCredential, OAuthStatefrom app.security.credential_vault import CredentialVaultError, get_vault@@ -109,6 +110,96 @@ _PKCE_REQUIRED: set[str] = {"atlassian",}+# Allow-list of OAuth provider hostnames we will redirect operators to.+#+# CodeQL (py/url-redirection) correctly flags ``RedirectResponse(url=...)``+# when the URL traces back to a database column the tenant can edit+# (``OAuthAppCredential.authorize_url`` / ``token_url``). We close that+# attack surface by *intersecting* the resolved authorize/token URL with+# this allow-list of well-known hostname suffixes — even if a hostile+# tenant admin pastes ``https://attacker.com`` into the OAuth app row,+# we refuse to bounce the operator there. The list is keyed off the+# real authorize/token endpoints documented by each provider whose+# connector ships ``OAuthHints`` (see services/connectors/app/connectors/).+_OAUTH_PROVIDER_HOST_SUFFIXES: tuple[str, ...] = (+ # Atlassian Cloud (Jira / Confluence) 3LO+ "auth.atlassian.com",+ # Auth0 (per-tenant subdomain, e.g. ``acme.auth0.com``)+ ".auth0.com",+ # Microsoft Entra ID / Azure AD / M365 / Defender / Activity / Graph+ "login.microsoftonline.com",+ "login.microsoft.com",+ # Cloudflare dashboard SSO+ "dash.cloudflare.com",+ # GCP / Google Workspace / Gmail / SCC / Cloud Audit+ "accounts.google.com",+ "oauth2.googleapis.com",+ # GitHub+ "github.com",+ # Okta (per-tenant subdomain, e.g. ``acme.okta.com``) and preview tier+ ".okta.com",+ ".oktapreview.com",+ # Salesforce login surface (production + sandbox)+ "login.salesforce.com",+ "test.salesforce.com",+ ".my.salesforce.com",+ # Slack+ "slack.com",+ # Tailscale+ "login.tailscale.com",+)+++def _is_allowed_oauth_host(host: str) -> bool:+ """Return ``True`` when ``host`` matches an allow-listed OAuth provider.++ Suffix matches starting with ``.`` (e.g. ``.okta.com``) accept any+ single-or-multi-label subdomain. Exact entries (e.g.+ ``login.microsoftonline.com``) match the host verbatim. We compare+ case-insensitively because hostnames are case-insensitive per RFC 3986.+ """+ if not host:+ return False+ host_lc = host.lower()+ for suffix in _OAUTH_PROVIDER_HOST_SUFFIXES:+ suffix_lc = suffix.lower()+ if suffix_lc.startswith("."):+ if host_lc.endswith(suffix_lc) and len(host_lc) > len(suffix_lc):+ return True+ elif host_lc == suffix_lc:+ return True+ return False+++def _validated_provider_url(url: str, *, kind: str) -> str:+ """Return ``url`` unchanged after enforcing the OAuth host allow-list.++ Raises ``HTTPException(400)`` for any of:+ * non-HTTPS scheme — providers reject http:// authorize URLs anyway,+ and refusing them here closes a downgrade vector;+ * embedded credentials (``user:pass@host``) — these can hide a+ hostile origin behind a benign-looking prefix;+ * a host that does not match :data:`_OAUTH_PROVIDER_HOST_SUFFIXES`.++ ``kind`` is interpolated into the error detail so the operator knows+ whether to fix the authorize_url or the token_url field.+ """+ parsed = urlparse(url)+ scheme_ok = parsed.scheme == "https"+ host = parsed.hostname or ""+ no_userinfo = not parsed.username and not parsed.password+ if not (scheme_ok and host and no_userinfo and _is_allowed_oauth_host(host)):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=(+ f"Refusing to use OAuth {kind} URL: host is not on the "+ "allow-list of trusted OAuth providers. Update the OAuth "+ "app row to point at the documented provider endpoint."+ ),+ )+ return url++# Some providers expect extra non-standard query params on the authorize# URL. We thread these through ``OAuthHints``-derived defaults plus# per-provider overrides keyed by connector_type.@@ -130,8 +221,16 @@ _AUTHORIZE_EXTRA_PARAMS: dict[str, dict[str, str]] = {# --------------------------------------------------------------- helpers-def _safe_log_val(value: str) -> str:- return _LOG_CTRL_RE.sub("", value)+def _safe_log_val(value: object) -> str:+ """Local alias for the canonical :func:`safe_log_value` helper.++ Kept as a thin wrapper so existing call sites stay untouched while the+ underlying implementation defends against CWE-117 (log injection) by+ escaping CR/LF/NUL/ESC and truncating overly long user-controlled+ values. Routes through :func:`app.core.logging.safe_log_value` so+ every service uses the same sanitisation contract.+ """+ return safe_log_value(value)def _safe_connector_type(value: str) -> str:@@ -208,9 +307,11 @@ def _validate_return_to(return_to: str | None) -> str:if base and return_to == base:return return_tologger.info(- "oauth.return_to.rejected raw=%s falling_back_to=%s",- _safe_log_val(return_to)[:200],- default,+ "oauth.return_to.rejected",+ extra={+ "raw": _safe_log_val(return_to),+ "falling_back_to": default,+ },)return default@@ -256,7 +357,14 @@ def _resolve_authorize_url(app_credential: OAuthAppCredential,hints: dict[str, Any],) -> str:- """Per-tenant override beats schema hint beats hard error."""+ """Per-tenant override beats schema hint beats hard error.++ The returned URL is also passed through :func:`_validated_provider_url`+ which enforces the OAuth host allow-list. This closes the open-redirect+ surface flagged by CodeQL ``py/url-redirection`` at the redirect call+ site: even if a tenant admin pastes a hostile authorize URL into the+ OAuth app row, we refuse to bounce the operator there.+ """url = (app_credential.authorize_url or hints.get("authorize_url") or "").strip()if not url:raise HTTPException(@@ -267,13 +375,20 @@ def _resolve_authorize_url("supply authorize_url."),)- return url+ return _validated_provider_url(url, kind="authorize")def _resolve_token_url(app_credential: OAuthAppCredential,hints: dict[str, Any],) -> str:+ """Resolve the OAuth ``token_url`` with the same allow-list guard.++ See :func:`_resolve_authorize_url` for the allow-list rationale. The+ token endpoint is server-to-server (not a redirect), but applying the+ same check defends against a hostile tenant admin redirecting our+ backchannel ``client_secret`` POST to an attacker-controlled host.+ """url = (app_credential.token_url or hints.get("token_url") or "").strip()if not url:raise HTTPException(@@ -283,7 +398,7 @@ def _resolve_token_url("tenant did not override it."),)- return url+ return _validated_provider_url(url, kind="token")def _resolve_scopes(@@ -421,10 +536,12 @@ async def upsert_oauth_app(await db.refresh(row)logger.info(- "oauth.app.upsert tenant=%s connector_type=%s created=%s",- current_user.tenant_id,- _safe_log_val(safe_type),- existing is None,+ "oauth.app.upsert",+ extra={+ "tenant": current_user.tenant_id,+ "connector_type": _safe_log_val(safe_type),+ "created": existing is None,+ },)return OAuthAppView(connector_type=row.connector_type,@@ -454,9 +571,11 @@ async def delete_oauth_app()await db.commit()logger.info(- "oauth.app.delete tenant=%s connector_type=%s",- current_user.tenant_id,- _safe_log_val(safe_type),+ "oauth.app.delete",+ extra={+ "tenant": current_user.tenant_id,+ "connector_type": _safe_log_val(safe_type),+ },)@@ -570,12 +689,30 @@ async def oauth_start(sep = "&" if "?" in authorize_url else "?"full_authorize = f"{authorize_url}{sep}{urlencode(qs, safe=':+/?#@!$&()*+,;=')}"+ # Defence in depth: the authorize_url base was already validated by+ # ``_resolve_authorize_url`` -> ``_validated_provider_url``, but we+ # re-parse the *fully composed* redirect target here so the host+ # check is locally visible at the ``RedirectResponse`` call site.+ # This also gives CodeQL (py/url-redirection) a sanitizer it can see+ # without needing inter-procedural taint tracking through helpers.+ parsed_full = urlparse(full_authorize)+ if not _is_allowed_oauth_host(parsed_full.hostname or ""):+ # Should be unreachable because _resolve_authorize_url already+ # rejected non-allowlisted hosts, but we treat any drift as a+ # 500 rather than silently redirecting somewhere unexpected.+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail="Internal error: composed OAuth authorize URL failed host allow-list re-check.",+ )+logger.info(- "oauth.start tenant=%s connector_type=%s reauth=%s pkce=%s",- current_user.tenant_id,- _safe_log_val(safe_type),- connector_id is not None,- needs_pkce,+ "oauth.start",+ extra={+ "tenant": current_user.tenant_id,+ "connector_type": _safe_log_val(safe_type),+ "reauth": connector_id is not None,+ "pkce": needs_pkce,+ },)if response_mode == "json":@@ -645,10 +782,12 @@ async def oauth_callback(await db.execute(delete(OAuthState).where(OAuthState.state == state))await db.commit()logger.warning(- "oauth.callback.provider_error tenant=%s connector_type=%s err=%s",- state_row.tenant_id,- _safe_log_val(state_row.connector_type),- _safe_log_val(error),+ "oauth.callback.provider_error",+ extra={+ "tenant": state_row.tenant_id,+ "connector_type": _safe_log_val(state_row.connector_type),+ "err": _safe_log_val(error),+ },)return _callback_error_redirect(return_to,diff --git a/services/api/app/api/v1/endpoints/shifts.py b/services/api/app/api/v1/endpoints/shifts.pyindex e85ce0c55..07f1c44c3 100644--- a/services/api/app/api/v1/endpoints/shifts.py+++ b/services/api/app/api/v1/endpoints/shifts.py@@ -4,12 +4,11 @@ from __future__ import annotationsimport uuidfrom datetime import UTC, datetime, timedelta-from typing import Annotated-from fastapi import APIRouter, Depends, HTTPException, Query+from fastapi import APIRouter, HTTPException, Queryfrom pydantic import BaseModel, Field-from app.api.v1.deps import AuthUser, require_permission+from app.api.v1.deps import AuthUserrouter = APIRouter(prefix="/shifts", tags=["shifts"])diff --git a/services/api/app/core/logging.py b/services/api/app/core/logging.pyindex fb290a380..79fe11d9c 100644--- a/services/api/app/core/logging.py+++ b/services/api/app/core/logging.py@@ -40,3 +40,36 @@ def configure_logging() -> None:def get_logger(name: str = __name__) -> structlog.BoundLogger:return structlog.get_logger(name)+++# Maximum length for a single user-derived value embedded in a log line.+# Keeps logs readable and bounds memory if a caller passes pathological input.+_MAX_LOG_VALUE_LEN = 256++# Characters that can be used to forge log entries, break log parsers, or+# inject ANSI escape sequences when logs are rendered to a terminal.+_LOG_INJECTION_TRANSLATE = str.maketrans(+ {+ "\r": "\\r",+ "\n": "\\n",+ "\t": "\\t",+ "\x00": "\\x00",+ "\x1b": "\\x1b",+ }+)+++def safe_log_value(value: object, max_len: int = _MAX_LOG_VALUE_LEN) -> str:+ """Sanitize an arbitrary value before embedding it in a log message.++ Defends against log-injection (CWE-117) by escaping characters that can+ forge new log entries (CR/LF/NUL/ESC) and by truncating overly long+ user-controlled strings. Use whenever a log statement interpolates a value+ that originated from an HTTP request, header, query string, or JSON body.+ """+ if value is None:+ return "<none>"+ text = str(value).translate(_LOG_INJECTION_TRANSLATE)+ if len(text) > max_len:+ text = text[:max_len] + "...<truncated>"+ return textdiff --git a/services/api/app/models/easm.py b/services/api/app/models/easm.pyindex 1b161318b..9d493c700 100644--- a/services/api/app/models/easm.py+++ b/services/api/app/models/easm.py@@ -3,19 +3,16 @@ External Attack Surface Management (EASM) models (Tier 3.6)."""from datetime import datetimefrom enum import Enum-from typing import Optionalfrom uuid import UUID, uuid4from sqlalchemy import (- Column,DateTime,Enum as SQLAEnum,ForeignKey,Index,String,- Text,)-from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID as PGUUID+from sqlalchemy.dialects.postgresql import JSONB, UUID as PGUUIDfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom . import Basediff --git a/services/api/app/services/easm_discovery.py b/services/api/app/services/easm_discovery.pyindex 6ebffdfb7..9243ffb1f 100644--- a/services/api/app/services/easm_discovery.py+++ b/services/api/app/services/easm_discovery.py@@ -16,7 +16,6 @@ import asyncioimport loggingimport socketfrom dataclasses import dataclass, field-from datetime import datetime, timezonefrom typing import Any, Sequenceimport httpxdiff --git a/services/api/app/services/easm_drift.py b/services/api/app/services/easm_drift.pyindex 3656cecdb..4a779ae6d 100644--- a/services/api/app/services/easm_drift.py+++ b/services/api/app/services/easm_drift.py@@ -20,7 +20,7 @@ from uuid import UUIDfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from app.models.easm import ExternalAsset, ExternalAssetDrift, ExternalAssetType+from app.models.easm import ExternalAsset, ExternalAssetDriftfrom app.services.easm_discovery import DiscoveredAssetlogger = logging.getLogger("aisoc.easm.drift")diff --git a/services/api/tests/test_easm.py b/services/api/tests/test_easm.pyindex 610ac1a17..a2854fa3b 100644--- a/services/api/tests/test_easm.py+++ b/services/api/tests/test_easm.py@@ -11,7 +11,6 @@ All tests run with mocked HTTP and socket calls — no live APIs required.from __future__ import annotations-import asyncioimport uuidfrom datetime import datetime, timezonefrom typing import Any@@ -19,7 +18,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from app.models.easm import ExternalAsset, ExternalAssetDrift, ExternalAssetType+from app.models.easm import ExternalAsset, ExternalAssetTypefrom app.services.easm_discovery import (DiscoveredAsset,_shodan_search,diff --git a/services/api/tests/test_mssp_rule_resolver.py b/services/api/tests/test_mssp_rule_resolver.pyindex 581916349..6ce508a98 100644--- a/services/api/tests/test_mssp_rule_resolver.py+++ b/services/api/tests/test_mssp_rule_resolver.py@@ -11,8 +11,6 @@ These tests run against an in-process SQLite/mock AsyncSessionfrom __future__ import annotationsimport uuid-from dataclasses import dataclass, field-from typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -20,7 +18,6 @@ import pytestfrom app.services.mssp_rule_resolver import (ResolvedRule,resolve_effective_rules,- count_effective_rules,)diff --git a/services/api/tests/test_oauth_refresh_worker.py b/services/api/tests/test_oauth_refresh_worker.pyindex f6d6d07dd..f1fd4e78c 100644--- a/services/api/tests/test_oauth_refresh_worker.py+++ b/services/api/tests/test_oauth_refresh_worker.py@@ -19,7 +19,7 @@ Coverage map:from __future__ import annotationsimport uuid-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetimefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patchdiff --git a/services/connectors/app/connectors/chronicle.py b/services/connectors/app/connectors/chronicle.pyindex 4898e2578..4f86a02d8 100644--- a/services/connectors/app/connectors/chronicle.py+++ b/services/connectors/app/connectors/chronicle.py@@ -11,7 +11,6 @@ Chronicle SDK / google-auth at runtime.from __future__ import annotations-from datetime import UTC, datetime, timedeltafrom typing import Anyimport structlogdiff --git a/services/connectors/app/connectors/jira_connector.py b/services/connectors/app/connectors/jira_connector.pyindex 48d01f1bd..6fd6e3343 100644--- a/services/connectors/app/connectors/jira_connector.py+++ b/services/connectors/app/connectors/jira_connector.py@@ -7,7 +7,6 @@ under Workstream 8, projects AiSOC cases / status changes back into Jira.from __future__ import annotationsfrom base64 import b64encode-from datetime import UTC, datetime, timedeltafrom typing import Anyimport httpxdiff --git a/services/connectors/app/connectors/onepassword.py b/services/connectors/app/connectors/onepassword.pyindex d155445a1..b15f6c1d8 100644--- a/services/connectors/app/connectors/onepassword.py+++ b/services/connectors/app/connectors/onepassword.py@@ -118,7 +118,6 @@ class OnePasswordConnector(BaseConnector):elif category == "firewall_failed":severity = "high"- session = raw.get("session", {}) or {}client_info = raw.get("client", {}) or {}return {diff --git a/services/connectors/app/connectors/tenable.py b/services/connectors/app/connectors/tenable.pyindex 4a5622cae..524d881e1 100644--- a/services/connectors/app/connectors/tenable.py+++ b/services/connectors/app/connectors/tenable.py@@ -8,7 +8,6 @@ vulnerabilities so the agent can treat them uniformly.from __future__ import annotations-from datetime import UTC, datetime, timedeltafrom typing import Anyimport httpx@@ -85,7 +84,6 @@ class TenableConnector(BaseConnector):async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:# Use the workbenches export filtered by last_found within the window.- since = datetime.now(UTC) - timedelta(seconds=since_seconds)try:async with httpx.AsyncClient(timeout=30.0) as client:resp = await client.get(diff --git a/services/connectors/app/connectors/zscaler.py b/services/connectors/app/connectors/zscaler.pyindex 3899aa66d..82804f92f 100644--- a/services/connectors/app/connectors/zscaler.py+++ b/services/connectors/app/connectors/zscaler.py@@ -5,9 +5,8 @@ Fetches web security logs from Zscaler Internet Access (ZIA).from __future__ import annotations-import hashlibimport time-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetimefrom typing import Anyimport httpxdiff --git a/services/fusion/app/services/vuln_boost.py b/services/fusion/app/services/vuln_boost.pyindex 178382485..92b6bd2cd 100644--- a/services/fusion/app/services/vuln_boost.py+++ b/services/fusion/app/services/vuln_boost.py@@ -6,7 +6,6 @@ service. If any entry has `is_exploited: true`, we set `exploit_in_wild=True`on the FusedAlert and append a positive ConfidenceFactor."""-from typing import Anyimport structlog