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.

The full profile could not come up, and three checks said it had (#828)

Beenu Aroraee73df6d22f1
diff --git a/Makefile b/Makefile
index 69184f0a2..e14a5716f 100644
--- a/Makefile
+++ b/Makefile
@@ -94,10 +94,22 @@ bootstrap:
# The lake and graph writers target stores that exist only in `full`, so the
# flags travel with the profile. In CORE they default off rather than
# retrying forever against a host that is not there.
-up-full:
+#
+# `_ports` runs here for the same reason it runs for `up`, more so: this
+# starts twenty-one services, so the bind failure compose reports arrives
+# even later and against even more unrelated output. Observed: a conflict on
+# 8123 stopped the stack after eight containers had already started, with
+# `Bind for 0.0.0.0:8123 failed: port is already allocated` naming neither the
+# process holding it nor what to do.
+up-full: _ports
AISOC_LAKE_WRITER_ENABLED=true AISOC_GRAPH_ENABLED=true $(COMPOSE) --profile full up -d
- @$(MAKE) --no-print-directory _wait
- @echo "Full profile up. Prove the pipeline works: make smoke"
+ @$(MAKE) --no-print-directory _wait PROFILE=full
+ @echo ""
+ @echo " Console: http://localhost:3000"
+ @echo " API: http://localhost:8000/api/docs"
+ @echo ""
+ @echo "Prove the pipeline works: make smoke"
+ @$(MAKE) --no-print-directory bootstrap
# Names a port conflict before compose hits it. Silent when every port is
# either free or already held by this deployment's own containers — re-running
@@ -112,14 +124,31 @@ _ports:
exit 1; \
}
-# Waits on the services that declare a healthcheck. Silent on success.
+# Waits on the services that declare a healthcheck, and refuses to call a
+# stack up while any container is dead.
+#
+# The old loop read `ps` without `-a` and looked only at Health. An *exited*
+# container is absent from that listing entirely and a *restarting* one
+# reports no health, so both were invisible: `make up-full` printed
+# "Full profile up." with OpenSearch OOM-killed and threatintel in a crash
+# loop. A container that is not running is the one thing a wait loop must
+# never score as success.
_wait:
@for i in $$(seq 1 60); do \
- unhealthy=$$($(COMPOSE) ps --format '{{.Service}} {{.Health}}' 2>/dev/null | awk '$$2=="starting"||$$2=="unhealthy"{print $$1}'); \
- [ -z "$$unhealthy" ] && exit 0; \
+ status=$$($(COMPOSE) $(PROFILE_ARG) ps -a --format '{{.Service}} {{.State}} {{.Health}}' 2>/dev/null); \
+ pending=$$(echo "$$status" | awk '$$3=="starting"{print $$1}'); \
+ broken=$$(echo "$$status" | awk '$$2=="exited"||$$2=="dead"||$$2=="restarting"||$$3=="unhealthy"{print $$1}'); \
+ if [ -n "$$broken" ]; then \
+ echo ""; \
+ echo "These services are not running: $$broken"; \
+ for s in $$broken; do echo " docker compose logs $$s | tail -30"; done; \
+ echo "Run 'make doctor' for the full picture."; \
+ exit 1; \
+ fi; \
+ [ -z "$$pending" ] && exit 0; \
sleep 3; \
done; \
- echo "Still not healthy after 3 minutes: $$unhealthy"; \
+ echo "Still not healthy after 3 minutes: $$pending"; \
echo "Run 'make doctor' to find out why."; \
exit 1
diff --git a/apps/web/src/app/(app)/purple-team/page.tsx b/apps/web/src/app/(app)/purple-team/page.tsx
index 512b42c3c..cd1893649 100644
--- a/apps/web/src/app/(app)/purple-team/page.tsx
+++ b/apps/web/src/app/(app)/purple-team/page.tsx
@@ -237,13 +237,26 @@ function CoverageHeatmap() {
}
}
- const resolved = data ?? MOCK_COVERAGE
+ // `fallbackData` above withholds MOCK_COVERAGE outside the hosted demo.
+ // Naming the constant again here put it back: with the purple-team service
+ // absent — it is an `extras`-profile service, so it is not running in
+ // `core` or `full` — the page rendered an invented ATT&CK matrix with
+ // per-technique test and detection counts as the tenant's own coverage.
+ // Zeroed rather than absent: `summary` is required by CoverageMatrix and is
+ // dereferenced unguarded below, and "0 of 0 techniques, 0% coverage" is the
+ // truthful reading when the service has told us nothing.
+ const EMPTY_COVERAGE: CoverageMatrix = {
+ tactics: [],
+ techniques: {},
+ summary: { total_techniques: 0, tested_techniques: 0, detected_techniques: 0, overall_coverage: 0 },
+ }
+ const resolved = data ?? EMPTY_COVERAGE
const {
summary: rawSummary,
- tactics = MOCK_COVERAGE.tactics,
- techniques = MOCK_COVERAGE.techniques,
+ tactics = EMPTY_COVERAGE.tactics,
+ techniques = EMPTY_COVERAGE.techniques,
} = resolved
- const summary = rawSummary ?? MOCK_COVERAGE.summary
+ const summary = rawSummary ?? EMPTY_COVERAGE.summary
// Index drift status by technique_id for O(1) lookup while rendering cells.
const driftByTid = new Map<string, DriftTechnique>()
diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsx
index 8f27bb486..7adca068a 100644
--- a/apps/web/src/components/cases/CasesView.tsx
+++ b/apps/web/src/components/cases/CasesView.tsx
@@ -175,7 +175,9 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {
return true;
});
- const allCases = casesData?.cases ?? MOCK_CASES;
+ // The list above already falls back to `[]`; this counted MOCK_CASES, so a
+ // failed request rendered an empty table under stat cards claiming 18 cases.
+ const allCases = casesData?.cases ?? [];
const statCounts = {
all: allCases.length,
open: allCases.filter(c => c.status === 'open').length,
diff --git a/apps/web/src/components/threat-intel/ThreatIntelView.tsx b/apps/web/src/components/threat-intel/ThreatIntelView.tsx
index d13202552..3d2eeb5dc 100644
--- a/apps/web/src/components/threat-intel/ThreatIntelView.tsx
+++ b/apps/web/src/components/threat-intel/ThreatIntelView.tsx
@@ -239,7 +239,11 @@ export function ThreatIntelView() {
{ fallbackData: demoFallback({ indicators: MOCK_INDICATORS, total: MOCK_INDICATORS.length }) },
);
- const allIndicators = data?.indicators ?? MOCK_INDICATORS;
+ // Not `?? MOCK_INDICATORS`. `fallbackData` above already withholds the
+ // sample set outside the hosted demo; repeating the constant here put it
+ // back, so a 404 from the indicators API rendered five invented IOCs and a
+ // "3 Added Today" counter on a tenant that had never ingested one.
+ const allIndicators = data?.indicators ?? [];
const indicators = allIndicators.filter((ioc) => {
if (typeFilter !== 'all' && ioc.type !== typeFilter) return false;
diff --git a/docker-compose.override.yml b/docker-compose.override.yml
new file mode 100644
index 000000000..15c88f10e
--- /dev/null
+++ b/docker-compose.override.yml
@@ -0,0 +1,12 @@
+# QA-only host port remap (untracked, never committed). Another stack on this
+# machine already publishes 5432, 8123 and 9000. Container ports are unchanged,
+# so service-to-service traffic over the compose network is identical to the
+# documented deployment; only the host-side bindings move.
+services:
+ postgres:
+ ports: !override
+ - "127.0.0.1:55432:5432"
+ clickhouse:
+ ports: !override
+ - "127.0.0.1:58123:8123"
+ - "127.0.0.1:59000:9000"
diff --git a/docker-compose.yml b/docker-compose.yml
index 8293437e7..7d12268bf 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -226,8 +226,25 @@ services:
- "127.0.0.1:9200:9200"
networks:
- aisoc
- mem_limit: 1g
- mem_reservation: 768m
+ healthcheck:
+ # Without this the only condition a dependant can express is
+ # `service_started`, which is true the instant the container exists —
+ # including for the ~40s before the node listens, and for a node that
+ # is about to die. threatintel aborts its lifespan when this port does
+ # not answer, so it needs the stronger condition.
+ test: ["CMD-SHELL", "curl -fsS http://localhost:9200/_cluster/health || exit 1"]
+ interval: 10s
+ timeout: 5s
+ retries: 12
+ start_period: 60s
+ # A 512m heap is not a 512m process. OpenSearch 2.11 loads ~20 bundled
+ # plugins (knn, ml, security-analytics, performance-analyzer) and settles
+ # at ~1.05GB RSS with this heap — measured, steady-state, single node,
+ # no indices. At `mem_limit: 1g` it was OOM-killed during bootstrap every
+ # time (exit 137, OOMKilled=true, ~10s in), so the full profile shipped a
+ # store that could never start.
+ mem_limit: 2g
+ mem_reservation: 1g
qdrant:
# full profile — Vector store for threat-intel embeddings (services/threatintel).
@@ -299,13 +316,32 @@ services:
AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}
REDIS_URL: redis://:redis_dev_secret@redis:6379/0
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
- CLICKHOUSE_URL: http://aisoc:clickhouse_dev_secret@clickhouse:8123/aisoc
+ # The lake client reads these five, not CLICKHOUSE_URL — nothing under
+ # services/api/app reads that name at all. Supplying only the URL left
+ # the settings at their defaults (localhost:9000, user `default`, no
+ # password), so /lake/sql answered every query with
+ # `Connection refused (localhost:9000)` while fusion archived to the
+ # same store perfectly well over the native port.
+ CLICKHOUSE_HOST: clickhouse
+ CLICKHOUSE_PORT: 9000
+ CLICKHOUSE_DATABASE: aisoc
+ CLICKHOUSE_USER: aisoc
+ CLICKHOUSE_PASSWORD: clickhouse_dev_secret
OPENSEARCH_URL: http://opensearch:9200
QDRANT_URL: http://qdrant:6333
+ # The API owns the vault write path; the connectors service reads with
+ # the same key. Passing it to one and not the other means a credential
+ # saved in the console can never be decrypted at poll time.
+ AISOC_CREDENTIAL_KEY: ${AISOC_CREDENTIAL_KEY:-}
+ AISOC_CREDENTIAL_KEY_ROTATION_FROM: ${AISOC_CREDENTIAL_KEY_ROTATION_FROM:-}
NEO4J_URI: bolt://neo4j:7687
NEO4J_USER: neo4j
NEO4J_PASSWORD: neo4j_dev_secret
- SECRET_KEY: dev_secret_key_change_in_production
+ # Was a bare literal, so a SECRET_KEY set in .env was ignored and the
+ # JWT signing key silently stayed on the dev default. It also has to
+ # match whatever the connectors service verifies with, or the console
+ # token the API forwards there fails its signature check.
+ SECRET_KEY: ${SECRET_KEY:-dev_secret_key_change_in_production}
ENVIRONMENT: development
LOG_LEVEL: info
# Issue #478 — LiteLLM gateway. Route this service's live LLM endpoints
@@ -624,10 +660,29 @@ services:
# profile-gated). It idles harmlessly with no configured instances; a cold
# `up` therefore ships the full ingest→detect→respond spine out of the box.
environment:
+ # app/scripts/serve.py binds PORT, defaulting to 8087. The mapping above
+ # publishes container port 8003, so leaving PORT unset put the listener
+ # on a port nothing forwards to: `connectors:8003` was refused from
+ # inside the network and the published host port answered nothing.
+ PORT: 8003
+ # Without one of these the tenant-scope dependency fails closed and
+ # every route answers 503, including the catalog the API proxies — so
+ # the console silently fell back to the 26-entry catalog bundled in the
+ # API image instead of the 84 connectors the registry actually has.
+ SECRET_KEY: ${SECRET_KEY:-dev_secret_key_change_in_production}
+ AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:-}
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
REDIS_URL: redis://:redis_dev_secret@redis:6379/6
DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc
CORE_API_URL: http://api:8000
+ # The scheduler decrypts stored connector credentials through the vault
+ # and refuses to start without this key. .env.example documents it as
+ # one of the three required values, but no compose service forwarded it,
+ # so setting it had no effect and every deployment lost the scheduler to
+ # `connector.scheduler.start_failed` — while the container still
+ # reported itself started.
+ AISOC_CREDENTIAL_KEY: ${AISOC_CREDENTIAL_KEY:-}
+ AISOC_CREDENTIAL_KEY_ROTATION_FROM: ${AISOC_CREDENTIAL_KEY_ROTATION_FROM:-}
CROWDSTRIKE_CLIENT_ID: ${CROWDSTRIKE_CLIENT_ID:-}
CROWDSTRIKE_CLIENT_SECRET: ${CROWDSTRIKE_CLIENT_SECRET:-}
AWS_REGION: ${AWS_REGION:-us-east-1}
@@ -654,9 +709,10 @@ services:
# OpenSearch is a hard dependency, not an optional one: the lifespan
# calls os_store.initialize() without a try/except, so starting before
# it is up kills the container and leaves `restart: unless-stopped` to
- # paper over the race.
+ # paper over the race. `service_healthy` is the condition that actually
+ # expresses that; `service_started` only says the container exists.
opensearch:
- condition: service_started
+ condition: service_healthy
ports:
- "127.0.0.1:8005:8005"
environment:
diff --git a/scripts/check_mock_data_gated.py b/scripts/check_mock_data_gated.py
index 2d0ebcd52..47f39e1e5 100644
--- a/scripts/check_mock_data_gated.py
+++ b/scripts/check_mock_data_gated.py
@@ -86,6 +86,38 @@ MOCK_ASSIGN = re.compile(rf"\bset[A-Z]\w*\(\s*{MOCK_NAME}")
#: dispatched") whenever no run was selected.
MOCK_FACTORY_ASSIGN = re.compile(r"\bset[A-Z]\w*\(\s*(?:make|build|get|create)(?:Mock|Demo|Sample|Fake|Fallback)\w*\(")
+#: Sample data reached through a nullish/OR fallback at the point of *render*,
+#: e.g. `const rows = data?.items ?? MOCK_ROWS;`.
+#:
+#: This is the shape the three patterns above cannot see, because the file can
+#: be correctly gated at the SWR boundary and still bypass it one line later.
+#: `ThreatIntelView.tsx` did exactly that: line 239 passed
+#: `fallbackData: demoFallback({ indicators: MOCK_INDICATORS })` — which the
+#: gate accepted, correctly — and line 242 then read
+#: `data?.indicators ?? MOCK_INDICATORS`. With demo mode off and the API
+#: returning 404, `data` is undefined and the mock renders anyway: five
+#: invented IOCs (a "Tor exit node with ransomware C2", a LockBit payload
+#: hash) under the counters "5 Total IOCs · 4 Malicious · 3 Added Today", on a
+#: deployment where no indicator had ever been ingested. Observed live; this
+#: gate reported "All sample-data fallbacks are gated behind demo mode."
+MOCK_RENDER_FALLBACK = re.compile(rf"(?:\?\?|\|\|)\s*{MOCK_NAME}\b")
+
+#: Sites where the fallback is UI configuration rather than a tenant's data.
+#: Keyed by `(path suffix, constant)` with the reason it is not a finding.
+#: Kept deliberately small: this gate's value depends on it staying quiet on
+#: the filter lists and option sets that make up most module-scope arrays in
+#: this console, and a gate that flags those gets switched off.
+RENDER_FALLBACK_EXEMPT: dict[tuple[str, str], str] = {
+ (
+ "identity/permissions/EffectivePermissionsView.tsx",
+ "DEMO_PROVIDERS",
+ ): "the provider capability list (aws/azure/gcp/gws/okta + coverage tier), not tenant data",
+ (
+ "identity/permissions/EffectivePermissionsView.tsx",
+ "DEMO_RESULT",
+ ): "supplies the default value of the principal input, not a rendered result",
+}
+
#: Files exempt by nature: the gate helper itself, tests, and stories.
EXEMPT_SUFFIXES = (".test.ts", ".test.tsx", ".stories.tsx", "demoFallback.ts")
@@ -160,6 +192,14 @@ DEMO_GATE = re.compile(r"demoFallback|canUseDemoData|isDemoMode")
ALLOWED_ILLUSTRATIVE: dict[tuple[str, str], str] = {}
+def _render_fallback_exempt(rel_path: str, matched: str) -> bool:
+ """True when this `?? MOCK_*` site is documented UI configuration."""
+ return any(
+ rel_path.endswith(suffix) and const in matched
+ for (suffix, const) in RENDER_FALLBACK_EXEMPT
+ )
+
+
def _array_body(lines: list[str], start: int) -> str:
"""Lines from `start` to the bracket that closes the array."""
depth = 0
@@ -235,6 +275,15 @@ def scan(root: pathlib.Path) -> list[str]:
f"check in this file. Show an error or empty state instead."
)
+ render_fallback = MOCK_RENDER_FALLBACK.search(line)
+ if render_fallback and not file_has_guard and not _render_fallback_exempt(str(rel), render_fallback.group(0)):
+ problems.append(
+ f"{rel}:{number}: sample data is reached through a `??`/`||` fallback with "
+ f"no canUseDemoData() check in this file. Gating the SWR fallbackData does "
+ f"not cover this — when the request fails the mock renders anyway. Fall back "
+ f"to an empty value and let the view show its error state."
+ )
+
if MOCK_FACTORY_ASSIGN.search(line) and not file_has_guard:
problems.append(
f"{rel}:{number}: a sample-data factory is assigned to state with no "
diff --git a/scripts/doctor.sh b/scripts/doctor.sh
index 5a9c60906..9cb65e331 100755
--- a/scripts/doctor.sh
+++ b/scripts/doctor.sh
@@ -253,12 +253,44 @@ fi
if [ "$PROFILE_FULL" = "1" ]; then
head2 "Full-profile stores"
+ # Probed over the published host port, the same way every other HTTP service
+ # in this script is checked. The previous spelling shelled into the container
+ # and ran `wget`, which answers "is wget installed" as much as "is the store
+ # up": the opensearch image ships curl and no wget, and the qdrant image
+ # ships neither. Both reported "running but did not answer" while serving
+ # 200 on every request — a false alarm on two of the four stores, which is
+ # worse than no check, because it teaches the operator to ignore this one.
+ store_probe() {
+ # $1 service, $2 container port, $3 path. Prints 200 or 000.
+ _sb_host_port="$(svc_published_port "$1" "$2" || true)"
+ if [ -n "${_sb_host_port:-}" ]; then
+ http_ok "http://localhost:${_sb_host_port}$3" 6
+ return
+ fi
+ # Not published on the host (a compose override may have dropped the
+ # mapping). Fall back to whichever client the image actually has.
+ dc_exec "$1" sh -c "
+ if command -v curl >/dev/null 2>&1; then
+ curl -fsS -m 3 -o /dev/null http://localhost:$2$3 && echo 200 || echo 000
+ elif command -v wget >/dev/null 2>&1; then
+ wget -qO- -T 3 http://localhost:$2$3 >/dev/null 2>&1 && echo 200 || echo 000
+ else
+ echo noclient
+ fi" || echo 000
+ }
+
for spec in "clickhouse 8123 /ping" "neo4j 7474 /" "qdrant 6333 /readyz" "opensearch 9200 /"; do
set -- $spec; name="$1"; port="$2"; path="$3"
if svc_running "$name"; then
- code="$(dc_exec "$name" sh -c "wget -qO- -T 3 http://localhost:${port}${path} >/dev/null 2>&1 && echo 200 || echo 000")"
- if [ "$code" = "200" ]; then pass "$name responding on $port"
- else warn "$name is running but did not answer http://localhost:${port}${path}" "docker compose logs $name | tail -20"; fi
+ code="$(store_probe "$name" "$port" "$path")"
+ case "$code" in
+ 200) pass "$name responding on $port" ;;
+ noclient)
+ warn "$name could not be probed: no host port published and the image has no curl or wget" \
+ "publish the port, or check it by hand: docker compose logs $name | tail -20" ;;
+ *) warn "$name is running but did not answer http://localhost:${port}${path}" \
+ "docker compose logs $name | tail -20" ;;
+ esac
else
warn "$name is not running (full profile)" "docker compose --profile full up -d $name"
fi
diff --git a/tests/test_full_profile_gate.py b/tests/test_full_profile_gate.py
new file mode 100644
index 000000000..07b936588
--- /dev/null
+++ b/tests/test_full_profile_gate.py
@@ -0,0 +1,247 @@
+"""Full-profile defects that every test suite passed and a real deployment did not.
+
+`tests/test_first_run_gate.py` covers the same genre for CORE. This file covers
+`make up-full`, which had never been brought up end to end by anyone: the
+acceptance pass that found these reported that `up-full` printed
+"Full profile up." while two of its twenty-one services were dead and a third
+was serving on a port nothing forwarded to.
+
+Every check below is a compose-manifest assertion, because every defect lived
+in the gap between a manifest and the code that reads it — an env var the
+service ignores, a memory limit smaller than the process, a published port the
+listener never binds. None of them is visible to a unit test of either side,
+and a container can report `running` through all of them.
+"""
+
+from __future__ import annotations
+
+import pathlib
+
+import pytest
+import yaml # type: ignore[import-untyped] # PyYAML ships no stubs; only used to read compose here
+
+REPO = pathlib.Path(__file__).resolve().parents[1]
+ROOT_COMPOSE = REPO / "docker-compose.yml"
+
+_MIB = 1024 * 1024
+
+
+def _compose() -> dict:
+ return yaml.safe_load(ROOT_COMPOSE.read_text())
+
+
+def _services() -> dict:
+ return _compose()["services"]
+
+
+def _env(service: dict) -> dict[str, str]:
+ """Normalise compose's two environment spellings to one mapping."""
+ raw = service.get("environment") or {}
+ if isinstance(raw, list):
+ out: dict[str, str] = {}
+ for item in raw:
+ key, _, value = str(item).partition("=")
+ out[key] = value
+ return out
+ return {k: "" if v is None else str(v) for k, v in raw.items()}
+
+
+def _to_bytes(limit: str | int | None) -> int | None:
+ """Parse a compose `mem_limit` (`2g`, `512m`, or a raw byte count)."""
+ if limit is None:
+ return None
+ if isinstance(limit, int):
+ return limit
+ text = str(limit).strip().lower()
+ for suffix, mult in (("g", 1024**3), ("m", 1024**2), ("k", 1024)):
+ if text.endswith(suffix):
+ return int(float(text[:-1]) * mult)
+ return int(text)
+
+
+def _published(service: dict) -> set[int]:
+ """Container-side ports this service publishes, in either port syntax."""
+ out: set[int] = set()
+ for entry in service.get("ports") or []:
+ if isinstance(entry, dict):
+ if entry.get("target") is not None:
+ out.add(int(entry["target"]))
+ continue
+ # "127.0.0.1:8088:8003" / "8088:8003" / "8003"
+ out.add(int(str(entry).strip('"').split(":")[-1]))
+ return out
+
+
+# ── OpenSearch: a 512m heap is not a 512m process ──────────────────────────
+#
+# Shipped as `mem_limit: 1g` with `-Xmx512m`. OpenSearch 2.11 loads ~20 bundled
+# plugins and settles at ~1.05GB RSS with that heap, so the container was
+# OOM-killed during bootstrap every single time (exit 137, OOMKilled=true,
+# ~10s in). The full profile shipped a store that could not start, and
+# `make up-full` reported success because its wait loop only inspects the
+# health of *running* containers — an exited one is absent from the listing
+# and a restarting one reports no health at all.
+def test_opensearch_memory_limit_exceeds_its_heap() -> None:
+ svc = _services()["opensearch"]
+ env = _env(svc)
+ opts = next(
+ (v for k, v in env.items() if k == "OPENSEARCH_JAVA_OPTS"),
+ " ".join(str(e) for e in (svc.get("environment") or []) if "JAVA_OPTS" in str(e)),
+ )
+ assert "-Xmx512m" in opts, (
+ "This bound assumes a 512m heap. If the heap changed, re-measure the "
+ "steady-state RSS and move the floor with it."
+ )
+
+ limit = _to_bytes(svc.get("mem_limit"))
+ assert limit is not None, "opensearch must declare a mem_limit"
+ assert limit >= 1800 * _MIB, (
+ f"opensearch mem_limit is {limit // _MIB}MiB. Measured steady state with "
+ "a 512m heap is ~1075MiB, so anything at or near 1GiB is OOM-killed at "
+ "boot. Keep real headroom above the measurement."
+ )
+
+
+# ── A dependant that needs readiness cannot express it without a healthcheck ─
+#
+# threatintel calls os_store.initialize() in its FastAPI lifespan with no
+# try/except, so starting before OpenSearch answers kills the container.
+# `condition: service_started` is satisfied the instant the container exists —
+# including for the ~40s before the node listens, and for a node about to die —
+# so the only honest condition is service_healthy, which needs a healthcheck on
+# the target.
+def test_service_healthy_dependencies_have_a_healthcheck_to_wait_on() -> None:
+ services = _services()
+ missing: list[str] = []
+ for name, svc in services.items():
+ depends = svc.get("depends_on") or {}
+ if not isinstance(depends, dict):
+ continue
+ for dep, spec in depends.items():
+ if not isinstance(spec, dict):
+ continue
+ if spec.get("condition") != "service_healthy":
+ continue
+ if not (services.get(dep) or {}).get("healthcheck"):
+ missing.append(f"{name} waits on {dep} being healthy, but {dep} declares no healthcheck")
+ assert not missing, "; ".join(missing)
+
+
+def test_threatintel_waits_for_a_ready_opensearch() -> None:
+ dep = (_services()["threatintel"].get("depends_on") or {}).get("opensearch")
+ assert isinstance(dep, dict) and dep.get("condition") == "service_healthy", (
+ "threatintel aborts its lifespan when OpenSearch does not answer, so "
+ "`service_started` leaves restart:unless-stopped to paper over a crash loop."
+ )
+
+
+# ── The API reads CLICKHOUSE_HOST, and nothing under services/api reads a URL ─
+#
+# The api service was handed `CLICKHOUSE_URL` alone. No module under
+# services/api/app reads that name, so the settings stayed at their defaults
+# (localhost:9000, user `default`, no password) and /lake/sql answered every
+# query with `Connection refused (localhost:9000)` — while fusion archived to
+# the same store perfectly well over the native port.
+CLICKHOUSE_SETTINGS = ("CLICKHOUSE_HOST", "CLICKHOUSE_PORT", "CLICKHOUSE_DATABASE", "CLICKHOUSE_USER", "CLICKHOUSE_PASSWORD")
+
+
+def test_api_receives_the_clickhouse_settings_its_code_actually_reads() -> None:
+ env = _env(_services()["api"])
+ missing = [k for k in CLICKHOUSE_SETTINGS if k not in env]
+ assert not missing, (
+ f"api is missing {missing}. app/core/config.py declares these five and no "
+ "module reads CLICKHOUSE_URL, so supplying only the URL silently leaves "
+ "the lake client pointed at localhost."
+ )
+
+
+def test_no_service_is_given_only_a_clickhouse_url() -> None:
+ """A service that gets CLICKHOUSE_URL and nothing else is a silent misconfiguration."""
+ for name, svc in _services().items():
+ env = _env(svc)
+ if "CLICKHOUSE_URL" not in env:
+ continue
+ if name == "ueba":
+ continue # reads CLICKHOUSE_URL directly; see services/ueba/app/core/config.py
+ assert "CLICKHOUSE_HOST" in env, (
+ f"{name} is given CLICKHOUSE_URL but no CLICKHOUSE_HOST. If it uses the "
+ "shared settings shape it will fall back to localhost and fail closed "
+ "with a connection error that names the wrong host."
+ )
+
+
+# ── A published port nothing binds ─────────────────────────────────────────
+#
+# connectors publishes container port 8003, but app/scripts/serve.py binds
+# `PORT`, defaulting to 8087. With PORT unset the listener sat on a port no
+# mapping forwarded to: `connectors:8003` was refused from inside the network,
+# the published host port answered nothing, and the API's catalog proxy fell
+# back to the 26-entry snapshot bundled in its image while the registry had 84.
+def test_connectors_binds_the_port_it_publishes() -> None:
+ svc = _services()["connectors"]
+ env = _env(svc)
+ assert "PORT" in env, (
+ "connectors/app/scripts/serve.py defaults PORT to 8087. Leaving it unset "
+ "binds a port the compose mapping does not forward to."
+ )
+ assert int(env["PORT"]) in _published(svc), (
+ f"connectors binds PORT={env['PORT']} but publishes {sorted(_published(svc))}."
+ )
+
+
+# ── A required key no service was given ────────────────────────────────────
+#
+# .env.example names AISOC_CREDENTIAL_KEY one of the three required values and
+# explains how to generate one, but no compose service forwarded it. Setting it
+# therefore had no effect: the connector scheduler raised CredentialVaultError
+# at startup, logged `connector.scheduler.start_failed`, and the container went
+# on to report `Application startup complete` and serve /health 200 with no
+# scheduler at all. No connector could ever auto-poll.
+def test_credential_vault_key_reaches_the_services_that_need_it() -> None:
+ services = _services()
+ for name in ("api", "connectors"):
+ env = _env(services[name])
+ assert "AISOC_CREDENTIAL_KEY" in env, (
+ f"{name} is not given AISOC_CREDENTIAL_KEY. The API owns the vault write "
+ "path and the connectors scheduler decrypts with the same key; a "
+ "credential saved in the console is undecryptable at poll time without it."
+ )
+
+
+# ── One signing key, honoured from .env ────────────────────────────────────
+#
+# api pinned SECRET_KEY to a bare literal, so a value set in .env was ignored
+# and the JWT signing key silently stayed on the dev default. It also has to
+# match whatever connectors verifies with: the API forwards the console token
+# there, and a mismatch turns every proxied catalog call into a 401 that the
+# caller reports as "connectors service unreachable".
+def test_secret_key_is_overridable_and_consistent_across_services() -> None:
+ services = _services()
+ keys = {}
+ for name in ("api", "connectors"):
+ env = _env(services[name])
+ assert "SECRET_KEY" in env, f"{name} must be given SECRET_KEY"
+ value = env["SECRET_KEY"]
+ assert value.startswith("${SECRET_KEY"), (
+ f"{name} pins SECRET_KEY to the literal {value!r}, so a value set in "
+ ".env is ignored."
+ )
+ keys[name] = value
+ assert len(set(keys.values())) == 1, (
+ f"api and connectors resolve different SECRET_KEY defaults ({keys}). The "
+ "console token the API forwards will fail its signature check."
+ )
+
+
[email protected]("service", ["clickhouse", "neo4j", "qdrant", "opensearch"])
+def test_full_profile_stores_are_reachable_over_a_published_port(service: str) -> None:
+ """scripts/doctor.sh probes these over the host port it resolves from compose.
+
+ The previous probe shelled into the container and ran `wget`, which answers
+ "is wget installed" as much as "is the store up" — the opensearch image
+ ships curl and no wget, the qdrant image ships neither, and both were
+ reported as not answering while serving 200 on every request.
+ """
+ assert _published(_services()[service]), (
+ f"{service} publishes no port, so the doctor cannot probe it from the host."
+ )
diff --git a/tests/test_mock_data_gate.py b/tests/test_mock_data_gate.py
index 468617b10..562e34ef4 100644
--- a/tests/test_mock_data_gate.py
+++ b/tests/test_mock_data_gate.py
@@ -83,6 +83,83 @@ def test_the_same_records_pass_once_demo_gated(tmp_path):
assert gate.scan(root) == []
+#: A file that gates its SWR fallback correctly and then bypasses the gate one
+#: line later. `ThreatIntelView.tsx` shipped this shape: with demo mode off and
+#: the indicators API returning 404, `data` is undefined and the `??` renders
+#: five invented IOCs under a "3 Added Today" counter, on a deployment that had
+#: never ingested one. The gate reported everything gated.
+GATED_THEN_BYPASSED = """\
+const MOCK_INDICATORS: ThreatIndicator[] = [
+ { id: 'ioc-001', type: 'ip', value: '185.220.101.45', confidence: 95 },
+];
+
+export function ThreatIntelView() {
+ const { data } = useSWR(
+ 'threat-intel-indicators',
+ () => threatIntelApi.list(),
+ { fallbackData: demoFallback({ indicators: MOCK_INDICATORS }) },
+ );
+ const allIndicators = data?.indicators ?? MOCK_INDICATORS;
+ return <IndicatorTable rows={allIndicators} />;
+}
+"""
+
+
+def test_a_gated_fallback_bypassed_at_render_is_caught(tmp_path):
+ root = _tree(tmp_path, "components/threat-intel/View.tsx", GATED_THEN_BYPASSED)
+ problems = gate.scan(root)
+ assert len(problems) == 1
+ assert "MOCK_INDICATORS" in (root / "components/threat-intel/View.tsx").read_text()
+ assert "`??`/`||` fallback" in problems[0]
+
+
+def test_the_three_older_patterns_alone_would_have_missed_the_bypass(tmp_path):
+ """Why the render-fallback check had to exist separately.
+
+ The `fallbackData:` line is correctly wrapped in `demoFallback(`, so the
+ first check passes it — as it should. Nothing is assigned through a setter.
+ The bypass is on a line none of the three shipped patterns describe.
+ """
+ root = _tree(tmp_path, "components/threat-intel/View.tsx", GATED_THEN_BYPASSED)
+ text = (root / "components/threat-intel/View.tsx").read_text(encoding="utf-8")
+ for line in text.split("\n"):
+ assert not (gate.FALLBACK_WITH_MOCK.search(line) and "demoFallback(" not in line)
+ assert not gate.MOCK_ASSIGN.search(line)
+ assert not gate.MOCK_FACTORY_ASSIGN.search(line)
+
+
+def test_an_empty_fallback_passes(tmp_path):
+ fixed = GATED_THEN_BYPASSED.replace(
+ "data?.indicators ?? MOCK_INDICATORS", "data?.indicators ?? []"
+ )
+ root = _tree(tmp_path, "components/threat-intel/View.tsx", fixed)
+ assert gate.scan(root) == []
+
+
+def test_a_demo_guarded_file_may_still_use_a_render_fallback(tmp_path):
+ guarded = GATED_THEN_BYPASSED.replace(
+ "data?.indicators ?? MOCK_INDICATORS",
+ "data?.indicators ?? (canUseDemoData() ? MOCK_INDICATORS : [])",
+ )
+ root = _tree(tmp_path, "components/threat-intel/View.tsx", guarded)
+ assert gate.scan(root) == []
+
+
+def test_documented_ui_configuration_is_exempt(tmp_path, monkeypatch):
+ """The exemption is keyed on file *and* constant, not the file alone."""
+ monkeypatch.setattr(
+ gate,
+ "RENDER_FALLBACK_EXEMPT",
+ {("identity/Perms.tsx", "DEMO_PROVIDERS"): "provider capability list, not tenant data"},
+ )
+ exempt = "const providers = info?.providers ?? DEMO_PROVIDERS;\n"
+ assert gate.scan(_tree(tmp_path, "identity/Perms.tsx", exempt)) == []
+
+ # A different constant in the same exempted file is still reported.
+ other = "const rows = data?.rows ?? MOCK_FINDINGS;\n"
+ assert len(gate.scan(_tree(tmp_path, "identity/Perms.tsx", other))) == 1
+
+
def test_named_people_with_scores_are_caught(tmp_path):
"""The second live instance: an analyst leaderboard with no backend."""
root = _tree(