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.

test(ai-estate): live Postgres suite with two negative controls, wired into CI

Beenu Arorac78d90c7174b
diff --git a/.github/workflows/ai-estate-live.yml b/.github/workflows/ai-estate-live.yml
new file mode 100644
index 000000000..46a2ae26d
--- /dev/null
+++ b/.github/workflows/ai-estate-live.yml
@@ -0,0 +1,142 @@
+# The AI inventory, written and read against a real PostgreSQL.
+#
+# Why a live database and not a double
+# ------------------------------------
+# Three of the properties this item depends on are properties of PostgreSQL,
+# not of the Python, and a fake connection answers for none of them:
+#
+# * `UNIQUE NULLS NOT DISTINCT` is what makes a provider key — which has no
+# device — coalesce onto one row. Under the default NULL semantics every
+# sighting inserts a new row and `first_seen_at` resets each time, so the
+# inventory grows without bound and loses the one fact it exists to keep.
+# Measured: reverting that one clause turns one row into three.
+# * `LEAST`/`GREATEST` on conflict are what stop a replayed Kafka batch
+# moving `first_seen_at` forward.
+# * The row-level security policy is what stops one tenant reading
+# another's AI estate, and it only applies when the connection is the
+# DML-only `aisoc_app` role. A superuser walks past every policy even
+# under FORCE ROW LEVEL SECURITY, which would make the isolation
+# assertion pass for the wrong reason.
+#
+# No `paths:` filter. A path filter on a live job is how a gate comes to
+# report success without running: the job must be unconditional on a push and
+# on a pull request, so a change anywhere that breaks the inventory is graded.
+name: AI estate (live)
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+
+concurrency:
+ group: ai-estate-live-${{ github.ref }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ ai-estate-live:
+ name: The observed AI estate survives a real database
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+
+ services:
+ postgres:
+ image: public.ecr.aws/docker/library/postgres:16-alpine
+ env:
+ POSTGRES_USER: aisoc
+ POSTGRES_PASSWORD: aisoc_ci_only
+ POSTGRES_DB: aisoc
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U aisoc"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 20
+
+ env:
+ AI_ESTATE_DSN: postgresql://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc
+ PGPASSWORD: aisoc_ci_only
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6
+ with:
+ python-version: "3.11"
+
+ - name: Install what the fusion recorder needs
+ run: |
+ python -m pip install --quiet --upgrade pip
+ python -m pip install --quiet asyncpg structlog pytest "pytest-asyncio>=1.0,<2.0" \
+ "pydantic>=2,<3" pydantic-settings
+
+ # Every migration, in order, rather than the one that creates the
+ # table. A cherry-picked subset builds a schema no deployment has —
+ # `current_tenant_id()` and the `aisoc_app` role both come from earlier
+ # migrations, and without them the RLS assertions would pass vacuously.
+ - name: Apply every migration, in order
+ run: |
+ for f in services/api/migrations/*.sql; do
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"
+ done
+
+ - name: Give the runtime role its password
+ run: |
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \
+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \
+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"
+
+ - name: A fixture estate of three kinds, written and read back
+ env:
+ ISOLATION_AI_ESTATE_DSN: ${{ env.AI_ESTATE_DSN }}
+ run: python -m pytest tests/isolation/test_ai_estate_live.py -v --tb=short
+
+ # Negative control one. Reverting `NULLS NOT DISTINCT` to PostgreSQL's
+ # default NULL semantics is the real defect, not an invented one: the
+ # deviceless kinds are provider keys and OAuth grants, which are
+ # exactly the rows an AI-governance review reads.
+ #
+ # Measured here: three rows for one key, each claiming to be first seen
+ # now.
+ - name: The suite fails when the identity constraint loses NULLS NOT DISTINCT
+ env:
+ ISOLATION_AI_ESTATE_DSN: ${{ env.AI_ESTATE_DSN }}
+ run: |
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q \
+ -c "ALTER TABLE aisoc_ai_assets DROP CONSTRAINT aisoc_ai_assets_identity;" \
+ -c "ALTER TABLE aisoc_ai_assets ADD CONSTRAINT aisoc_ai_assets_identity UNIQUE (tenant_id, kind, external_id, device);"
+ if python -m pytest tests/isolation/test_ai_estate_live.py -q >/dev/null 2>&1; then
+ echo "FAIL: the suite passed with the default NULL semantics, so it is not"
+ echo " measuring the constraint it claims to measure."
+ exit 1
+ fi
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q \
+ -c "ALTER TABLE aisoc_ai_assets DROP CONSTRAINT aisoc_ai_assets_identity;" \
+ -c "ALTER TABLE aisoc_ai_assets ADD CONSTRAINT aisoc_ai_assets_identity UNIQUE NULLS NOT DISTINCT (tenant_id, kind, external_id, device);"
+ echo "OK: removing NULLS NOT DISTINCT fails the suite, as it must."
+
+ # Negative control two, on the other property a double cannot see.
+ - name: The suite fails when the tenant policy stops comparing tenants
+ env:
+ ISOLATION_AI_ESTATE_DSN: ${{ env.AI_ESTATE_DSN }}
+ run: |
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q \
+ -c "DROP POLICY aisoc_ai_assets_tenant ON aisoc_ai_assets;" \
+ -c "CREATE POLICY aisoc_ai_assets_tenant ON aisoc_ai_assets USING (true);"
+ if python -m pytest tests/isolation/test_ai_estate_live.py -q >/dev/null 2>&1; then
+ echo "FAIL: one tenant could read another's AI estate and the suite passed."
+ exit 1
+ fi
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q \
+ -c "DROP POLICY aisoc_ai_assets_tenant ON aisoc_ai_assets;" \
+ -c "CREATE POLICY aisoc_ai_assets_tenant ON aisoc_ai_assets USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);"
+ echo "OK: weakening the policy fails the suite, as it must."
+
+ - name: Green again on the restored schema
+ env:
+ ISOLATION_AI_ESTATE_DSN: ${{ env.AI_ESTATE_DSN }}
+ run: python -m pytest tests/isolation/test_ai_estate_live.py -q
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 84f8a2a4a..d3dcbceac 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -701,6 +701,19 @@ jobs:
run: python3 scripts/check_cloud_native_collection.py --self-test
- name: Cloud-native collection gate
run: python3 scripts/check_cloud_native_collection.py
+ # Depth 6.1. The AI estate is a stored value a console page reads, and
+ # the failure that costs most here is not an absent feature but a
+ # present one nothing writes: the page renders "no AI estate" to a
+ # tenant that has one, which is the single most dangerous false
+ # statement it could make. The WRITER rule is therefore the
+ # load-bearing one — it requires the fusion consumer to call the
+ # recorder on the raw-events branch *and* the service to construct it
+ # at startup, because an unconstructed recorder is a None that every
+ # call site skips in silence.
+ - name: AI asset inventory gate — self-test
+ run: python3 scripts/check_ai_asset_inventory.py --self-test
+ - name: AI asset inventory gate
+ run: python3 scripts/check_ai_asset_inventory.py
# One layer in from the name: the profile gate asks whether a connector
# reaches a normalization path, this asks which OCSF class it reaches
# when it gets there. The class uid divided by a thousand is the
diff --git a/tests/isolation/test_ai_estate_live.py b/tests/isolation/test_ai_estate_live.py
new file mode 100644
index 000000000..915e57b9e
--- /dev/null
+++ b/tests/isolation/test_ai_estate_live.py
@@ -0,0 +1,251 @@
+"""The AI inventory, written and read against a real PostgreSQL.
+
+Depth plan 6.1's "Done when": *a fixture estate with one coding agent, one
+MCP server and one provider key shows all three on the inventory page, linked
+to the right person and device.*
+
+Why this needs a live database rather than a double
+---------------------------------------------------
+Everything load-bearing here is a property of PostgreSQL rather than of the
+Python:
+
+* ``UNIQUE NULLS NOT DISTINCT`` is the reason a provider key — which has no
+ device — coalesces onto one row instead of inserting one per sighting.
+ Under the default NULL semantics every sighting is a new row and the
+ inventory grows without bound while ``first_seen_at`` resets each time. A
+ fake connection answers neither way.
+* ``LEAST``/``GREATEST`` on conflict are what stop a replayed Kafka batch
+ moving ``first_seen_at`` forward.
+* The RLS policy is what stops one tenant reading another's estate, and it
+ only applies when the connection is the DML-only ``aisoc_app`` role: a
+ superuser walks past every policy even under ``FORCE ROW LEVEL SECURITY``.
+
+The suite connects as ``aisoc_app`` for exactly that reason.
+
+Run it with ``ISOLATION_AI_ESTATE_DSN`` pointing at a migrated database. It
+is a hard failure, never a skip, when the variable is set — a live suite that
+skips is a green check over nothing.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+import uuid
+from pathlib import Path
+from typing import Any
+
+import asyncpg
+import pytest
+import pytest_asyncio
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(REPO_ROOT / "services" / "fusion"))
+
+DSN = os.environ.get("ISOLATION_AI_ESTATE_DSN")
+
+pytestmark = [
+ pytest.mark.skipif(not DSN, reason="ISOLATION_AI_ESTATE_DSN is not set"),
+ pytest.mark.asyncio,
+]
+
+TENANT_A = "aaaaaaaa-0000-0000-0000-00000000000a"
+TENANT_B = "bbbbbbbb-0000-0000-0000-00000000000b"
+
+
+def _recorder_module():
+ """Import the real recorder, not a reimplementation of it."""
+ from app.services import ai_asset_recorder
+
+ return ai_asset_recorder
+
+
+def coding_agent_event(tenant: str) -> dict[str, Any]:
+ """An `ai-runtime` span, placed per `templates/ai-runtime.yaml`."""
+ return {
+ "tenant_id": tenant,
+ "ocsf_event": {
+ "class_uid": 6003,
+ "source_type": "ai-runtime",
+ "activity_name": "search_siem",
+ "actor": {
+ "process": {"name": "agent-7f2", "path": "/usr/local/bin/claude"},
+ "user": {"name": "[email protected]"},
+ },
+ "src_endpoint": {"hostname": "ada-mbp"},
+ "metadata": {"product": {"name": "AI Runtime", "feature": {"name": "claude-sonnet-4"}}},
+ "cloud": {"provider": "anthropic"},
+ "resource": {"name": "github-mcp"},
+ },
+ }
+
+
+def provider_key_event(tenant: str) -> dict[str, Any]:
+ """An OpenAI organization audit record, as `llm_usage` normalizes it."""
+ return {
+ "tenant_id": tenant,
+ "ocsf_event": {
+ "class_uid": 3001,
+ "source_type": "llm_usage",
+ "activity_name": "openai.api_key.created",
+ "actor": {"user": {"name": "[email protected]"}},
+ "metadata": {"product": {"vendor_name": "OpenAI", "name": "AI / LLM Usage Audit"}},
+ "finding": {"uid": "key_abc123"},
+ },
+ }
+
+
+class _Pool:
+ """A real asyncpg pool, opened per test and closed after it."""
+
+ def __init__(self, pool: Any) -> None:
+ self._pool = pool
+
+ def acquire(self): # noqa: ANN201
+ return self._pool.acquire()
+
+
+async def _connect(dsn: str) -> Any:
+ return await asyncpg.create_pool(dsn, min_size=1, max_size=2)
+
+
+async def _seed_tenants(pool: Any) -> None:
+ async with pool.acquire() as conn:
+ for tenant, slug in ((TENANT_A, "iso-ai-a"), (TENANT_B, "iso-ai-b")):
+ await conn.execute(
+ "INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING",
+ uuid.UUID(tenant),
+ f"AI estate {slug}",
+ slug,
+ )
+
+
+async def _clear(pool: Any) -> None:
+ async with pool.acquire() as conn:
+ await conn.execute("DELETE FROM aisoc_ai_assets WHERE tenant_id = ANY($1::uuid[])", [uuid.UUID(TENANT_A), uuid.UUID(TENANT_B)])
+
+
+@pytest_asyncio.fixture
+async def pool(): # noqa: ANN201
+ assert DSN, "ISOLATION_AI_ESTATE_DSN must be set"
+ raw = await _connect(DSN)
+ await _seed_tenants(raw)
+ await _clear(raw)
+ try:
+ yield raw
+ finally:
+ await _clear(raw)
+ await raw.close()
+
+
+async def _rows(pool: Any, tenant: str) -> list[dict[str, Any]]:
+ """Read the inventory the way the console route reads it."""
+ async with pool.acquire() as conn:
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, false)", tenant)
+ records = await conn.fetch(
+ "SELECT kind, external_id, display_name, vendor, discovery_source, principal, device, "
+ "risk_score, first_seen_at, last_seen_at, observation_count "
+ "FROM aisoc_ai_assets WHERE tenant_id = $1::uuid ORDER BY kind",
+ tenant,
+ )
+ return [dict(r) for r in records]
+
+
+async def test_fixture_estate_shows_all_three_kinds_linked(pool):
+ """The plan's own acceptance condition, end to end."""
+ mod = _recorder_module()
+ recorder = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await recorder.observe(coding_agent_event(TENANT_A))
+ await recorder.observe(provider_key_event(TENANT_A))
+ written = await recorder.flush()
+ assert written == 3, "expected a coding agent, an MCP server and a provider key"
+
+ rows = await _rows(pool, TENANT_A)
+ by_kind = {r["kind"]: r for r in rows}
+ assert set(by_kind) == {"coding_agent", "mcp_server", "provider_key"}
+
+ agent = by_kind["coding_agent"]
+ assert agent["principal"] == "[email protected]"
+ assert agent["device"] == "ada-mbp"
+ assert agent["vendor"] == "Anthropic"
+
+ server = by_kind["mcp_server"]
+ assert server["external_id"] == "github-mcp"
+ assert server["device"] == "ada-mbp"
+
+ key = by_kind["provider_key"]
+ assert key["external_id"] == "key_abc123"
+ assert key["principal"] == "[email protected]"
+ # Not "no device": the provider's audit log carries none, and the row
+ # says so through its discovery source rather than through a blank.
+ assert key["device"] is None
+ assert key["discovery_source"] == "provider_audit"
+
+
+async def test_a_deviceless_asset_coalesces_instead_of_multiplying(pool):
+ """`UNIQUE NULLS NOT DISTINCT`, which is the whole reason it is named.
+
+ Under PostgreSQL's default NULL semantics this asserts the defect: three
+ rows for one key, each claiming to be first seen now.
+ """
+ mod = _recorder_module()
+ for _ in range(3):
+ recorder = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await recorder.observe(provider_key_event(TENANT_A))
+ await recorder.flush()
+
+ rows = [r for r in await _rows(pool, TENANT_A) if r["kind"] == "provider_key"]
+ assert len(rows) == 1, f"expected one row for one key, got {len(rows)}"
+ assert rows[0]["observation_count"] == 3
+
+
+async def test_a_replayed_batch_cannot_move_first_seen_forward(pool):
+ """LEAST/GREATEST on conflict, against a real timestamp comparison."""
+ mod = _recorder_module()
+ recorder = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await recorder.observe(coding_agent_event(TENANT_A))
+ await recorder.flush()
+ first = [r for r in await _rows(pool, TENANT_A) if r["kind"] == "coding_agent"][0]
+
+ await asyncio.sleep(0.05)
+ again = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await again.observe(coding_agent_event(TENANT_A))
+ await again.flush()
+ second = [r for r in await _rows(pool, TENANT_A) if r["kind"] == "coding_agent"][0]
+
+ assert second["first_seen_at"] == first["first_seen_at"], "a replay moved first_seen_at"
+ assert second["last_seen_at"] >= first["last_seen_at"]
+ assert second["observation_count"] == 2
+
+
+async def test_a_later_anonymous_sighting_does_not_erase_the_person(pool):
+ """COALESCE in the UPDATE, proven against the real statement."""
+ mod = _recorder_module()
+ recorder = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await recorder.observe(coding_agent_event(TENANT_A))
+ await recorder.flush()
+
+ anonymous = coding_agent_event(TENANT_A)
+ anonymous["ocsf_event"]["actor"].pop("user")
+ later = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await later.observe(anonymous)
+ await later.flush()
+
+ agent = [r for r in await _rows(pool, TENANT_A) if r["kind"] == "coding_agent"][0]
+ assert agent["principal"] == "[email protected]"
+
+
+async def test_one_tenant_cannot_read_anothers_ai_estate(pool):
+ """Row-level security, as the DML-only runtime role sees it."""
+ mod = _recorder_module()
+ recorder = mod.AiAssetRecorder(lambda: _Pool(pool))
+ await recorder.observe(coding_agent_event(TENANT_A))
+ await recorder.observe(coding_agent_event(TENANT_B))
+ await recorder.flush()
+
+ async with pool.acquire() as conn:
+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, false)", TENANT_A)
+ visible = await conn.fetch("SELECT tenant_id FROM aisoc_ai_assets")
+ assert visible, "tenant A sees nothing at all, so this proves no isolation"
+ assert {str(r["tenant_id"]) for r in visible} == {TENANT_A}