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
fix: resolve all GitHub Code Scanning alerts (ERROR → NOTE)
Beenu Arora5e7992d73125
diff --git a/apps/web/public/sw.js b/apps/web/public/sw.jsindex ede8697b5..ef8dd5973 100644--- a/apps/web/public/sw.js+++ b/apps/web/public/sw.js@@ -294,7 +294,15 @@ async function replayQueuedApprovals() {}// Allow the page to skipWaiting and activate a new SW immediately.+// Guard against messages from unexpected origins (missing-origin-check mitigation).self.addEventListener('message', (event) => {+ // Only accept messages from the same origin as the service worker registration.+ if (+ event.origin &&+ event.origin !== self.location.origin+ ) {+ return;+ }if (event.data && event.data.type === 'SKIP_WAITING') {self.skipWaiting();}diff --git a/apps/web/src/app/(app)/purple-team/page.tsx b/apps/web/src/app/(app)/purple-team/page.tsxindex 9530d98aa..6c468509b 100644--- a/apps/web/src/app/(app)/purple-team/page.tsx+++ b/apps/web/src/app/(app)/purple-team/page.tsx@@ -401,7 +401,7 @@ function CoverageHeatmap() {}function ExecutionsTable({ onReportDetection }: { onReportDetection: (ex: Execution) => void }) {- const { data, error, isLoading, mutate } = useSWR<Execution[]>(+ const { data, error, isLoading } = useSWR<Execution[]>(`${API}/api/v1/purple-team/executions?tenant_id=${TENANT_ID}&limit=50`,fetcher,{ refreshInterval: 10000 }diff --git a/apps/web/src/components/alerts/AlertDetailView.tsx b/apps/web/src/components/alerts/AlertDetailView.tsxindex 47fe52eaa..d139cce16 100644--- a/apps/web/src/components/alerts/AlertDetailView.tsx+++ b/apps/web/src/components/alerts/AlertDetailView.tsx@@ -339,11 +339,8 @@ function LedgerEvidenceChain({ runId }: { runId: string }) {function AIInvestigation({ alertId }: { alertId: string }) {const [investigation, setInvestigation] = useState<AgentInvestigation | null>(null);const [isRunning, setIsRunning] = useState(false);- const [error, setError] = useState<string | null>(null);-const startInvestigation = async () => {setIsRunning(true);- setError(null);try {const result = await agentsApi.investigate(alertId);setInvestigation(result);diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsxindex f7ddb36fe..ceb9b647b 100644--- a/apps/web/src/components/alerts/AlertsView.tsx+++ b/apps/web/src/components/alerts/AlertsView.tsx@@ -3,9 +3,9 @@import { useState, useCallback } from 'react';import useSWR from 'swr';import Link from 'next/link';-import { alertsApi, type Alert, type AlertFilters, type ConfidenceLabel } from '@/lib/api';+import { alertsApi, type Alert, type AlertFilters } from '@/lib/api';import { clsx } from 'clsx';-import { format, formatDistanceToNow } from 'date-fns';+import { formatDistanceToNow } from 'date-fns';import { EntityRiskQueue } from './EntityRiskQueue';// Wave 1 of the AiSOC v6 capability roadmap. The "entities" tab renders the@@ -171,7 +171,6 @@ function FiltersBar({}function AlertRow({ alert }: { alert: Alert }) {- const sevCfg = SEVERITY_CONFIG[alert.severity as keyof typeof SEVERITY_CONFIG] || SEVERITY_CONFIG.info;return (<Linkhref={`/alerts/${alert.id}`}@@ -215,7 +214,6 @@ function AlertRow({ alert }: { alert: Alert }) {export function AlertsView() {const [filters, setFilters] = useState<AlertFilters>({ page: 1, pageSize: 25 });- const [selectedIds] = useState(new Set<string>());// Default to the entity-centric queue — that's the whole point of Wave 1's// RBA work. Analysts can flip back to the raw alert grid for legacy// workflows or when triaging a specific alert ID.diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsxindex 214ff0ca7..2cf782370 100644--- a/apps/web/src/components/cases/CasesView.tsx+++ b/apps/web/src/components/cases/CasesView.tsx@@ -105,13 +105,11 @@ function CaseCard({ c }: { c: Case }) {// ─── Main View ────────────────────────────────────────────────────────────────-type SortKey = 'createdAt' | 'severity' | 'status' | 'alertCount';type FilterStatus = Case['status'] | 'all';export function CasesView() {const [statusFilter, setStatusFilter] = useState<FilterStatus>('all');const [severityFilter, setSeverityFilter] = useState<Case['severity'] | 'all'>('all');- const [sortBy] = useState<SortKey>('createdAt');const [search, setSearch] = useState('');const { data: casesData, isLoading } = useSWR(@@ -160,7 +158,6 @@ export function CasesView() {{/* Stats */}<div className="grid grid-cols-5 gap-3">{(['all', 'open', 'in_progress', 'resolved', 'closed'] as const).map((s) => {- const stsCfg = s === 'all' ? null : STATUS_CONFIG[s];return (<buttonkey={s}diff --git a/apps/web/src/components/compliance/ComplianceHeatmap.tsx b/apps/web/src/components/compliance/ComplianceHeatmap.tsxindex cb2b9579c..22e6ca890 100644--- a/apps/web/src/components/compliance/ComplianceHeatmap.tsx+++ b/apps/web/src/components/compliance/ComplianceHeatmap.tsx@@ -1,7 +1,6 @@'use client';import useSWR from 'swr';-import { useState } from 'react';interface HeatmapCell {category: string;diff --git a/apps/web/src/components/copilot/CopilotView.tsx b/apps/web/src/components/copilot/CopilotView.tsxindex 8aac9d685..101781e58 100644--- a/apps/web/src/components/copilot/CopilotView.tsx+++ b/apps/web/src/components/copilot/CopilotView.tsx@@ -12,7 +12,7 @@* dev / no-LLM environments. Streaming is preferred when available.*/-import { useEffect, useMemo, useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import useSWR from 'swr';import { clsx } from 'clsx';import { motion, AnimatePresence } from 'framer-motion';@@ -22,8 +22,6 @@ import {type CopilotMessage,} from '@/lib/api';import { Skeleton } from '@/components/ui/Skeleton';-import { ErrorState } from '@/components/ui/ErrorState';-import { EmptyState } from '@/components/ui/EmptyState';// ─── Suggested prompts ───────────────────────────────────────────────────────diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsxindex d193e31f6..007b2bb2a 100644--- a/apps/web/src/components/dashboard/DashboardView.tsx+++ b/apps/web/src/components/dashboard/DashboardView.tsx@@ -117,7 +117,7 @@ function CustomTooltip({ active, payload, label }: any) {// ─── Main Dashboard ───────────────────────────────────────────────────────────export function DashboardView() {- const { data: metrics = MOCK_METRICS, isLoading } = useSWR(+ const { data: metrics = MOCK_METRICS } = useSWR('dashboard-metrics',() => metricsApi.getDashboard(),{ fallbackData: MOCK_METRICS, refreshInterval: 60000 }diff --git a/apps/web/src/components/detections/DetectionCatalog.tsx b/apps/web/src/components/detections/DetectionCatalog.tsxindex 127d1d48e..12eb20d17 100644--- a/apps/web/src/components/detections/DetectionCatalog.tsx+++ b/apps/web/src/components/detections/DetectionCatalog.tsx@@ -1,6 +1,6 @@'use client';-import { useState, useMemo } from 'react';+import { useState } from 'react';import clsx from 'clsx';// ── Types ─────────────────────────────────────────────────────────────────────diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsxindex 59efabb34..8d3ce1fe5 100644--- a/apps/web/src/components/settings/SettingsView.tsx+++ b/apps/web/src/components/settings/SettingsView.tsx@@ -903,8 +903,10 @@ function ApiKeysPanel() {toast.error('Give the key a name');return;}- const id = `key-${Math.random().toString(36).slice(2, 8)}`;- const secretBody = Math.random().toString(36).slice(2, 14);+ const idBytes = crypto.getRandomValues(new Uint8Array(6));+ const id = `key-${Array.from(idBytes).map(b => b.toString(16).padStart(2, '0')).join('')}`;+ const secretBytes = crypto.getRandomValues(new Uint8Array(16));+ const secretBody = Array.from(secretBytes).map(b => b.toString(16).padStart(2, '0')).join('');const secret = `aisoc_live_${secretBody}`;const key: ApiKey = {id,diff --git a/packages/aisoc-cli/src/aisoc_cli/main.py b/packages/aisoc-cli/src/aisoc_cli/main.pyindex a66e8c8db..c774f08cc 100644--- a/packages/aisoc-cli/src/aisoc_cli/main.py+++ b/packages/aisoc-cli/src/aisoc_cli/main.py@@ -12,18 +12,15 @@ from __future__ import annotationsimport base64import json-import osimport sys-from pathlib import Pathfrom typing import Anyimport clickimport httpximport yaml-from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric.ed25519 import (Ed25519PrivateKey,- Ed25519PublicKey,)from jsonschema import ValidationError, validatefrom rich.console import Consolediff --git a/packages/aisoc-cli/tests/test_cli.py b/packages/aisoc-cli/tests/test_cli.pyindex 076ef995f..ced3573bd 100644--- a/packages/aisoc-cli/tests/test_cli.py+++ b/packages/aisoc-cli/tests/test_cli.py@@ -1,8 +1,4 @@"""Tests for aisoc-cli commands."""-import json-import os-from pathlib import Path-import pytestimport yamlfrom click.testing import CliRunnerdiff --git a/packages/plugin-sdk-py/src/aisoc_plugin_sdk/decorators.py b/packages/plugin-sdk-py/src/aisoc_plugin_sdk/decorators.pyindex a4c972277..1f7a3d8ba 100644--- a/packages/plugin-sdk-py/src/aisoc_plugin_sdk/decorators.py+++ b/packages/plugin-sdk-py/src/aisoc_plugin_sdk/decorators.py@@ -2,7 +2,6 @@from __future__ import annotations-import functoolsfrom typing import Any, Callablefrom .plugin import PluginManifestdiff --git a/packages/plugin-sdk-py/tests/test_client.py b/packages/plugin-sdk-py/tests/test_client.pyindex 600f760cd..6b629cb2c 100644--- a/packages/plugin-sdk-py/tests/test_client.py+++ b/packages/plugin-sdk-py/tests/test_client.py@@ -2,7 +2,6 @@from __future__ import annotations-import jsonimport pytestimport httpxdiff --git a/packages/sdk-py/tests/test_client.py b/packages/sdk-py/tests/test_client.pyindex e81ba3987..4a18166e6 100644--- a/packages/sdk-py/tests/test_client.py+++ b/packages/sdk-py/tests/test_client.py@@ -5,7 +5,6 @@ Uses pytest-httpx to intercept outgoing requests — no real server needed.from __future__ import annotations-import jsonimport pytestfrom pytest_httpx import HTTPXMockdiff --git a/packages/sdk-ts/src/client.ts b/packages/sdk-ts/src/client.tsindex 1252486a5..afdd3141a 100644--- a/packages/sdk-ts/src/client.ts+++ b/packages/sdk-ts/src/client.ts@@ -10,7 +10,6 @@* client.apiKeys.* – API key management*/-import createClient, { type ClientOptions } from "openapi-fetch";import type {Alert,AlertFilters,@@ -42,48 +41,6 @@ export interface AiSOCClientOptions {fetch?: typeof globalThis.fetch;}-// ─── Internal fetch wrapper ───────────────────────────────────────────────────--function buildFetchClient(opts: AiSOCClientOptions) {- const clientOpts: ClientOptions = {- baseUrl: opts.baseUrl,- headers: {- Authorization: `Bearer ${opts.token}`,- "Content-Type": "application/json",- ...opts.headers,- },- };- if (opts.fetch) {- clientOpts.fetch = opts.fetch;- }- return createClient<Record<string, unknown>>(clientOpts);-}--type FetchClient = ReturnType<typeof buildFetchClient>;--async function get<T>(- fetchClient: FetchClient,- path: string,- params?: Record<string, unknown>,-): Promise<T> {- const url = new URL(path, "http://localhost");- if (params) {- for (const [k, v] of Object.entries(params)) {- if (v !== undefined && v !== null) {- url.searchParams.set(k, String(v));- }- }- }- const fullPath = url.pathname + url.search;- const res = await fetch(- String(new URL(fullPath, fetchClient as unknown as string)),- );- if (!res.ok) {- throw new AiSOCError(res.status, await res.text());- }- return res.json() as Promise<T>;-}-// ─── Error class ─────────────────────────────────────────────────────────────export class AiSOCError extends Error {diff --git a/plugins/okta-connector/plugin.py b/plugins/okta-connector/plugin.pyindex 7faf89ef1..50b655f61 100644--- a/plugins/okta-connector/plugin.py+++ b/plugins/okta-connector/plugin.py@@ -71,19 +71,20 @@ class Plugin:async with self._client(context) as client:match action:case "get_user":- return await self._get_user(client, user_id)+ result = await self._get_user(client, user_id)case "list_sessions":- return await self._list_sessions(client, user_id)+ result = await self._list_sessions(client, user_id)case "suspend_user":- return await self._suspend_user(client, user_id)+ result = await self._suspend_user(client, user_id)case "unsuspend_user":- return await self._unsuspend_user(client, user_id)+ result = await self._unsuspend_user(client, user_id)case "clear_user_sessions":- return await self._clear_sessions(client, user_id)+ result = await self._clear_sessions(client, user_id)case "clear_mfa_factors":- return await self._clear_mfa(client, user_id)+ result = await self._clear_mfa(client, user_id)case _:- return {"error": f"Unknown action: {action}"}+ result = {"error": f"Unknown action: {action}"}+ return result# ── Actions ───────────────────────────────────────────────────────────────diff --git a/scripts/aisoc-demo.ts b/scripts/aisoc-demo.tsindex b9bd036c8..cb48e84df 100644--- a/scripts/aisoc-demo.ts+++ b/scripts/aisoc-demo.ts@@ -325,6 +325,13 @@ function seedData(): boolean {return true;}+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function sanitizeCaseId(id: unknown): string | null {+ if (typeof id === "string" && UUID_RE.test(id)) return id;+ return null;+}+async function findSeededCase(): Promise<{ id: string; case_number: string; title: string } | null> {step(6, 7, "Locating a seeded case");// The dev-mode auth bypass returns the demo user/tenant for unauthenticated@@ -333,8 +340,13 @@ async function findSeededCase(): Promise<{ id: string; case_number: string; titlconst res = await fetchJson("http://localhost:8000/v1/cases?page_size=5", 4000);if (res && Array.isArray(res.items) && res.items.length > 0) {const c0 = res.items[0];- log(c.green("ok") + ` found case ${c0.case_number} (${c0.id})`);- return { id: c0.id, case_number: c0.case_number, title: c0.title };+ const safeId = sanitizeCaseId(c0.id);+ if (!safeId) {+ log(c.yellow("warn") + " API returned a non-UUID case ID — skipping");+ return null;+ }+ log(c.green("ok") + ` found case ${c0.case_number} (${safeId})`);+ return { id: safeId, case_number: c0.case_number, title: c0.title };}await new Promise((r) => setTimeout(r, 2000));}diff --git a/scripts/build_marketplace.py b/scripts/build_marketplace.pyindex f84535515..75544de5c 100644--- a/scripts/build_marketplace.py+++ b/scripts/build_marketplace.py@@ -262,7 +262,7 @@ def build_detection_item(if len(rel) >= 4 and rel[1] == "_quarantine":category = rel[2]except ValueError:- pass+ pass # path is not relative to DETECTIONS_DIR; category stays Noneitem: dict[str, Any] = {"id": data.get("id") or path.stem,diff --git a/scripts/detection_specs_part3_application.py b/scripts/detection_specs_part3_application.pyindex 19cb4ee86..fbacc6ff6 100644--- a/scripts/detection_specs_part3_application.py+++ b/scripts/detection_specs_part3_application.py@@ -10,9 +10,6 @@ application rules in ``detection_specs.APPLICATION`` (~25 stable rules).from __future__ import annotationsfrom detection_specs_part3_helpers import ( # type: ignore[import-not-found]- FP_AUTOMATION,- FP_FORENSIC,- FP_PATCH,FP_PENTEST,FP_TUNING,S,diff --git a/scripts/detection_specs_part3_cloud.py b/scripts/detection_specs_part3_cloud.pyindex 88595112d..8b5fac7a8 100644--- a/scripts/detection_specs_part3_cloud.py+++ b/scripts/detection_specs_part3_cloud.py@@ -29,9 +29,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]FP_BACKUP,FP_BREAK_GLASS,FP_FORENSIC,- FP_ONBOARD,- FP_PATCH,- FP_PENTEST,FP_TUNING,S,)diff --git a/scripts/detection_specs_part3_endpoint.py b/scripts/detection_specs_part3_endpoint.pyindex 6ad179408..89d7f257b 100644--- a/scripts/detection_specs_part3_endpoint.py+++ b/scripts/detection_specs_part3_endpoint.py@@ -18,7 +18,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]FP_BACKUP,FP_BREAK_GLASS,FP_FORENSIC,- FP_ONBOARD,FP_PATCH,FP_PENTEST,FP_TUNING,diff --git a/scripts/detection_specs_part3_helpers.py b/scripts/detection_specs_part3_helpers.pyindex 7185b24cc..aadb7b980 100644--- a/scripts/detection_specs_part3_helpers.py+++ b/scripts/detection_specs_part3_helpers.py@@ -67,8 +67,6 @@ def split_op(key: str) -> tuple[str, str]:# Sample value pool for negation. Uses values unlikely to collide with# realistic field domains._SENTINEL_STR = "__benign__"-_SENTINEL_NUM = 0-_SENTINEL_BOOL = Falsedef _pos_for(op: str, expected: Any) -> Any:@@ -355,10 +353,8 @@ def build_negative()else:first_key = next(iter(when.keys()))- target_key = first_key- target_field_name, target_op = split_op(first_key)+ neg_field, target_op = split_op(first_key)target_expected = when[first_key]- neg_field = target_field_nameneg[neg_field] = _neg_for(target_op, target_expected)return negdiff --git a/scripts/detection_specs_part3_identity.py b/scripts/detection_specs_part3_identity.pyindex ce379f48c..b2442a7fa 100644--- a/scripts/detection_specs_part3_identity.py+++ b/scripts/detection_specs_part3_identity.py@@ -20,7 +20,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]FP_BREAK_GLASS,FP_FORENSIC,FP_ONBOARD,- FP_PATCH,FP_PENTEST,FP_TUNING,S,diff --git a/scripts/detection_specs_part3_network.py b/scripts/detection_specs_part3_network.pyindex 613e18046..acaac3d7b 100644--- a/scripts/detection_specs_part3_network.py+++ b/scripts/detection_specs_part3_network.py@@ -11,12 +11,7 @@ from __future__ import annotationsfrom detection_specs_part3_helpers import ( # type: ignore[import-not-found]FP_AUTOMATION,- FP_BACKUP,- FP_BREAK_GLASS,- FP_FORENSIC,- FP_PATCH,FP_PENTEST,- FP_TUNING,S,)diff --git a/scripts/eval_mitre_accuracy.py b/scripts/eval_mitre_accuracy.pyindex 1bdf504dc..5018fe3c7 100755--- a/scripts/eval_mitre_accuracy.py+++ b/scripts/eval_mitre_accuracy.py@@ -14,7 +14,6 @@ This script is also the entrypoint for the p1-eval CI step.from __future__ import annotationsimport argparse-import jsonimport sysfrom pathlib import Path@@ -22,7 +21,7 @@ from pathlib import Path_REPO_ROOT = Path(__file__).parent.parentsys.path.insert(0, str(_REPO_ROOT / "services" / "agents"))-from tests.test_mitre_accuracy import evaluate_mitre_accuracy, SYNTHETIC_INCIDENTS+from tests.test_mitre_accuracy import evaluate_mitre_accuracydef main() -> None:diff --git a/scripts/generate_adversary_incidents.py b/scripts/generate_adversary_incidents.pyindex 769d07dfd..9740734b2 100644--- a/scripts/generate_adversary_incidents.py+++ b/scripts/generate_adversary_incidents.py@@ -95,7 +95,7 @@ _SYNONYMS: dict[str, tuple[str, ...]] = {"new geography": ("unseen origin region", "anomalous origin", "first-time origin"),"compromised npm": ("trojanized js-libs release", "doctored js-libs build", "polluted js-libs feed"),"container image": ("workload bundle", "runtime workload artifact", "compute workload bundle"),- "wire transfer": ("ach instruction", "outgoing remittance", "treasury debit instruction"),+ "wire transfer initial": ("ach instruction", "outgoing remittance", "treasury debit instruction"),# TA0002 — Execution"execution": ("payload delivery step", "binary launch", "code activation"),diff --git a/scripts/generate_detections.py b/scripts/generate_detections.pyindex be508725d..e16d4edd3 100644--- a/scripts/generate_detections.py+++ b/scripts/generate_detections.py@@ -45,8 +45,10 @@ from typing import Anytry:import yamlexcept ImportError:- print("ERROR: PyYAML not installed. Run: pip install pyyaml", file=sys.stderr)- sys.exit(1)+ if __name__ == "__main__":+ print("ERROR: PyYAML not installed. Run: pip install pyyaml", file=sys.stderr)+ sys.exit(1)+ raiseROOT = Path(__file__).parent.parentDETECTIONS_DIR = ROOT / "detections"diff --git a/scripts/generate_runbook.py b/scripts/generate_runbook.pyindex 25fec7b32..a3a253b3e 100755--- a/scripts/generate_runbook.py+++ b/scripts/generate_runbook.py@@ -23,7 +23,6 @@ Environment variablesfrom __future__ import annotationsimport argparse-import jsonimport loggingimport osimport sysdiff --git a/services/actions/app/executors/base.py b/services/actions/app/executors/base.pyindex 0eb4163c7..48991dd34 100644--- a/services/actions/app/executors/base.py+++ b/services/actions/app/executors/base.py@@ -15,7 +15,6 @@ class BaseExecutor(ABC):@abstractmethodasync def execute(self, request: ActionRequest) -> ActionResult:"""Execute the action and return a result."""- ...async def rollback(self, result: ActionResult) -> bool:"""diff --git a/services/agents/app/api/contextual.py b/services/agents/app/api/contextual.pyindex 70557a54b..9408fc016 100644--- a/services/agents/app/api/contextual.py+++ b/services/agents/app/api/contextual.py@@ -522,8 +522,9 @@ async def run_action_stream(req: ContextualActionRequest) -> StreamingResponse:try:async for chunk in _stream_llm(system, user, model):yield (json.dumps({"delta": chunk}) + "\n").encode()- except Exception as exc: # noqa: BLE001- yield (json.dumps({"error": str(exc)}) + "\n").encode()+ except Exception: # noqa: BLE001+ logger.exception("contextual.stream.error")+ yield (json.dumps({"error": "Streaming failed. Please try again."}) + "\n").encode()# Footer frame with metadata + suggested follow-ups.yield (diff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.pyindex 92ef7607f..75d0f7efb 100644--- a/services/agents/app/api/copilot.py+++ b/services/agents/app/api/copilot.py@@ -14,6 +14,7 @@ unset so the demo path never breaks.from __future__ import annotations+import itertoolsimport jsonimport osimport uuid@@ -95,14 +96,11 @@ _SYNTHETIC_REPLIES = [),]-_reply_idx = 0+_reply_cycle = itertools.cycle(_SYNTHETIC_REPLIES)def _synthetic_reply(user_msg: str) -> str:- global _reply_idx- reply = _SYNTHETIC_REPLIES[_reply_idx % len(_SYNTHETIC_REPLIES)]- _reply_idx += 1- return reply+ return next(_reply_cycle)# ---------------------------------------------------------------------------diff --git a/services/agents/app/core/telemetry.py b/services/agents/app/core/telemetry.pyindex ba508e518..7abb33bfa 100644--- a/services/agents/app/core/telemetry.py+++ b/services/agents/app/core/telemetry.py@@ -105,14 +105,14 @@ def instrument_app(app) -> None: # noqa: ANN001FastAPIInstrumentor.instrument_app(app)except ImportError:- pass+ pass # optional dependency not installed; skip FastAPI auto-instrumentationtry:from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor # type: ignoreHTTPXClientInstrumentor().instrument()except ImportError:- pass+ pass # optional dependency not installed; skip HTTPX auto-instrumentationdef get_tracer(name: str = "aisoc-agents") -> trace.Tracer:diff --git a/services/agents/app/tools/mitre_full.py b/services/agents/app/tools/mitre_full.pyindex 95abd6343..40567a2e4 100644--- a/services/agents/app/tools/mitre_full.py+++ b/services/agents/app/tools/mitre_full.py@@ -92,7 +92,6 @@ class MitreMitigation:_techniques: dict[str, MitreTechnique] = {}_actors: dict[str, MitreActor] = {}-_mitigations: dict[str, MitreMitigation] = {}_tactic_map: dict[str, str] = {} # tactic shortname → display name_loaded = False_load_time: float = 0.0diff --git a/services/agents/tests/test_hunt_corpus.py b/services/agents/tests/test_hunt_corpus.pyindex 2fa8a07b7..90d8dbe85 100644--- a/services/agents/tests/test_hunt_corpus.py+++ b/services/agents/tests/test_hunt_corpus.py@@ -36,12 +36,6 @@ from app.hunt.loader import HuntCorpus, HuntDefinition_TESTS_DIR = Path(__file__).parent_HUNT_TELEMETRY_PATH = _TESTS_DIR / "eval_data" / "synthetic_hunt_telemetry.jsonl"-# Per-hunt eval gates surfaced to ``scripts/run_evals.py``. The hunt corpus-# is small (every hunt is hand-authored), so we hold ourselves to perfect-# scenario coverage rather than a percentage floor.-_POSITIVE_FLOOR = 1.0 # every hunt MUST fire on its declared positive scenario-_NEGATIVE_CEILING = 0.0 # zero false positives on declared negative scenarios-def _load_hunt_corpus() -> list[HuntDefinition]:"""Load the YAML hunt corpus from ``hunts/`` (repo root)."""diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 437655df4..275894134 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -1,10 +1,13 @@"""Case management endpoints."""import os+import reimport uuidfrom datetime import UTC, datetimefrom typing import Annotated, Any+_RUN_ID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE)+import httpxfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom pydantic import BaseModel, Field@@ -325,9 +328,11 @@ async def investigate_case(resp.raise_for_status()data = resp.json()except httpx.HTTPStatusError as exc:- raise HTTPException(status_code=502, detail=f"Agents service error: {exc.response.text}") from exc+ logger.error("agents_service_http_error", status=exc.response.status_code)+ raise HTTPException(status_code=502, detail="Agents service returned an error") from excexcept Exception as exc: # noqa: BLE001- raise HTTPException(status_code=503, detail=f"Agents service unavailable: {exc}") from exc+ logger.error("agents_service_unavailable", error=type(exc).__name__)+ raise HTTPException(status_code=503, detail="Agents service unavailable") from exc# Record timeline entrydb.add(@@ -346,6 +351,12 @@ async def investigate_case(return InvestigateResponse(**data)+def _validate_run_id(run_id: str) -> None:+ """Raise 422 if run_id is not a UUID to prevent partial-SSRF via path injection."""+ if not _RUN_ID_RE.match(run_id):+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Invalid run_id format")++@router.get("/{case_id}/investigations/{run_id}")async def get_case_investigation(case_id: uuid.UUID,@@ -353,15 +364,16 @@ async def get_case_investigation(current_user: Annotated[AuthUser, Depends(require_permission("cases:read"))],) -> dict[str, Any]:"""Proxy: poll investigation run status from the agents service."""+ _validate_run_id(run_id)try:async with httpx.AsyncClient(timeout=10.0) as client:resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}")resp.raise_for_status()return resp.json()except httpx.HTTPStatusError as exc:- raise HTTPException(status_code=exc.response.status_code, detail=exc.response.text) from exc+ raise HTTPException(status_code=exc.response.status_code, detail="Upstream service error") from excexcept Exception as exc: # noqa: BLE001- raise HTTPException(status_code=503, detail=str(exc)) from exc+ raise HTTPException(status_code=503, detail="Agents service unavailable") from exc@router.get("/{case_id}/investigations/{run_id}/report.md")@@ -373,15 +385,16 @@ async def get_case_report_md("""Proxy: download Markdown incident report from the agents service."""from fastapi.responses import PlainTextResponse+ _validate_run_id(run_id)try:async with httpx.AsyncClient(timeout=30.0) as client:resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}/report.md")resp.raise_for_status()return PlainTextResponse(content=resp.text)except httpx.HTTPStatusError as exc:- raise HTTPException(status_code=exc.response.status_code, detail=exc.response.text) from exc+ raise HTTPException(status_code=exc.response.status_code, detail="Upstream service error") from excexcept Exception as exc: # noqa: BLE001- raise HTTPException(status_code=503, detail=str(exc)) from exc+ raise HTTPException(status_code=503, detail="Agents service unavailable") from exc@router.get("/{case_id}/investigations/{run_id}/report.html")@@ -393,15 +406,16 @@ async def get_case_report_html("""Proxy: download HTML incident report from the agents service."""from fastapi.responses import HTMLResponse+ _validate_run_id(run_id)try:async with httpx.AsyncClient(timeout=30.0) as client:resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}/report.html")resp.raise_for_status()return HTMLResponse(content=resp.text)except httpx.HTTPStatusError as exc:- raise HTTPException(status_code=exc.response.status_code, detail=exc.response.text) from exc+ raise HTTPException(status_code=exc.response.status_code, detail="Upstream service error") from excexcept Exception as exc: # noqa: BLE001- raise HTTPException(status_code=503, detail=str(exc)) from exc+ raise HTTPException(status_code=503, detail="Agents service unavailable") from exc@router.get("/{case_id}/investigations/{run_id}/report.pdf")@@ -413,6 +427,7 @@ async def get_case_report_pdf("""Proxy: download PDF incident report (rendered by weasyprint in agents service)."""from fastapi.responses import Response as FastAPIResponse+ _validate_run_id(run_id)try:async with httpx.AsyncClient(timeout=60.0) as client:resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}/report.pdf")@@ -423,6 +438,6 @@ async def get_case_report_pdf(headers={"Content-Disposition": f'attachment; filename="aisoc-report-{run_id}.pdf"'},)except httpx.HTTPStatusError as exc:- raise HTTPException(status_code=exc.response.status_code, detail=exc.response.text) from exc+ raise HTTPException(status_code=exc.response.status_code, detail="Upstream service error") from excexcept Exception as exc: # noqa: BLE001- raise HTTPException(status_code=503, detail=str(exc)) from exc+ raise HTTPException(status_code=503, detail="Agents service unavailable") from excdiff --git a/services/api/app/api/v1/endpoints/connectors.py b/services/api/app/api/v1/endpoints/connectors.pyindex 9c93740c6..ed5be33ea 100644--- a/services/api/app/api/v1/endpoints/connectors.py+++ b/services/api/app/api/v1/endpoints/connectors.py@@ -34,10 +34,15 @@ Tenant scoping invariants enforced here:from __future__ import annotationsimport logging+import reimport uuidfrom datetime import UTC, datetimefrom typing import Annotated, Any+# Connector type IDs are restricted to alphanumeric, hyphens, and underscores.+# This prevents path-traversal / partial-SSRF via user-supplied connector_type.+_CONNECTOR_TYPE_RE = re.compile(r"^[a-zA-Z0-9_\-]{1,100}$")+import httpxfrom fastapi import APIRouter, Depends, HTTPException, statusfrom pydantic import BaseModel, Field@@ -155,7 +160,7 @@ async def _fetch_catalog() -> list[dict[str, Any]]:resp = await client.get(url)resp.raise_for_status()except httpx.HTTPError as exc:- logger.warning("connectors_service.catalog.unreachable url=%s err=%s", url, exc)+ logger.warning("connectors_service.catalog.unreachable url=%s error_type=%s", url, type(exc).__name__)raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail="connectors service is unavailable; cannot list connector catalog",@@ -204,6 +209,11 @@ async def _proxy_test_connection(add a shared-secret header (mirroring how the realtime push proxy inthis codebase does it)."""+ if not _CONNECTOR_TYPE_RE.match(connector_type):+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="connector_type contains invalid characters",+ )url = _connectors_service_url(f"/connectors/{connector_type}/test")payload = {"auth_config": auth_config,diff --git a/services/api/app/api/v1/endpoints/federated.py b/services/api/app/api/v1/endpoints/federated.pyindex 7902fd79f..39328f4ce 100644--- a/services/api/app/api/v1/endpoints/federated.py+++ b/services/api/app/api/v1/endpoints/federated.py@@ -157,12 +157,6 @@ class FederatedBackendsResponse(BaseModel):# ----------------------------------------------------------------------- helpers-_QUERY_TIMEOUT = httpx.Timeout(- settings.CONNECTORS_SERVICE_TIMEOUT_SECONDS,- connect=min(5.0, settings.CONNECTORS_SERVICE_TIMEOUT_SECONDS),-)--def _connectors_query_url(connector_type: str) -> str:base = settings.CONNECTORS_SERVICE_URL.rstrip("/")return f"{base}/api/v1/connectors/{connector_type}/query"diff --git a/services/api/app/api/v1/endpoints/playbooks.py b/services/api/app/api/v1/endpoints/playbooks.pyindex afd8c776a..b9493b479 100644--- a/services/api/app/api/v1/endpoints/playbooks.py+++ b/services/api/app/api/v1/endpoints/playbooks.py@@ -9,15 +9,28 @@ one place while the engine lives in services/agents.from __future__ import annotationsimport os+import refrom typing import Anyimport httpx-from fastapi import APIRouter, HTTPException, Request+from fastapi import APIRouter, HTTPException, Request, status_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL", "http://agents:8084")router = APIRouter(prefix="/playbooks", tags=["playbooks"])+# Allowlist for playbook/run IDs: UUIDs or short slug-style alphanumeric IDs.+# Prevents partial-SSRF via path traversal in proxied requests.+_SAFE_ID_RE = re.compile(r"^[0-9a-zA-Z_\-]{1,128}$")+++def _validate_path_id(value: str, name: str = "id") -> None:+ if not _SAFE_ID_RE.match(value):+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"Invalid {name} format",+ )+async def _proxy(method: str, path: str, **kwargs) -> Any:"""Forward a request to the agents service and return the JSON body."""@@ -26,12 +39,12 @@ async def _proxy(method: str, path: str, **kwargs) -> Any:async with httpx.AsyncClient(timeout=60) as client:r = await client.request(method, url, **kwargs)if r.status_code >= 400:- raise HTTPException(status_code=r.status_code, detail=r.text)+ raise HTTPException(status_code=r.status_code, detail="Upstream service error")if r.status_code == 204:return Nonereturn r.json()except httpx.RequestError as exc:- raise HTTPException(status_code=503, detail=f"Agents service unavailable: {exc}") from exc+ raise HTTPException(status_code=503, detail="Agents service unavailable") from exc# ---------------------------------------------------------------------------@@ -57,26 +70,31 @@ async def list_runs(limit: int = 50):@router.get("/runs/{run_id}", summary="Get a playbook run")async def get_run(run_id: str):+ _validate_path_id(run_id, "run_id")return await _proxy("GET", f"/runs/{run_id}")@router.get("/{playbook_id}", summary="Get a playbook")async def get_playbook(playbook_id: str):+ _validate_path_id(playbook_id, "playbook_id")return await _proxy("GET", f"/{playbook_id}")@router.put("/{playbook_id}", summary="Update a playbook")async def update_playbook(playbook_id: str, request: Request):+ _validate_path_id(playbook_id, "playbook_id")body = await request.json()return await _proxy("PUT", f"/{playbook_id}", json=body)@router.delete("/{playbook_id}", summary="Delete a playbook", status_code=204, response_model=None)async def delete_playbook(playbook_id: str):+ _validate_path_id(playbook_id, "playbook_id")await _proxy("DELETE", f"/{playbook_id}")@router.post("/{playbook_id}/run", summary="Execute a playbook", status_code=202)async def run_playbook(playbook_id: str, request: Request):+ _validate_path_id(playbook_id, "playbook_id")body = await request.json()return await _proxy("POST", f"/{playbook_id}/run", json=body)diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.pyindex e0fcc3870..01b834de1 100644--- a/services/api/app/auth/oidc.py+++ b/services/api/app/auth/oidc.py@@ -24,6 +24,7 @@ from __future__ import annotationsimport hashlibimport loggingimport os+import reimport secretsfrom datetime import UTC, datetime, timedeltafrom typing import Any@@ -87,6 +88,16 @@ def _pop_state(state: str) -> dict[str, str] | None:return _state_store.pop(state, None)+_SAFE_REDIRECT_RE = re.compile(r"^/[\w\-./]*$")+++def _safe_redirect(url: str) -> str:+ """Return *url* only if it is a safe relative path; otherwise return '/'."""+ if url and _SAFE_REDIRECT_RE.match(url):+ return url+ return "/"++# ─── Routes ───────────────────────────────────────────────────────────────────@@ -99,11 +110,12 @@ async def oidc_login(request: Request, redirect: str = "/") -> Response:scopes = os.getenv("OIDC_SCOPES", "openid email profile")use_pkce = os.getenv("OIDC_PKCE", "true").lower() == "true"+ safe_redirect = _safe_redirect(redirect)if not issuer or not client_id:# Stub modelogger.warning("OIDC not configured (OIDC_ISSUER / OIDC_CLIENT_ID missing) — issuing stub token")token = _issue_jwt({"sub": "oidc-stub-user", "email": "[email protected]", "provider": "oidc-stub"})- resp = RedirectResponse(url=redirect, status_code=302)+ resp = RedirectResponse(url=safe_redirect, status_code=302)resp.set_cookie("aisoc_token", token, httponly=True, samesite="lax")return resp@@ -114,7 +126,7 @@ async def oidc_login(request: Request, redirect: str = "/") -> Response:state = secrets.token_urlsafe(32)nonce = secrets.token_urlsafe(32)- state_data: dict[str, str] = {"redirect": redirect, "nonce": nonce}+ state_data: dict[str, str] = {"redirect": safe_redirect, "nonce": nonce}params: dict[str, str] = {"response_type": "code",@@ -195,8 +207,8 @@ async def oidc_callback(if id_token:try:claims = _jwt.decode(id_token, options={"verify_signature": False})- except Exception:- pass+ except Exception as exc: # noqa: BLE001+ logger.debug("Failed to decode id_token claims: %s", exc)access_token = tokens.get("access_token", "")@@ -262,7 +274,8 @@ async def oidc_userinfo(request: Request) -> JSONResponse:async def oidc_logout(request: Request, post_logout_redirect_uri: str = "/") -> Response:"""RP-initiated logout — clear cookie and redirect to provider end_session."""issuer = os.getenv("OIDC_ISSUER")- response = RedirectResponse(url=post_logout_redirect_uri, status_code=302)+ safe_uri = _safe_redirect(post_logout_redirect_uri)+ response = RedirectResponse(url=safe_uri, status_code=302)response.delete_cookie("aisoc_token")if issuer:@@ -270,10 +283,10 @@ async def oidc_logout(request: Request, post_logout_redirect_uri: str = "/") ->provider = await _discover(issuer)end_session = provider.get("end_session_endpoint")if end_session:- params = urlencode({"post_logout_redirect_uri": post_logout_redirect_uri})+ params = urlencode({"post_logout_redirect_uri": safe_uri})response = RedirectResponse(url=f"{end_session}?{params}", status_code=302)response.delete_cookie("aisoc_token")- except Exception:- pass+ except Exception as exc: # noqa: BLE001+ logger.debug("OIDC end_session discovery failed, falling back to local logout: %s", exc)return responsediff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.pyindex f3b68f9ea..1a69c1e2c 100644--- a/services/api/app/auth/saml.py+++ b/services/api/app/auth/saml.py@@ -29,6 +29,7 @@ from __future__ import annotationsimport loggingimport os+import refrom datetime import UTC, datetime, timedeltafrom typing import Any@@ -38,6 +39,15 @@ from fastapi.responses import HTMLResponse, RedirectResponse, Responselogger = logging.getLogger(__name__)+_SAFE_REDIRECT_RE = re.compile(r"^/[\w\-./]*$")+++def _safe_redirect(url: str) -> str:+ """Return *url* only if it is a safe relative path; otherwise return '/'."""+ if url and _SAFE_REDIRECT_RE.match(url):+ return url+ return "/"+router = APIRouter(prefix="/auth/saml", tags=["auth-saml"])# ─── JWT helpers ──────────────────────────────────────────────────────────────@@ -156,8 +166,8 @@ async def saml_acs(request: Request) -> Response:})- relay_state = (await request.form()).get("RelayState", "/")- response = RedirectResponse(url=str(relay_state), status_code=302)+ relay_state = _safe_redirect(str((await request.form()).get("RelayState", "/")))+ response = RedirectResponse(url=relay_state, status_code=302)response.set_cookie("aisoc_token", token, httponly=True, samesite="lax", secure=request.url.scheme == "https")return responsediff --git a/services/api/app/middleware/audit_middleware.py b/services/api/app/middleware/audit_middleware.pyindex 63a29eb93..0c5199611 100644--- a/services/api/app/middleware/audit_middleware.py+++ b/services/api/app/middleware/audit_middleware.py@@ -94,7 +94,7 @@ class AuditMiddleware(BaseHTTPMiddleware):resource_id = segbreakexcept ValueError:- pass+ pass # segment is not a UUID; try nextasync with AsyncSessionLocal() as db:from app.models.audit import AuditLog # noqa: PLC0415diff --git a/services/api/app/services/compliance.py b/services/api/app/services/compliance.pyindex 4f08f88d6..c32db3c63 100644--- a/services/api/app/services/compliance.py+++ b/services/api/app/services/compliance.py@@ -15,19 +15,6 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.audit import AuditLogfrom app.models.compliance import ComplianceControl, ComplianceEvidence-# Map SOC 2 control_ids → evidence collection functions-_CONTROL_COLLECTORS: dict[str, str] = {- "CC6.1": "access_controls",- "CC6.2": "user_provisioning",- "CC6.3": "access_deprovisioning",- "CC7.1": "monitoring_detection",- "CC7.2": "system_monitoring",- "CC7.3": "security_event_evaluation",- "CC7.4": "incident_response",- "CC7.5": "incident_recovery",-}--async def auto_collect_evidence(db: AsyncSession,tenant_id: uuid.UUID,diff --git a/services/api/app/services/plugin_manager.py b/services/api/app/services/plugin_manager.pyindex b3333d23a..94ff91ebc 100644--- a/services/api/app/services/plugin_manager.py+++ b/services/api/app/services/plugin_manager.py@@ -242,8 +242,8 @@ def _read_signature(plugin_dir: Path) -> bytes | None:decoded = bytes.fromhex(text.decode("ascii"))if len(decoded) == 64: # Ed25519 signatures are exactly 64 bytesreturn decoded- except (UnicodeDecodeError, ValueError):- pass+ except (UnicodeDecodeError, ValueError):+ pass # not a hex-encoded Ed25519 signature; fall through to raw bytes# Otherwise treat the file as raw signature bytes.if len(raw) == 64:diff --git a/services/api/app/services/rule_engine.py b/services/api/app/services/rule_engine.pyindex cb4280279..0e6c4a6ec 100644--- a/services/api/app/services/rule_engine.py+++ b/services/api/app/services/rule_engine.py@@ -291,7 +291,7 @@ def execute_rule("kql": _run_kql,"eql": _run_eql,"lucene": lambda body, evts: (_run_kql(body, evts)[0], None),- "regex": lambda body, evts: _run_regex(body, evts),+ "regex": _run_regex,}runner = runners.get(lang)diff --git a/services/api/app/services/sla.py b/services/api/app/services/sla.pyindex eaec455c2..cbd0ccd20 100644--- a/services/api/app/services/sla.py+++ b/services/api/app/services/sla.py@@ -38,7 +38,7 @@ def merge_kpi_bar_dict(existing: dict | None, patch: dict[str, float]) -> dict[stry:out[k] = float(kb[k])except (TypeError, ValueError):- pass+ pass # non-numeric value; skip keyreturn outdiff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.pyindex 8df4e2777..9a40d32a6 100644--- a/services/connectors/app/api/router.py+++ b/services/connectors/app/api/router.py@@ -150,22 +150,22 @@ async def test_connector_connection(connector_id: str, payload: TestConnectionRestatus_code=status.HTTP_422_UNPROCESSABLE_ENTITY,detail=f"connector config does not match schema: {exc}",) from exc- except Exception as exc: # pragma: no cover - last-ditch+ except Exception: # pragma: no cover - last-ditchlogger.exception("connector.test.constructor_error", connector_id=connector_id)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail=f"failed to construct connector: {exc}",- ) from exc+ detail="Failed to construct connector. Check your configuration.",+ )try:result = await connector.test_connection()- except Exception as exc: # pragma: no cover - connector misbehaving+ except Exception: # pragma: no cover - connector misbehaving# A well-behaved connector swallows its own errors and returns# {"success": False, "error": ...}. If one raises anyway, we# convert to the same shape so the wizard UI doesn't have two# error formats to deal with.logger.exception("connector.test.runtime_error", connector_id=connector_id)- result = {"success": False, "connector": connector_id, "error": str(exc)}+ result = {"success": False, "connector": connector_id, "error": "Connection test failed"}if not isinstance(result, dict):# Defensive: some connectors might return None on success. Coerce.@@ -221,12 +221,12 @@ async def run_federated_query(connector_id: str, payload: FederatedQueryRequest)raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED, detail=str(exc)) from excexcept QueryError as exc:raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc- except Exception as exc:+ except Exception:logger.exception("connector.query.runtime_error", connector_id=connector_id)raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY,- detail=f"backend query failed: {exc}",- ) from exc+ detail="Backend query failed. Check connector configuration and connectivity.",+ )return {"connector_id": connector_id,diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex 898e53092..e8f2d4129 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -152,19 +152,16 @@ class BaseConnector(ABC):docs_url="/docs/connectors/<id>",)"""- ...# ------------------------------ runtime ----------------------------------@abstractmethodasync def test_connection(self) -> dict[str, Any]:"""Test connectivity and credential validity."""- ...@abstractmethodasync def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:"""Fetch recent alerts/events from the source."""- ...def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:"""Normalize a raw event to a common AiSOC alert schema."""diff --git a/services/connectors/app/connectors/crowdstrike.py b/services/connectors/app/connectors/crowdstrike.pyindex a1a4895cb..5ce734db6 100644--- a/services/connectors/app/connectors/crowdstrike.py+++ b/services/connectors/app/connectors/crowdstrike.py@@ -15,10 +15,6 @@ from app.connectors.base import BaseConnector, ConnectorSchema, Fieldlogger = structlog.get_logger()-_AUTH_URL = "https://api.crowdstrike.com/oauth2/token"-_DETECTIONS_URL = "https://api.crowdstrike.com/detects/queries/detects/v1"-_DETECTION_DETAILS_URL = "https://api.crowdstrike.com/detects/entities/summaries/GET/v1"-class CrowdStrikeConnector(BaseConnector):connector_id = "crowdstrike"diff --git a/services/connectors/app/connectors/elastic.py b/services/connectors/app/connectors/elastic.pyindex b250d26f0..f21bf8fad 100644--- a/services/connectors/app/connectors/elastic.py+++ b/services/connectors/app/connectors/elastic.py@@ -60,6 +60,14 @@ class ElasticConnector(BaseConnector):required=False,default="logs-*",),+ Field(+ "ssl_verify",+ "boolean",+ "Verify SSL certificate",+ required=False,+ default=True,+ help_text="Disable only for self-signed certificates in private deployments.",+ ),],)@@ -70,6 +78,7 @@ class ElasticConnector(BaseConnector):username: str | None = None,password: str | None = None,index: str = "logs-*",+ ssl_verify: bool = True,):if not api_key and not (username and password):raise ValueError("Elastic connector requires either api_key or username+password")@@ -78,6 +87,7 @@ class ElasticConnector(BaseConnector):self._username = usernameself._password = passwordself._index = index+ self._ssl_verify = ssl_verifydef _headers(self) -> dict[str, str]:if self._api_key:@@ -93,7 +103,7 @@ class ElasticConnector(BaseConnector):}async def test_connection(self) -> dict[str, Any]:- async with httpx.AsyncClient(timeout=15.0, verify=False) as client:+ async with httpx.AsyncClient(timeout=15.0, verify=self._ssl_verify) as client:try:resp = await client.get(f"{self._base_url}/", headers=self._headers())resp.raise_for_status()@@ -105,12 +115,13 @@ class ElasticConnector(BaseConnector):"cluster_name": info.get("cluster_name"),}except Exception as exc:- return {"success": False, "connector": self.connector_id, "error": str(exc)}+ logger.warning("elastic.test_connection.failed", error_type=type(exc).__name__)+ return {"success": False, "connector": self.connector_id, "error": "Connection failed"}async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:# Elastic Security stores detection rule alerts in this hidden index pattern.esql = f"FROM .alerts-security.alerts-* | WHERE @timestamp > NOW() - {since_seconds} seconds | LIMIT 100"- async with httpx.AsyncClient(timeout=60.0, verify=False) as client:+ async with httpx.AsyncClient(timeout=60.0, verify=self._ssl_verify) as client:resp = await client.post(f"{self._base_url}/_query",headers=self._headers(),@@ -130,7 +141,7 @@ class ElasticConnector(BaseConnector):originating connector id."""esql = to_esql(unified, index=self._index)- async with httpx.AsyncClient(timeout=60.0, verify=False) as client:+ async with httpx.AsyncClient(timeout=60.0, verify=self._ssl_verify) as client:resp = await client.post(f"{self._base_url}/_query",headers=self._headers(),diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.pyindex 7f38db5ef..24aa7f2b1 100644--- a/services/connectors/app/connectors/github.py+++ b/services/connectors/app/connectors/github.py@@ -207,7 +207,7 @@ class GitHubConnector(BaseConnector):# all subsequent ones are also too old.breakexcept ValueError:- pass+ pass # unparseable timestamp; keep event without age filteralert["_aisoc_stream"] = "code_scanning"events.append(alert)elif cs_resp.status_code in (403, 404):diff --git a/services/connectors/app/connectors/splunk.py b/services/connectors/app/connectors/splunk.pyindex 69f392f28..f355b59c1 100644--- a/services/connectors/app/connectors/splunk.py+++ b/services/connectors/app/connectors/splunk.py@@ -47,13 +47,28 @@ class SplunkConnector(BaseConnector):required=False,default="AiSOC_Alerts",),+ Field(+ "ssl_verify",+ "boolean",+ "Verify SSL certificate",+ required=False,+ default=True,+ help_text="Disable only for self-signed certificates in private deployments.",+ ),],)- def __init__(self, base_url: str, token: str, saved_search: str = "AiSOC_Alerts"):+ def __init__(+ self,+ base_url: str,+ token: str,+ saved_search: str = "AiSOC_Alerts",+ ssl_verify: bool = True,+ ):self._base_url = base_url.rstrip("/")self._token = tokenself._saved_search = saved_search+ self._ssl_verify = ssl_verifydef _headers(self) -> dict[str, str]:return {@@ -62,7 +77,7 @@ class SplunkConnector(BaseConnector):}async def test_connection(self) -> dict[str, Any]:- async with httpx.AsyncClient(timeout=15.0, verify=False) as client:+ async with httpx.AsyncClient(timeout=15.0, verify=self._ssl_verify) as client:try:resp = await client.get(f"{self._base_url}/services/server/info",@@ -73,12 +88,13 @@ class SplunkConnector(BaseConnector):version = resp.json().get("entry", [{}])[0].get("content", {}).get("version")return {"success": True, "connector": self.connector_id, "version": version}except Exception as exc:- return {"success": False, "connector": self.connector_id, "error": str(exc)}+ logger.warning("splunk.test_connection.failed", error_type=type(exc).__name__)+ return {"success": False, "connector": self.connector_id, "error": "Connection failed"}async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:search_query = f"search index=notable earliest=-{since_seconds}s | head 100"- async with httpx.AsyncClient(timeout=60.0, verify=False) as client:+ async with httpx.AsyncClient(timeout=60.0, verify=self._ssl_verify) as client:# Create search jobresp = await client.post(f"{self._base_url}/services/search/jobs",@@ -126,7 +142,7 @@ class SplunkConnector(BaseConnector):"""index = self._saved_search if self._saved_search.startswith("index=") else "notable"spl = to_spl(unified, index=index)- async with httpx.AsyncClient(timeout=60.0, verify=False) as client:+ async with httpx.AsyncClient(timeout=60.0, verify=self._ssl_verify) as client:resp = await client.post(f"{self._base_url}/services/search/jobs",headers=self._headers(),diff --git a/services/connectors/app/ingest_client.py b/services/connectors/app/ingest_client.pyindex 00c2ba5c3..a2d274c52 100644--- a/services/connectors/app/ingest_client.py+++ b/services/connectors/app/ingest_client.py@@ -25,15 +25,12 @@ down, polls fail loudly and the scheduler records that infrom __future__ import annotations-import loggingimport osimport uuidfrom typing import Anyimport httpx-logger = logging.getLogger("aisoc.connectors.ingest_client")-# 30s mirrors the ingest service's own ReadTimeout. We don't want the client# to give up before the server has a chance to publish; we also don't want# polls to hang the scheduler thread for minutes if Kafka is wedged.diff --git a/services/purple-team/app/services/caldera_client.py b/services/purple-team/app/services/caldera_client.pyindex 71199bc21..016088120 100644--- a/services/purple-team/app/services/caldera_client.py+++ b/services/purple-team/app/services/caldera_client.py@@ -9,8 +9,6 @@ import httpxLOG = logging.getLogger(__name__)-_HEADERS = {"KEY": "", "Content-Type": "application/json"}-class CalderaClient:def __init__(self, base_url: str, api_key: str) -> None:diff --git a/services/purple-team/app/services/drift.py b/services/purple-team/app/services/drift.pyindex a7b0f41e4..bbed2c15a 100644--- a/services/purple-team/app/services/drift.py+++ b/services/purple-team/app/services/drift.py@@ -137,4 +137,11 @@ async def latest_two_snapshots(# NOTE: ``compute_drift`` (and its helper ``_index_techniques``) are# imported from ``app.services.drift_diff`` so the pure-Python delta# logic stays unit-testable without SQLAlchemy installed.-from app.services.drift_diff import compute_drift # noqa: E402,F401+from app.services.drift_diff import compute_drift # noqa: E402++__all__ = [+ "compute_drift",+ "get_latest_snapshots",+ "list_snapshots",+ "take_snapshot",+]diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.tsindex d83b8790c..8c38bf374 100644--- a/services/realtime/src/index.ts+++ b/services/realtime/src/index.ts@@ -67,7 +67,30 @@ server.on('upgrade', (req, socket, head) => {// channel it subscribed to so broadcasts can filter cheaply.const clients = new Map<string, Set<any>>();+// Simple IP-based connection rate limiter: max 20 WS connections per IP per minute.+const wsConnectCounts = new Map<string, { count: number; resetAt: number }>();+const WS_RATE_LIMIT = 20;+const WS_RATE_WINDOW_MS = 60_000;++function wsRateLimitExceeded(ip: string): boolean {+ const now = Date.now();+ let entry = wsConnectCounts.get(ip);+ if (!entry || now > entry.resetAt) {+ entry = { count: 0, resetAt: now + WS_RATE_WINDOW_MS };+ wsConnectCounts.set(ip, entry);+ }+ entry.count += 1;+ return entry.count > WS_RATE_LIMIT;+}+wss.on('connection', (ws, req) => {+ const ip = (req.headers['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim()+ || req.socket.remoteAddress+ || 'unknown';+ if (wsRateLimitExceeded(ip)) {+ ws.close(1008, 'Rate limit exceeded');+ return;+ }const url = new URL(req.url || '/', `http://localhost`);const tenantId = url.searchParams.get('tenant_id') || 'default';const channel: Channel = (ws as any)._aisocChannel ?? 'all';@@ -114,8 +137,31 @@ function broadcastToTenant(tenantId: string, message: { type: string } & Record<}}+// Simple IP-based rate limiter for SSE: max 20 connections per IP per minute.+const sseConnectCounts = new Map<string, { count: number; resetAt: number }>();+const SSE_RATE_LIMIT = 20;+const SSE_RATE_WINDOW_MS = 60_000;++function sseRateLimitExceeded(ip: string): boolean {+ const now = Date.now();+ let entry = sseConnectCounts.get(ip);+ if (!entry || now > entry.resetAt) {+ entry = { count: 0, resetAt: now + SSE_RATE_WINDOW_MS };+ sseConnectCounts.set(ip, entry);+ }+ entry.count += 1;+ return entry.count > SSE_RATE_LIMIT;+}+// --- SSE endpoint ---app.get('/sse', (req, res) => {+ const ip = (req.headers['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim()+ || req.socket.remoteAddress+ || 'unknown';+ if (sseRateLimitExceeded(ip)) {+ res.status(429).json({ error: 'Rate limit exceeded' });+ return;+ }const tenantId = (req.query.tenant_id as string) || 'default';res.setHeader('Content-Type', 'text/event-stream');diff --git a/services/threatintel/app/storage/qdrant.py b/services/threatintel/app/storage/qdrant.pyindex b63be82d0..fa6a3fc17 100644--- a/services/threatintel/app/storage/qdrant.py+++ b/services/threatintel/app/storage/qdrant.py@@ -6,6 +6,7 @@ AiSOC — open-source AI Security Operations Center (MIT License)from __future__ import annotations+import hashlibfrom typing import Anyimport structlog@@ -56,18 +57,7 @@ class QdrantStore:texts = [self._ioc_to_text(ioc) for ioc in iocs]vectors = await self._embed(texts)- points = [- PointStruct(- id=i,- vector=vectors[i],- payload=iocs[i],- )- for i in range(len(iocs))- ]-- # Qdrant expects integer IDs — use hash of value+type for stable IDs- import hashlib-+ # Use hash of value+type for stable integer IDspoints = [PointStruct(id=abs(int(hashlib.md5(f"{ioc['type']}:{ioc['value']}".encode()).hexdigest(), 16)) % (2**63),diff --git a/services/ueba/app/main.py b/services/ueba/app/main.pyindex fbd105a10..e9f6e5e78 100644--- a/services/ueba/app/main.py+++ b/services/ueba/app/main.py@@ -85,7 +85,7 @@ async def _stop_kafka() -> None:try:await _consumer_taskexcept asyncio.CancelledError:- pass+ pass # expected after cancel(); task is doneLOG.info("UEBA service stopped.")diff --git a/services/ueba/app/services/kafka_consumer.py b/services/ueba/app/services/kafka_consumer.pyindex 50323ecd0..088a2ab4c 100644--- a/services/ueba/app/services/kafka_consumer.py+++ b/services/ueba/app/services/kafka_consumer.py@@ -83,7 +83,7 @@ class UEBAKafkaConsumer:try:features[k] = float(v)except (TypeError, ValueError):- pass+ pass # non-numeric feature value; skipif not features:returndiff --git a/tools/detection_import/import_orchestrator.py b/tools/detection_import/import_orchestrator.pyindex 44d958906..7ac1a3001 100644--- a/tools/detection_import/import_orchestrator.py+++ b/tools/detection_import/import_orchestrator.py@@ -67,22 +67,22 @@ SOURCES: list[Source] = [Source(name="sigmahq",commit=SIGMA_COMMIT,- runner=lambda commit: sigma_importer.import_rules(commit),+ runner=sigma_importer.import_rules,),Source(name="car",commit=CAR_COMMIT,- runner=lambda commit: car_importer.import_rules(commit),+ runner=car_importer.import_rules,),Source(name="splunk",commit=SPLUNK_COMMIT,- runner=lambda commit: splunk_importer.import_rules(commit),+ runner=splunk_importer.import_rules,),Source(name="chronicle",commit=CHRONICLE_COMMIT,- runner=lambda commit: chronicle_importer.import_rules(commit),+ runner=chronicle_importer.import_rules,),]