Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(cli): add aisoc submit command + lateral-movement fixture (#111)

Beenu Arora7c5f77df1e5f
diff --git a/examples/alerts/lateral-movement.json b/examples/alerts/lateral-movement.json
new file mode 100644
index 000000000..f90acc68f
--- /dev/null
+++ b/examples/alerts/lateral-movement.json
@@ -0,0 +1,85 @@
+{
+ "_description": "Two-event lateral-movement scenario in Okta System Log format. The same user ([email protected]) successfully authenticates from a New York corp IP at 09:30 UTC, then from a Saint Petersburg IP eight minutes later. Routes through the okta_system_log connector profile (OCSF class_uid 3002, Authentication) when posted to /v1/ingest/batch.",
+ "_usage": "aisoc submit examples/alerts/lateral-movement.json",
+ "events": [
+ {
+ "uuid": "11111111-1111-4111-8111-111111111111",
+ "published": "2026-05-14T09:30:14.123Z",
+ "eventType": "user.session.start",
+ "displayMessage": "User login to Okta",
+ "severity": "INFO",
+ "actor": {
+ "id": "00u1abc23xYZdEfgHi45",
+ "type": "User",
+ "alternateId": "[email protected]",
+ "displayName": "Alice Carter"
+ },
+ "client": {
+ "ipAddress": "203.0.113.42",
+ "userAgent": {
+ "rawUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/537.36",
+ "os": "Mac OS X",
+ "browser": "CHROME"
+ },
+ "device": "Computer",
+ "geographicalContext": {
+ "city": "New York",
+ "state": "New York",
+ "country": "United States",
+ "geolocation": {"lat": 40.7128, "lon": -74.006}
+ }
+ },
+ "outcome": {
+ "result": "SUCCESS",
+ "reason": "User authenticated"
+ },
+ "transaction": {"id": "txn-lat-mov-001"},
+ "authenticationContext": {
+ "authenticationProvider": "FACTOR_PROVIDER",
+ "credentialType": "PASSWORD"
+ }
+ },
+ {
+ "uuid": "22222222-2222-4222-8222-222222222222",
+ "published": "2026-05-14T09:38:02.987Z",
+ "eventType": "user.session.start",
+ "displayMessage": "User login to Okta",
+ "severity": "WARN",
+ "actor": {
+ "id": "00u1abc23xYZdEfgHi45",
+ "type": "User",
+ "alternateId": "[email protected]",
+ "displayName": "Alice Carter"
+ },
+ "client": {
+ "ipAddress": "185.220.101.7",
+ "userAgent": {
+ "rawUserAgent": "Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/126.0",
+ "os": "Linux",
+ "browser": "FIREFOX"
+ },
+ "device": "Unknown",
+ "geographicalContext": {
+ "city": "Saint Petersburg",
+ "country": "Russia",
+ "geolocation": {"lat": 59.9343, "lon": 30.3351}
+ }
+ },
+ "outcome": {
+ "result": "SUCCESS",
+ "reason": "User authenticated"
+ },
+ "transaction": {"id": "txn-lat-mov-002"},
+ "authenticationContext": {
+ "authenticationProvider": "FACTOR_PROVIDER",
+ "credentialType": "PASSWORD"
+ },
+ "debugContext": {
+ "debugData": {
+ "risk": "HIGH",
+ "behaviors": "New Geo-Location=POSITIVE, New IP=POSITIVE, Velocity=POSITIVE"
+ }
+ }
+ }
+ ]
+}
diff --git a/packages/aisoc-cli/src/aisoc_cli/main.py b/packages/aisoc-cli/src/aisoc_cli/main.py
index 0bf1a0ada..a460407e1 100644
--- a/packages/aisoc-cli/src/aisoc_cli/main.py
+++ b/packages/aisoc-cli/src/aisoc_cli/main.py
@@ -12,6 +12,7 @@ Commands:
aisoc db upgrade Run database migrations against the dev stack
aisoc mcp serve [--transport] Launch the MCP server for IDE assistants
aisoc mcp install --host <h> Wire AiSOC into Claude / Cursor / Continue
+ aisoc submit <file> POST an alert/event JSON payload to the ingest API
"""
from __future__ import annotations
@@ -703,5 +704,222 @@ def mcp_install(host: str) -> None:
sys.exit(result.returncode)
+# ── submit command ───────────────────────────────────────────────────────────
+#
+# `aisoc submit <file>` lets the founder-flow demo and any operator land a
+# canned OCSF/Okta-shaped payload on the local dev stack in one command.
+# It POSTs to the Go ingest service's batch endpoint with the same envelope
+# the real connectors use (see services/connectors/app/ingest_client.py):
+#
+# POST {ingest_url}/v1/ingest/batch
+# X-Tenant-ID: <uuid>
+# { connector_id, connector_type, source_format, events: [...] }
+#
+# The fixture format is intentionally forgiving — the file may be:
+# * { "events": [...], "connector_id": ..., "connector_type": ..., "source_format": ... }
+# * a bare JSON list of event dicts
+# * a single event dict (auto-wrapped)
+# Any keys present in a dict-shaped fixture override the matching CLI flags,
+# so a fixture can pin its own connector identity without operator flags.
+
+_DEFAULT_INGEST_URL = "http://127.0.0.1:8081"
+_DEFAULT_TENANT_ID = "00000000-0000-0000-0000-000000000001"
+_DEFAULT_CONNECTOR_ID = "aisoc-cli-submit"
+_DEFAULT_CONNECTOR_TYPE = "okta_system_log"
+_DEFAULT_SOURCE_FORMAT = "json"
+
+
+def _coerce_events(payload: Any) -> tuple[list[dict[str, Any]], dict[str, str]]:
+ """Normalize a parsed JSON payload into (events, fixture_overrides).
+
+ Returns the event list plus any connector_id / connector_type /
+ source_format overrides that a dict-shaped fixture wants to pin.
+ """
+ overrides: dict[str, str] = {}
+ if isinstance(payload, list):
+ events = payload
+ elif isinstance(payload, dict):
+ if "events" in payload and isinstance(payload["events"], list):
+ events = payload["events"]
+ for key in ("connector_id", "connector_type", "source_format"):
+ value = payload.get(key)
+ if isinstance(value, str) and value:
+ overrides[key] = value
+ else:
+ events = [payload]
+ else:
+ raise click.ClickException(
+ "Payload must be a JSON object, a list of events, "
+ "or an object with an 'events' list."
+ )
+
+ cleaned: list[dict[str, Any]] = []
+ for idx, event in enumerate(events):
+ if not isinstance(event, dict):
+ raise click.ClickException(
+ f"Event at index {idx} is not a JSON object (got {type(event).__name__})."
+ )
+ cleaned.append(event)
+
+ if not cleaned:
+ raise click.ClickException("No events to submit — the payload is empty.")
+
+ return cleaned, overrides
+
+
+ "file",
+ type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
+)
+ "--ingest-url",
+ envvar="AISOC_INGEST_URL",
+ default=_DEFAULT_INGEST_URL,
+ show_default=True,
+ help="Base URL for the ingest service (e.g. http://127.0.0.1:8081).",
+)
+ "--tenant-id",
+ envvar="AISOC_TENANT_ID",
+ default=_DEFAULT_TENANT_ID,
+ show_default=True,
+ help="Tenant UUID sent in the X-Tenant-ID header.",
+)
+ "--connector-id",
+ default=_DEFAULT_CONNECTOR_ID,
+ show_default=True,
+ help="connector_id field in the ingest envelope.",
+)
+ "--connector-type",
+ default=_DEFAULT_CONNECTOR_TYPE,
+ show_default=True,
+ help="connector_type field — chooses the normalizer profile (e.g. okta_system_log).",
+)
+ "--source-format",
+ default=_DEFAULT_SOURCE_FORMAT,
+ show_default=True,
+ help="source_format hint for the normalizer.",
+)
+ "--timeout",
+ type=float,
+ default=30.0,
+ show_default=True,
+ help="HTTP timeout in seconds.",
+)
+def submit(
+ file: Path,
+ ingest_url: str,
+ tenant_id: str,
+ connector_id: str,
+ connector_type: str,
+ source_format: str,
+ timeout: float,
+) -> None:
+ """Submit a JSON alert/event payload to the local ingest service.
+
+ Reads ``FILE``, normalizes it into the ingest batch envelope, and POSTs to
+ ``{ingest_url}/v1/ingest/batch`` with the tenant header. Used by the
+ quickstart video script to drop a lateral-movement alert into the stack
+ in one command.
+ """
+ try:
+ raw = file.read_text(encoding="utf-8")
+ except OSError as exc: # pragma: no cover - click handles `exists=True`
+ raise click.ClickException(f"Could not read {file}: {exc}") from exc
+
+ # Strip a leading BOM, which `json.loads` otherwise refuses.
+ if raw.startswith("\ufeff"):
+ raw = raw.lstrip("\ufeff")
+
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise click.ClickException(f"{file} is not valid JSON: {exc}") from exc
+
+ events, overrides = _coerce_events(payload)
+ connector_id = overrides.get("connector_id", connector_id)
+ connector_type = overrides.get("connector_type", connector_type)
+ source_format = overrides.get("source_format", source_format)
+
+ url = f"{ingest_url.rstrip('/')}/v1/ingest/batch"
+ body = {
+ "connector_id": connector_id,
+ "connector_type": connector_type,
+ "source_format": source_format,
+ "events": events,
+ }
+
+ console.print(
+ Panel(
+ f"[bold]file:[/bold] {file}\n"
+ f"[bold]url:[/bold] {url}\n"
+ f"[bold]tenant:[/bold] {tenant_id}\n"
+ f"[bold]connector_id:[/bold] {connector_id}\n"
+ f"[bold]connector_type:[/bold] {connector_type}\n"
+ f"[bold]source_format:[/bold] {source_format}\n"
+ f"[bold]events:[/bold] {len(events)}",
+ title="[bold green]aisoc submit[/bold green]",
+ )
+ )
+
+ headers = {
+ "Content-Type": "application/json",
+ "X-Tenant-ID": tenant_id,
+ }
+
+ try:
+ with httpx.Client(timeout=timeout) as client:
+ resp = client.post(url, headers=headers, json=body)
+ except httpx.HTTPError as exc:
+ console.print(
+ f"[red]Ingest service unreachable at {url}:[/red] {exc}\n"
+ "Is the dev stack running? Try [bold]aisoc serve[/bold] first."
+ )
+ sys.exit(1)
+
+ if resp.status_code >= 400:
+ console.print(
+ f"[red]Ingest service returned {resp.status_code}:[/red] {resp.text[:500]}"
+ )
+ sys.exit(1)
+
+ try:
+ data = resp.json()
+ except ValueError:
+ console.print(
+ f"[red]Ingest service returned non-JSON ({resp.status_code}):[/red] "
+ f"{resp.text[:200]}"
+ )
+ sys.exit(1)
+
+ accepted = data.get("accepted", 0)
+ rejected = data.get("rejected", 0)
+ request_id = data.get("request_id", "-")
+ errors = data.get("errors") or []
+
+ console.print(
+ Panel(
+ f"[bold]status:[/bold] {resp.status_code}\n"
+ f"[bold]accepted:[/bold] {accepted}\n"
+ f"[bold]rejected:[/bold] {rejected}\n"
+ f"[bold]request_id:[/bold] {request_id}",
+ title="[bold green]ingest response[/bold green]",
+ )
+ )
+
+ if errors:
+ console.print("[yellow]errors:[/yellow]")
+ for err in errors:
+ console.print(f" • {err}")
+
+ if rejected and not accepted:
+ sys.exit(1)
+
+
if __name__ == "__main__":
cli()
diff --git a/packages/aisoc-cli/tests/test_submit_command.py b/packages/aisoc-cli/tests/test_submit_command.py
new file mode 100644
index 000000000..7428e86da
--- /dev/null
+++ b/packages/aisoc-cli/tests/test_submit_command.py
@@ -0,0 +1,347 @@
+"""CLI surface tests for ``aisoc submit``.
+
+These tests pin the contract the founder-flow quickstart relies on:
+
+* ``aisoc submit <file>`` is registered and discoverable via ``--help``.
+* The CLI POSTs to ``{ingest_url}/v1/ingest/batch`` with an ``X-Tenant-ID``
+ header and the canonical ingest envelope shape (connector_id,
+ connector_type, source_format, events).
+* Fixture-level overrides (a file with ``connector_id`` / ``connector_type``
+ / ``source_format`` keys) win over the matching CLI flags.
+* The CLI surfaces accepted / rejected counts on success, and exits non-zero
+ on transport errors, 4xx responses, or non-JSON responses.
+
+We use ``httpx.MockTransport`` to intercept the HTTP call without standing
+up a real ingest service. If these tests break, the quickstart video will
+desync from the CLI.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+from click.testing import CliRunner
+
+from aisoc_cli import main as cli_main
+from aisoc_cli.main import cli
+
+
+def runner() -> CliRunner:
+ return CliRunner()
+
+
+def _write_fixture(tmp_path: Path, payload: Any, name: str = "alert.json") -> Path:
+ path = tmp_path / name
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return path
+
+
+class _CapturingTransport(httpx.MockTransport):
+ """Mock transport that records each request and returns a canned response."""
+
+ def __init__(self, response_factory):
+ self.requests: list[httpx.Request] = []
+ super().__init__(self._handler)
+ self._response_factory = response_factory
+
+ def _handler(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ return self._response_factory(request)
+
+
+def _install_transport(
+ monkeypatch: pytest.MonkeyPatch,
+ response_factory,
+) -> _CapturingTransport:
+ """Patch ``httpx.Client`` so the CLI uses the mock transport."""
+ transport = _CapturingTransport(response_factory)
+ real_client = httpx.Client
+
+ def _client_factory(*args, **kwargs):
+ kwargs["transport"] = transport
+ return real_client(*args, **kwargs)
+
+ monkeypatch.setattr(cli_main.httpx, "Client", _client_factory)
+ return transport
+
+
+def test_submit_help_lists_command(runner: CliRunner) -> None:
+ result = runner.invoke(cli, ["--help"])
+ assert result.exit_code == 0, result.output
+ assert "submit" in result.output
+
+
+def test_submit_help_shows_options(runner: CliRunner) -> None:
+ result = runner.invoke(cli, ["submit", "--help"])
+ assert result.exit_code == 0, result.output
+ for flag in ("--ingest-url", "--tenant-id", "--connector-id", "--connector-type", "--source-format"):
+ assert flag in result.output
+
+
+def test_submit_posts_envelope_with_tenant_header(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(
+ tmp_path,
+ {
+ "events": [
+ {"uuid": "abc", "eventType": "user.session.start"},
+ {"uuid": "def", "eventType": "user.session.start"},
+ ]
+ },
+ )
+
+ def respond(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={"accepted": 2, "rejected": 0, "request_id": "req-001"},
+ )
+
+ transport = _install_transport(monkeypatch, respond)
+
+ result = runner.invoke(
+ cli,
+ ["submit", str(fixture_path), "--ingest-url", "http://localhost:8081"],
+ )
+ assert result.exit_code == 0, result.output
+ assert len(transport.requests) == 1
+
+ req = transport.requests[0]
+ assert req.method == "POST"
+ assert str(req.url) == "http://localhost:8081/v1/ingest/batch"
+ assert req.headers["X-Tenant-ID"] == "00000000-0000-0000-0000-000000000001"
+ assert req.headers["Content-Type"].startswith("application/json")
+
+ body = json.loads(req.content.decode("utf-8"))
+ assert body["connector_id"] == "aisoc-cli-submit"
+ assert body["connector_type"] == "okta_system_log"
+ assert body["source_format"] == "json"
+ assert len(body["events"]) == 2
+
+ assert "accepted: 2" in result.output
+ assert "request_id: req-001" in result.output
+
+
+def test_submit_accepts_bare_list_payload(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, [{"uuid": "1"}, {"uuid": "2"}])
+
+ transport = _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(200, json={"accepted": 2, "rejected": 0}),
+ )
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code == 0, result.output
+ body = json.loads(transport.requests[0].content.decode("utf-8"))
+ assert len(body["events"]) == 2
+
+
+def test_submit_wraps_single_object_payload(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"uuid": "only"})
+
+ transport = _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(200, json={"accepted": 1, "rejected": 0}),
+ )
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code == 0, result.output
+ body = json.loads(transport.requests[0].content.decode("utf-8"))
+ assert body["events"] == [{"uuid": "only"}]
+
+
+def test_submit_fixture_overrides_beat_cli_flags(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(
+ tmp_path,
+ {
+ "connector_id": "fixture-conn",
+ "connector_type": "splunk_enterprise",
+ "source_format": "raw_json",
+ "events": [{"uuid": "x"}],
+ },
+ )
+
+ transport = _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(200, json={"accepted": 1, "rejected": 0}),
+ )
+
+ result = runner.invoke(
+ cli,
+ [
+ "submit",
+ str(fixture_path),
+ "--connector-id",
+ "cli-conn",
+ "--connector-type",
+ "okta_system_log",
+ "--source-format",
+ "json",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ body = json.loads(transport.requests[0].content.decode("utf-8"))
+ assert body["connector_id"] == "fixture-conn"
+ assert body["connector_type"] == "splunk_enterprise"
+ assert body["source_format"] == "raw_json"
+
+
+def test_submit_uses_cli_flags_when_fixture_has_no_overrides(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"events": [{"uuid": "x"}]})
+
+ transport = _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(200, json={"accepted": 1, "rejected": 0}),
+ )
+
+ result = runner.invoke(
+ cli,
+ [
+ "submit",
+ str(fixture_path),
+ "--tenant-id",
+ "deadbeef-0000-4000-8000-000000000000",
+ "--connector-id",
+ "demo-cli",
+ "--connector-type",
+ "okta_system_log",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ req = transport.requests[0]
+ assert req.headers["X-Tenant-ID"] == "deadbeef-0000-4000-8000-000000000000"
+ body = json.loads(req.content.decode("utf-8"))
+ assert body["connector_id"] == "demo-cli"
+
+
+def test_submit_env_overrides_default_url_and_tenant(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"events": [{"uuid": "x"}]})
+ monkeypatch.setenv("AISOC_INGEST_URL", "http://ingest-worker:8080")
+ monkeypatch.setenv("AISOC_TENANT_ID", "11111111-1111-4111-8111-111111111111")
+
+ transport = _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(200, json={"accepted": 1, "rejected": 0}),
+ )
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code == 0, result.output
+ req = transport.requests[0]
+ assert str(req.url) == "http://ingest-worker:8080/v1/ingest/batch"
+ assert req.headers["X-Tenant-ID"] == "11111111-1111-4111-8111-111111111111"
+
+
+def test_submit_returns_nonzero_on_4xx(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"events": [{"uuid": "x"}]})
+ _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(400, text="missing X-Tenant-ID"),
+ )
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code == 1, result.output
+ assert "Ingest service returned 400" in result.output
+
+
+def test_submit_returns_nonzero_on_transport_error(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"events": [{"uuid": "x"}]})
+
+ def boom(_: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("connection refused")
+
+ _install_transport(monkeypatch, boom)
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code == 1, result.output
+ assert "Ingest service unreachable" in result.output
+ assert "aisoc serve" in result.output
+
+
+def test_submit_rejects_invalid_json(
+ runner: CliRunner,
+ tmp_path: Path,
+) -> None:
+ bad = tmp_path / "broken.json"
+ bad.write_text("{ not json", encoding="utf-8")
+
+ result = runner.invoke(cli, ["submit", str(bad)])
+ assert result.exit_code != 0, result.output
+ assert "not valid JSON" in result.output
+
+
+def test_submit_rejects_empty_event_list(
+ runner: CliRunner,
+ tmp_path: Path,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"events": []})
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code != 0, result.output
+ assert "empty" in result.output.lower()
+
+
+def test_submit_rejects_non_object_event(
+ runner: CliRunner,
+ tmp_path: Path,
+) -> None:
+ fixture_path = _write_fixture(tmp_path, {"events": ["just-a-string"]})
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code != 0, result.output
+ assert "not a JSON object" in result.output
+
+
+def test_submit_real_lateral_movement_fixture(
+ runner: CliRunner,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Smoke-test the actual repo fixture so the demo path stays wired up."""
+ repo_root = Path(__file__).resolve().parents[3]
+ fixture_path = repo_root / "examples" / "alerts" / "lateral-movement.json"
+ if not fixture_path.exists():
+ pytest.skip("lateral-movement fixture is created in this PR; run from repo root")
+
+ transport = _install_transport(
+ monkeypatch,
+ lambda _: httpx.Response(200, json={"accepted": 2, "rejected": 0, "request_id": "req-9"}),
+ )
+
+ result = runner.invoke(cli, ["submit", str(fixture_path)])
+ assert result.exit_code == 0, result.output
+ body = json.loads(transport.requests[0].content.decode("utf-8"))
+ assert len(body["events"]) == 2
+ assert body["events"][0]["actor"]["alternateId"] == "[email protected]"