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.

fix(deploy): stop a published credential from satisfying a production guard (#971)

Beenu Arora835aa046685d
diff --git a/.env.example b/.env.example
index 234da0391..2004bea71 100644
--- a/.env.example
+++ b/.env.example
@@ -141,8 +141,18 @@ CONNECTORS_SERVICE_TIMEOUT_SECONDS=15
# Both are interpolated by docker-compose.yml, so changing them here rotates
# them across the stack. They are deliberately different values: they are
# different privilege levels.
-POSTGRES_PASSWORD=aisoc_dev_secret
-AISOC_APP_DB_PASSWORD=aisoc_app_dev_secret
+#
+# Empty here and generated by `scripts/ensure_env.py`, like the six secrets
+# above. This file used to ship `POSTGRES_PASSWORD=aisoc_dev_secret`, and
+# `docker-compose.prod.yml` guarded it with
+# `${POSTGRES_PASSWORD:?… the development default is a published literal}` —
+# a guard that rejects an *empty* variable and cannot look at a value, so the
+# one input its message named was the one input it accepted. A production
+# stack booted on a password printed in this repository while the file said
+# it could not. `preflight-secrets` in that file now refuses the value, and
+# shipping these empty means a fresh install never has one to refuse.
+POSTGRES_PASSWORD=
+AISOC_APP_DB_PASSWORD=
# What every service connects as.
DATABASE_URL=postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD}@localhost:5432/aisoc
@@ -153,8 +163,14 @@ DATABASE_URL=postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD}@localhost:5
# ("permission denied for schema public") on one that has.
# aisoc-db-role: owner — the migration chain applies DDL; the runtime role holds none
DATABASE_MIGRATION_URL=postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD}@localhost:5432/aisoc
-REDIS_URL=redis://:redis_dev_secret@localhost:6379/0
-CLICKHOUSE_URL=http://aisoc:clickhouse_dev_secret@localhost:8123/aisoc
+
+# Generated alongside the Postgres pair, and referenced rather than repeated:
+# these two used to spell the password out inside the DSN, so rotating
+# REDIS_PASSWORD left a stale copy here that still worked.
+REDIS_PASSWORD=
+CLICKHOUSE_PASSWORD=
+REDIS_URL=redis://:${REDIS_PASSWORD}@localhost:6379/0
+CLICKHOUSE_URL=http://aisoc:${CLICKHOUSE_PASSWORD}@localhost:8123/aisoc
# ─── Messaging ────────────────────────────────────────────────────────────────
KAFKA_BOOTSTRAP_SERVERS=localhost:9092
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0d5d7fc0b..8df874a68 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -679,6 +679,17 @@ jobs:
run: |
python3 scripts/check_profile_service_counts.py --self-test
python3 scripts/check_profile_service_counts.py
+ # `docker-compose.prod.yml` states that nothing starts on a default
+ # credential and implements it with `${VAR:?…}`. Compose's `:?` rejects
+ # an unset or empty variable and cannot look at a value, so the guard
+ # whose message reads "the development default is a published literal"
+ # accepted `aisoc_dev_secret` — the literal `.env.example` shipped. The
+ # value check runs as a preflight service; this asserts every guard
+ # reaches it and that nothing starts ahead of it.
+ - name: No production guard can be satisfied by a published credential
+ run: |
+ python3 scripts/check_published_secrets.py --self-test
+ python3 scripts/check_published_secrets.py --check
# The marketplace index has to exist in three build contexts, none of
# which can see the other two. The API's copy was missing, so its image
# shipped no catalogue and the marketplace answered 503 on every
diff --git a/.github/workflows/compose-smoke.yml b/.github/workflows/compose-smoke.yml
index 3550479a9..562166fc0 100644
--- a/.github/workflows/compose-smoke.yml
+++ b/.github/workflows/compose-smoke.yml
@@ -95,7 +95,9 @@ jobs:
# now rather than duplicated across the two triggers it had.
paths=(
'docker-compose.yml'
+ 'docker-compose.prod.yml'
'infra/compose/docker-compose.demo.yml'
+ 'scripts/check_published_secrets.py'
'.env.example'
'.github/workflows/compose-smoke.yml'
'services/'
@@ -186,6 +188,47 @@ jobs:
if: steps.relevant.outputs.run == 'true'
run: docker compose config --quiet
+ # `docker-compose.prod.yml` shipped sixteen passing assertions about
+ # nothing starting on a default credential, and every one of them read
+ # the file rather than starting it. Compose's `${VAR:?}` rejects an
+ # unset or empty variable and cannot look at a value, so the guard
+ # reading "the development default is a published literal" accepted
+ # `aisoc_dev_secret`. This starts the stack, both ways, and asserts the
+ # exit status — a static read of the same file cannot tell the
+ # difference between these two runs.
+ - name: A published credential cannot start the production stack
+ if: steps.relevant.outputs.run == 'true'
+ env:
+ COMPOSE_PROJECT_NAME: aisoc-prodguard
+ run: |
+ set -euo pipefail
+ real() { openssl rand -hex 24; }
+ {
+ for name in POSTGRES_PASSWORD AISOC_APP_DB_PASSWORD REDIS_PASSWORD SECRET_KEY \
+ AISOC_CREDENTIAL_KEY AISOC_SERVICE_TOKEN AISOC_ACTIONS_SERVICE_TOKEN \
+ AISOC_REALTIME_JWT_SECRET REALTIME_INTERNAL_TOKEN METRICS_TOKEN \
+ JWT_SECRET NEO4J_PASSWORD CLICKHOUSE_PASSWORD GRAFANA_ADMIN_PASSWORD; do
+ printf '%s=%s\n' "$name" "$(real)"
+ done
+ printf 'AISOC_VERSION=%s\n' "${AISOC_VERSION}"
+ } > /tmp/prod-real.env
+ sed 's|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=aisoc_dev_secret|' /tmp/prod-real.env > /tmp/prod-published.env
+
+ echo "::group::published credential — must refuse"
+ if docker compose --env-file /tmp/prod-published.env -f docker-compose.yml -f docker-compose.prod.yml \
+ up --no-build --exit-code-from preflight-secrets preflight-secrets; then
+ echo "::error::the production stack started on aisoc_dev_secret"
+ exit 1
+ fi
+ docker compose --env-file /tmp/prod-published.env -f docker-compose.yml -f docker-compose.prod.yml down -v
+ echo "::endgroup::"
+
+ echo "::group::real credentials — must start"
+ docker compose --env-file /tmp/prod-real.env -f docker-compose.yml -f docker-compose.prod.yml \
+ up --no-build --exit-code-from preflight-secrets preflight-secrets
+ docker compose --env-file /tmp/prod-real.env -f docker-compose.yml -f docker-compose.prod.yml down -v
+ echo "::endgroup::"
+
- name: Detect build-context changes
id: dockerfile_changes
if: steps.relevant.outputs.run == 'true'
diff --git a/.gitleaksignore b/.gitleaksignore
index 71d77e5b8..726931424 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -113,3 +113,4 @@ services/connectors/tests/connectors/test_snowflake.py:private-key:17
# Kubernetes audit connector config fixture; "tok-abcdef-1234567890" is an
# invented inbox token for a schema assertion.
services/connectors/tests/test_kubernetes_audit.py:generic-api-key:218
+
diff --git a/apps/docs/docs/deployment/docker.md b/apps/docs/docs/deployment/docker.md
index 0f7f2446d..0a52e6b1f 100644
--- a/apps/docs/docs/deployment/docker.md
+++ b/apps/docs/docs/deployment/docker.md
@@ -118,12 +118,14 @@ COMPOSE_PROFILES=connectors,osquery,slack docker compose up -d
```bash
make env # generates the six service secrets
-docker compose -f docker-compose.prod.yml up -d
+docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
```
-The production file `include`s `docker-compose.yml` and overrides what
-production changes, so there is one definition of every service and the two
-cannot drift apart. It differs from the development stack in three ways that
+The production file is an overlay over `docker-compose.yml` and changes only
+what production changes, so there is one definition of every service and the
+two cannot drift apart. Both `-f` flags are required and the order matters —
+the overlay comes second. A single `-f docker-compose.prod.yml` resolves on
+Compose 5.x and fails on 2.x with `conflicts with imported resource`. It differs from the development stack in three ways that
matter:
- **The auth bypass is unreachable.** `ENVIRONMENT` and `AISOC_DEV_MODE` are
@@ -131,7 +133,12 @@ matter:
shim described above.
- **Nothing starts on a default credential.** Every secret is declared
`${VAR:?...}`, so Compose refuses to start and names the variable rather than
- booting on a literal published in this repository and looking healthy.
+ booting on nothing. Compose's `:?` rejects an *unset or empty* variable and
+ has no way to compare a value, so a `preflight-secrets` service runs ahead of
+ everything else and refuses the literals this repository publishes —
+ `aisoc_dev_secret`, `redis_dev_secret`, Grafana's `admin` and the rest. It
+ derives that list from the tree (`scripts/check_published_secrets.py`), so a
+ default added later is refused without anyone having to remember it.
- **Only the console and the ingest endpoint are reachable.** `web` on `:3000`
and `ingest-worker` on `:8081`, and nothing else — not the datastores, not
the internal services, not Prometheus or Grafana. The console proxies every
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.md
index d96933cbd..f49d7239d 100644
--- a/apps/docs/docs/deployment/env-vars.md
+++ b/apps/docs/docs/deployment/env-vars.md
@@ -40,6 +40,27 @@ The API uses bare environment variable names (no prefix). Booleans accept `true`
| `AISOC_SERVICE_TOKEN` | _empty_ | Shared bearer for service-to-service calls. The API **sends** it when proxying the connector catalog and "Test connection" to `services/connectors`, which **verifies** it — so a value set on one side only is a 401 the wizard reports as a failed connection test. `make env` generates one and compose passes it to both. |
| `AISOC_CONNECTORS_SERVICE_TOKEN` | _empty_ | Per-service override for the above, if you would rather not share one secret. |
| `AISOC_CONSOLE_URL` | `http://localhost:3000` | Base URL `make bootstrap` prints as the sign-in address. Set it to the address operators actually browse to — any non-localhost deployment otherwise prints the wrong one beside a credential shown exactly once. |
+| `POSTGRES_PASSWORD` | _empty_ | Postgres **owner** role. Owns every table and applies the migration chain; no service connects as it. `make env` generates one. |
+| `AISOC_APP_DB_PASSWORD` | _empty_ | Postgres **runtime** role (`aisoc_app`), DML only so the row-level-security policies apply to it. `make env` generates one. |
+| `REDIS_PASSWORD` | _empty_ | Redis AUTH password. `REDIS_URL` references it rather than repeating it, so rotating one rotates both. `make env` generates one. |
+| `CLICKHOUSE_PASSWORD` | _empty_ | ClickHouse event-lake password, referenced the same way by `CLICKHOUSE_URL`. `make env` generates one. |
+
+:::info A published default cannot satisfy a production guard
+
+The four datastore passwords above used to ship in `.env.example` as
+`aisoc_dev_secret`, `aisoc_app_dev_secret`, `redis_dev_secret` and
+`clickhouse_dev_secret`. `docker-compose.prod.yml` guarded each with
+`${VAR:?… the development default is a published literal}`, but Compose's `:?`
+rejects an **unset or empty** variable and cannot look at a value — so every
+one of those guards accepted the exact literal its own message named.
+
+They ship empty and generated now, and `docker-compose.prod.yml` runs a
+`preflight-secrets` service ahead of everything else that refuses any value
+published in this repository. An existing `.env` is not rewritten by
+`make env`, so a deployment that already holds one of these will be told at
+startup rather than silently keeping it.
+
+:::
### Migration runner
diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml
index 37a88c646..a1f450f93 100644
--- a/docker-compose.prod.yml
+++ b/docker-compose.prod.yml
@@ -1,6 +1,6 @@
# AiSOC — production compose.
#
-# docker compose -f docker-compose.prod.yml up -d
+# docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
#
# This is the file `apps/docs/docs/deployment/docker.md` has pointed at since
# the deployment page was written. It did not exist, which is what discussion
@@ -10,19 +10,32 @@
# `services/api/app/api/v1/dev_auth.py` resolves an unauthenticated request to
# a demo user whose role is `admin`.
#
-# It uses the Compose Spec `include` directive, the same way
-# `infra/compose/docker-compose.dev.yml` does, so there is exactly one
+# It is an overlay over `docker-compose.yml`, so there is exactly one
# definition of every service and this file holds only what production changes.
# A standalone copy would have drifted from the base within a release, which is
# the failure this repository keeps finding.
#
+# It was written with the Compose Spec `include` directive and a single `-f`,
+# which is how `infra/compose/docker-compose.dev.yml` pulls the base in. That
+# does not work here: `include` imports a model, and overriding a service it
+# imported is rejected with `services.<name> conflicts with imported resource`.
+# Measured rather than assumed — `-f docker-compose.prod.yml` alone fails on
+# Compose v2.29.7 and v2.39.4 and resolves only on 5.1.3, so the documented
+# production command worked on almost no installation. Two `-f` flags are the
+# ordinary override form and resolve identically on all three.
+#
# WHAT THIS FILE GUARANTEES
#
# * The authentication bypass is unreachable. `ENVIRONMENT` and `AISOC_DEV_MODE`
# are fixed values here, not interpolated, so no `.env` can re-enable them.
# * Nothing starts on a default credential. Every secret uses `${VAR:?...}`,
-# which makes Compose refuse to start and name the variable, rather than
-# booting on `aisoc_dev_secret` and looking healthy.
+# which makes Compose refuse to start and name the variable rather than
+# starting on nothing — and, because `:?` rejects an *empty* variable and
+# cannot look at a value, `preflight-secrets` below runs ahead of every
+# other service and refuses the literals this repository publishes. Until
+# it existed this bullet was false: `${POSTGRES_PASSWORD:?… the
+# development default is a published literal}` accepted `aisoc_dev_secret`,
+# which is what `.env.example` shipped.
# * No datastore is reachable from the host. Postgres, Redis, Kafka and
# Qdrant publish no ports at all; the console and the ingest endpoint are
# the only things bound, and they bind to loopback unless you set
@@ -35,10 +48,59 @@
# are not in a compose file. `docs/runbooks/HARDENING.md` is the checklist
# and this file is the starting posture, not the finished one.
-include:
- - ./docker-compose.yml
services:
+ # ---------------------------------------------------------------------------
+ # The value check `${VAR:?}` cannot do.
+ #
+ # Compose's `:?` operator rejects an unset or empty variable. It cannot look
+ # at a value, so `${POSTGRES_PASSWORD:?… the development default is a
+ # published literal}` accepted `aisoc_dev_secret` — the exact literal its own
+ # message names, shipped in `.env.example` and defaulted to in
+ # `docker-compose.yml`. Every guard below had the same hole, so the guarantee
+ # in this file's header held for none of them.
+ #
+ # This runs first and every other service waits for it to exit 0.
+ # `scripts/check_published_secrets.py` derives the refused values from the
+ # tree — the `${VAR:-literal}` defaults in the compose files, the non-empty
+ # values in `.env.example`, and INSECURE_SECRET_KEY_DEFAULTS — so a default
+ # added later is refused without anyone remembering to list it here.
+ #
+ # Every `${VAR:?}` variable in this file is repeated below. That is what
+ # gets it into the container's environment, and `--check` fails when a guard
+ # exists that the preflight never sees.
+ # ---------------------------------------------------------------------------
+ preflight-secrets:
+ image: ghcr.io/beenuar/aisoc-core-api:${AISOC_VERSION:-latest}
+ pull_policy: missing
+ container_name: aisoc-preflight-secrets
+ restart: "no"
+ entrypoint: ["python3", "/repo/scripts/check_published_secrets.py", "--check-env"]
+ # Read-only, and the whole tree rather than the four files the harvest
+ # happens to read today: a hand-listed mount is another list that stops
+ # matching the code, and the failure mode is the check quietly reading
+ # less than it thinks it does. `AISOC_REPO_ROOT` is how `gate_toolkit`
+ # is pointed at a tree without shelling out to git, which this image
+ # does not carry.
+ volumes:
+ - .:/repo:ro
+ environment:
+ AISOC_REPO_ROOT: /repo
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD — the development default is a published literal}
+ AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:?set AISOC_APP_DB_PASSWORD — the development default is a published literal}
+ REDIS_PASSWORD: ${REDIS_PASSWORD:?set REDIS_PASSWORD}
+ SECRET_KEY: ${SECRET_KEY:?set SECRET_KEY — run `make env` to generate it}
+ AISOC_CREDENTIAL_KEY: ${AISOC_CREDENTIAL_KEY:?set AISOC_CREDENTIAL_KEY — run `make env` to generate it}
+ AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:?set AISOC_SERVICE_TOKEN — run `make env` to generate it}
+ AISOC_ACTIONS_SERVICE_TOKEN: ${AISOC_ACTIONS_SERVICE_TOKEN:?set AISOC_ACTIONS_SERVICE_TOKEN — run `make env` to generate it}
+ AISOC_REALTIME_JWT_SECRET: ${AISOC_REALTIME_JWT_SECRET:?set AISOC_REALTIME_JWT_SECRET — run `make env` to generate it}
+ REALTIME_INTERNAL_TOKEN: ${REALTIME_INTERNAL_TOKEN:?set REALTIME_INTERNAL_TOKEN — run `make env` to generate it}
+ METRICS_TOKEN: ${METRICS_TOKEN:?set METRICS_TOKEN — guards /metrics outside development; `openssl rand -hex 32`}
+ JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET — signs SAML/OIDC sessions}
+ NEO4J_PASSWORD: ${NEO4J_PASSWORD:?set NEO4J_PASSWORD}
+ CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:?set CLICKHOUSE_PASSWORD}
+ GRAFANA_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?set GRAFANA_ADMIN_PASSWORD — required for the monitoring profile}
+
# ---------------------------------------------------------------------------
# Data plane. No published ports: in the development stack these are bound to
# 127.0.0.1 so a developer can attach a client, which is reasonable there and
@@ -46,6 +108,9 @@ services:
# appending to it.
# ---------------------------------------------------------------------------
postgres:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -56,18 +121,30 @@ services:
AISOC_APP_DB_PASSWORD: ${AISOC_APP_DB_PASSWORD:?set AISOC_APP_DB_PASSWORD — the development default is a published literal}
redis:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
zookeeper:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
kafka:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
qdrant:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
@@ -78,6 +155,9 @@ services:
# lives, which is the defect this file exists to make impossible.
# ---------------------------------------------------------------------------
api:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -123,6 +203,9 @@ services:
JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET — signs SAML/OIDC sessions; the same value ingest-worker takes below}
ingest-worker:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !override ["${AISOC_BIND_ADDR:-127.0.0.1}:8081:8080"]
restart: unless-stopped
environment:
@@ -139,6 +222,9 @@ services:
AISOC_NEO4J_PASSWORD: ${NEO4J_PASSWORD:?set NEO4J_PASSWORD}
fusion:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -148,6 +234,9 @@ services:
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:?set CLICKHOUSE_PASSWORD}
agents:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -158,6 +247,9 @@ services:
NEO4J_PASSWORD: ${NEO4J_PASSWORD:?set NEO4J_PASSWORD}
actions:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -169,6 +261,9 @@ services:
AISOC_ACTIONS_SERVICE_TOKEN: ${AISOC_ACTIONS_SERVICE_TOKEN:?set AISOC_ACTIONS_SERVICE_TOKEN}
connectors:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -179,6 +274,9 @@ services:
SECRET_KEY: ${SECRET_KEY:?set SECRET_KEY}
threatintel:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -187,6 +285,9 @@ services:
NEO4J_PASSWORD: ${NEO4J_PASSWORD:?set NEO4J_PASSWORD}
realtime:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
@@ -197,16 +298,34 @@ services:
REALTIME_INTERNAL_TOKEN: ${REALTIME_INTERNAL_TOKEN:?set REALTIME_INTERNAL_TOKEN — run `make env` to generate it}
litellm:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
ollama:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
+ # Declared here only to take the preflight dependency. It is the one service
+ # the base file defines that this overlay otherwise has nothing to say about,
+ # and a single service that starts ahead of the credential check is the hole
+ # the check exists to close.
+ ollama-pull:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
+
# The console. Demo mode is inlined at build time by Next, so this asserts
# the runtime side only; pull the `latest` tag rather than a `-demo` one.
web:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
restart: unless-stopped
environment:
NODE_ENV: production
@@ -220,18 +339,27 @@ services:
# on the services that dial them so the two cannot disagree.
# ---------------------------------------------------------------------------
neo4j:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
NEO4J_AUTH: neo4j/${NEO4J_PASSWORD:?set NEO4J_PASSWORD — required for the full profile}
clickhouse:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:?set CLICKHOUSE_PASSWORD — required for the full profile}
opensearch:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
@@ -240,6 +368,9 @@ services:
# so it is moved onto a profile nothing here activates: `--profile full` no
# longer starts it. An operator who wants it can still ask for it by name.
kafka-ui:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
profiles: !override ["debug-ui"]
ports: !reset []
# `no`, not `unless-stopped`: this is a tool you bring up to look at
@@ -257,37 +388,67 @@ services:
# for debugging, or publish one deliberately in a local override.
# ---------------------------------------------------------------------------
alertmanager:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
enrichment:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
honeytokens:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
osquery-tls:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
otel-collector:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
prometheus:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
purple-team:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
slack-bot:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
tempo:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
ueba:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
# HARDENING.md section 5 — observability and audit.
@@ -296,6 +457,9 @@ services:
# `--profile monitoring` cannot start a dashboard over production telemetry
# on a password printed in its own documentation.
grafana:
+ depends_on:
+ preflight-secrets:
+ condition: service_completed_successfully
ports: !reset []
restart: unless-stopped
environment:
diff --git a/scripts/check_published_secrets.py b/scripts/check_published_secrets.py
new file mode 100644
index 000000000..f024beb48
--- /dev/null
+++ b/scripts/check_published_secrets.py
@@ -0,0 +1,382 @@
+#!/usr/bin/env python3
+"""Refuse a secret whose value is published in this repository.
+
+The hole this closes
+--------------------
+``docker-compose.prod.yml`` states, in its own header, that "nothing starts on
+a default credential", and implements that with::
+
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD — the development default is a published literal}
+
+Compose's ``:?`` operator rejects an **unset or empty** variable. It cannot
+look at a value. ``.env.example`` ships ``POSTGRES_PASSWORD=aisoc_dev_secret``
+and ``docker-compose.yml`` defaults the same variable to the same literal, so
+the one input the message names is the one input the guard accepts. Measured
+before the fix::
+
+ $ printf 'POSTGRES_PASSWORD=aisoc_dev_secret\\n' > .env
+ $ docker compose config
+ POSTGRES_PASSWORD: aisoc_dev_secret # no error
+
+Every ``${VAR:?}`` in that file has the same shape, so the property the file
+claims held for none of them.
+
+Why a value check has to run
+----------------------------
+There is no Compose expression that compares a value, so the check cannot live
+in the interpolation. It runs as the ``preflight-secrets`` service, which every
+other service depends on with ``condition: service_completed_successfully`` —
+a non-zero exit there stops the stack before the first datastore starts, which
+is the same moment and the same shape of failure as the ``:?`` guard the file
+already documents.
+
+Where the list of published values comes from
+---------------------------------------------
+Derived from the tree, never hand-written. A hand-maintained list of "secrets
+we published" is a list that stops matching the day someone adds a new default,
+and the gate that reads it keeps printing OK. So this reads:
+
+* every ``${VAR:-literal}`` fallback in the compose files, for secret-shaped
+ variable names — that is where a published default actually lives;
+* every non-empty value in ``.env.example`` for a secret-shaped name, plus any
+ password embedded in a URL there (``redis://:redis_dev_secret@…``);
+* ``INSECURE_SECRET_KEY_DEFAULTS`` from the API settings module, read by AST
+ rather than imported so this file keeps running on a bare interpreter.
+
+The comparison is on **values**, not on variable names. Setting
+``NEO4J_PASSWORD`` to the literal published for ``POSTGRES_PASSWORD`` is the
+same disclosure, and naming the variable it was published for is the useful
+half of the error message.
+
+Modes
+-----
+``--check-env`` inspect this process's environment. What the preflight
+ container runs; the production stack's guarded variables are
+ interpolated into it by Compose.
+``--check`` verdict over the repository: every ``${VAR:?}`` guard in the
+ production compose file must be a variable the preflight
+ service actually receives, and the preflight must be wired
+ ahead of every service. A guard added without extending the
+ preflight is the way this would rot, so it is the thing
+ asserted.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import os
+import re
+import sys
+from collections.abc import Iterable, Mapping
+from pathlib import Path
+from urllib.parse import urlsplit
+
+# `scripts/` is on sys.path when this file is run as a program, but not when a
+# test loads it by path with importlib. gate_toolkit sits beside it either way.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import repo_root, self_test_if_requested
+
+self_test_if_requested(__file__)
+
+#: The Compose service that runs ``--check-env`` ahead of everything else.
+PREFLIGHT_SERVICE = "preflight-secrets"
+
+#: Variable names whose value is a credential. Matched on the name, and used
+#: only to decide *what to harvest as published* and *what to inspect in an
+#: environment* — never to decide whether a value is safe.
+SECRET_NAME_RE = re.compile(
+ r"(PASSWORD|PASSWD|SECRET|TOKEN|_KEY$|_KEY_|APIKEY|API_KEY|CREDENTIAL|PRIVATE)",
+ re.IGNORECASE,
+)
+
+#: Variables that carry a credential inside a URL rather than on their own.
+URL_NAME_RE = re.compile(r"(_URL$|_DSN$|_URI$)", re.IGNORECASE)
+
+#: ``${NAME:-default}`` with a non-empty default.
+COMPOSE_DEFAULT_RE = re.compile(r"\$\{([A-Z0-9_]+):-([^}]+)\}")
+
+#: ``${NAME:?message}`` — the guard this module exists because of.
+COMPOSE_REQUIRED_RE = re.compile(r"\$\{([A-Z0-9_]+):\?")
+
+#: Values that are not credentials even though they sit on a secret-shaped
+#: name, so harvesting them would make the checker refuse a correct
+#: deployment. Each is a mode switch or a file path, not a shared secret.
+NOT_A_CREDENTIAL = frozenset(
+ {
+ "true",
+ "false",
+ "0",
+ "1",
+ "none",
+ "disabled",
+ "enabled",
+ "auto",
+ "latest",
+ }
+)
+
+#: A published value shorter than this is a word, not a key, and matching on it
+#: would refuse real passwords that happen to contain it. ``admin`` is below the
+#: bar and is listed explicitly because Grafana really does ship it.
+MIN_HARVEST_LEN = 6
+ALWAYS_HARVEST = frozenset({"admin", "aisoc", "changeme", "password", "secret"})
+
+
+def _dotenv_pairs(text: str) -> Iterable[tuple[str, str]]:
+ for raw in text.splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#"):
+ continue
+ name, sep, value = line.partition("=")
+ if not sep:
+ continue
+ name = name.removeprefix("export ").strip()
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
+ continue
+ yield name, value.strip().strip('"').strip("'")
+
+
+def _url_password(value: str) -> str | None:
+ """The password embedded in ``scheme://user:password@host``, if any."""
+ if "://" not in value:
+ return None
+ try:
+ parsed = urlsplit(value)
+ except ValueError:
+ return None
+ password = parsed.password
+ if not password or "${" in password:
+ return None
+ return password
+
+
+def _harvestable(value: str) -> bool:
+ candidate = value.strip()
+ if not candidate or "${" in candidate:
+ return False
+ if candidate.lower() in NOT_A_CREDENTIAL:
+ return False
+ if candidate.lower() in ALWAYS_HARVEST:
+ return True
+ return len(candidate) >= MIN_HARVEST_LEN
+
+
+def _insecure_secret_key_defaults(root: Path) -> set[str]:
+ """``INSECURE_SECRET_KEY_DEFAULTS`` from the API settings, read by AST.
+
+ Imported would mean pydantic on the path. This runs in a preflight
+ container built for something else, and on a host before any install.
+ """
+ config = root / "services" / "api" / "app" / "core" / "config.py"
+ if not config.exists():
+ return set()
+ try:
+ tree = ast.parse(config.read_text(encoding="utf-8"))
+ except SyntaxError:
+ return set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
+ target = node.target.id
+ elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
+ target = node.targets[0].id
+ else:
+ continue
+ if target != "INSECURE_SECRET_KEY_DEFAULTS" or node.value is None:
+ continue
+ return {
+ literal.value.strip()
+ for literal in ast.walk(node.value)
+ if isinstance(literal, ast.Constant) and isinstance(literal.value, str) and literal.value.strip()
+ }
+ return set()
+
+
+def compose_files(root: Path) -> list[Path]:
+ paths = [root / "docker-compose.yml", root / "docker-compose.prod.yml"]
+ paths += sorted((root / "infra" / "compose").glob("docker-compose*.yml"))
+ return [p for p in paths if p.exists()]
+
+
+def published_literals(root: Path | None = None) -> dict[str, str]:
+ """``value -> where it is published``, derived from the tree.
+
+ Raises when it harvests nothing: an empty set of published values makes
+ every check below pass, and "scanned nothing" must not print the same word
+ as "found nothing".
+ """
+ root = root or repo_root()
+ found: dict[str, str] = {}
+
+ for path in compose_files(root):
+ rel = path.relative_to(root)
+ for name, default in COMPOSE_DEFAULT_RE.findall(path.read_text(encoding="utf-8")):
+ # A URL-shaped variable publishes only the credential inside it.
+ # Harvesting the whole value would put `http://api:8000` on the
+ # refused list and make the preflight reject a correct stack.
+ value = _url_password(default) if URL_NAME_RE.search(name) else (default if SECRET_NAME_RE.search(name) else None)
+ if value and _harvestable(value):
+ found.setdefault(value, f"{rel} default for {name}")
+
+ example = root / ".env.example"
+ if example.exists():
+ for name, value in _dotenv_pairs(example.read_text(encoding="utf-8")):
+ harvested = _url_password(value) if URL_NAME_RE.search(name) else (value if SECRET_NAME_RE.search(name) else None)
+ if harvested and _harvestable(harvested):
+ found.setdefault(harvested, f".env.example {name}")
+
+ for value in _insecure_secret_key_defaults(root):
+ if _harvestable(value):
+ found.setdefault(value, "INSECURE_SECRET_KEY_DEFAULTS in services/api/app/core/config.py")
+
+ if not found:
+ raise SystemExit(
+ "check_published_secrets: harvested no published values from "
+ f"{root}. Refusing to report a clean environment against an empty list."
+ )
+ return found
+
+
+def offending(env: Mapping[str, str], published: Mapping[str, str]) -> list[tuple[str, str]]:
+ """``(variable, where the value is published)`` for each hit in ``env``."""
+ hits: list[tuple[str, str]] = []
+ for name, value in sorted(env.items()):
+ if not value:
+ continue
+ candidates = [value.strip()]
+ embedded = _url_password(value)
+ if embedded:
+ candidates.append(embedded)
+ if not (SECRET_NAME_RE.search(name) or URL_NAME_RE.search(name)):
+ continue
+ for candidate in candidates:
+ where = published.get(candidate)
+ if where:
+ hits.append((name, where))
+ break
+ return hits
+
+
+def _compose_services(path: Path) -> dict:
+ """`services:` from a compose file, with the merge tags understood."""
+ import yaml # noqa: PLC0415 — only the repo-side verdict needs a YAML parser
+
+ class _Loader(yaml.SafeLoader):
+ pass
+
+ def _strip(loader, node): # noqa: ANN001, ANN202 - loader plumbing
+ if isinstance(node, yaml.SequenceNode):
+ return loader.construct_sequence(node, deep=True)
+ if isinstance(node, yaml.MappingNode):
+ return loader.construct_mapping(node, deep=True)
+ return loader.construct_scalar(node)
+
+ for tag in ("!reset", "!override"):
+ _Loader.add_constructor(tag, _strip)
+
+ return (yaml.load(path.read_text(encoding="utf-8"), Loader=_Loader) or {}).get("services") or {} # noqa: S506
+
+
+def guarded_variables(prod: Path) -> set[str]:
+ """Every ``${VAR:?}`` the production compose file actually interpolates.
+
+ Read off the parsed values rather than the raw text. The header comment
+ in that file spells `${VAR:?}` out to explain the hole this module closes,
+ and a text scan harvests `VAR` from the prose — the same mistake
+ ``test_no_dev_secret_literal_reaches_a_service`` in the gate records
+ having made once already.
+ """
+ found: set[str] = set()
+ for service in _compose_services(prod).values():
+ environment = (service or {}).get("environment") or {}
+ values = environment.values() if isinstance(environment, dict) else environment
+ for value in values:
+ found |= set(COMPOSE_REQUIRED_RE.findall(str(value)))
+ return found
+
+
+def _check_env() -> int:
+ published = published_literals()
+ hits = offending(os.environ, published)
+ if not hits:
+ print(f"OK: no secret holds one of the {len(published)} values published in this repository.")
+ return 0
+ print("Refusing to start: these hold a value published in this repository.", file=sys.stderr)
+ for name, where in hits:
+ print(f" - {name} is set to the literal published as {where}", file=sys.stderr)
+ print(
+ "\nGenerate replacements with `make env`, or set them yourself; `openssl rand -hex 32` is fine for any of them.",
+ file=sys.stderr,
+ )
+ return 1
+
+
+def _check_repo() -> int:
+ root = repo_root()
+ prod = root / "docker-compose.prod.yml"
+ if not prod.exists():
+ print("FAIL: docker-compose.prod.yml is missing.", file=sys.stderr)
+ return 1
+
+ guarded = guarded_variables(prod)
+ if not guarded:
+ print("FAIL: found no `${VAR:?}` guards to cover.", file=sys.stderr)
+ return 1
+
+ services = _compose_services(prod)
+ preflight = services.get(PREFLIGHT_SERVICE)
+ if not preflight:
+ print(f"FAIL: `{PREFLIGHT_SERVICE}` is not defined in docker-compose.prod.yml.", file=sys.stderr)
+ return 1
+
+ received = set((preflight.get("environment") or {}).keys())
+ missing = sorted(guarded - received)
+ if missing:
+ print(
+ "FAIL: these are guarded with `${VAR:?}` but never reach the preflight, "
+ "so a published value in them would not be caught: " + ", ".join(missing),
+ file=sys.stderr,
+ )
+ return 1
+
+ ungated = sorted(
+ name
+ for name, service in services.items()
+ if name != PREFLIGHT_SERVICE and PREFLIGHT_SERVICE not in ((service or {}).get("depends_on") or {})
+ )
+ if ungated:
+ print(
+ f"FAIL: these start without waiting for `{PREFLIGHT_SERVICE}`: " + ", ".join(ungated),
+ file=sys.stderr,
+ )
+ return 1
+
+ published = published_literals(root)
+ sample = next(iter(published))
+ if not offending({"POSTGRES_PASSWORD": sample}, published):
+ print("FAIL: the checker does not flag a value it harvested as published.", file=sys.stderr)
+ return 1
+
+ print(
+ f"OK: {len(guarded)} guarded variables all reach `{PREFLIGHT_SERVICE}`, "
+ f"{len(services) - 1} services wait for it, and {len(published)} published values are refused."
+ )
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--check-env", action="store_true", help="inspect this process's environment")
+ parser.add_argument("--check", action="store_true", help="verdict over the repository")
+ args = parser.parse_args(argv)
+ if args.check_env:
+ return _check_env()
+ if args.check:
+ return _check_repo()
+ parser.error("choose --check-env or --check")
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ensure_env.py b/scripts/ensure_env.py
index 43e0c8b27..8760c5858 100644
--- a/scripts/ensure_env.py
+++ b/scripts/ensure_env.py
@@ -122,6 +122,34 @@ GENERATED: dict[str, tuple[Callable[[], str], str]] = {
lambda: secrets.token_urlsafe(32),
"Bearer for realtime's /internal/* fan-out (API/agents -> realtime). Sent as x-internal-token.",
),
+ # The datastore passwords. `.env.example` shipped these as
+ # `aisoc_dev_secret` / `aisoc_app_dev_secret` / `redis_dev_secret` /
+ # `clickhouse_dev_secret`, and `docker-compose.prod.yml` guarded each one
+ # with `${VAR:?… the development default is a published literal}`.
+ # Compose's `:?` rejects an unset or empty variable and cannot look at a
+ # value, so every one of those guards accepted the exact literal its own
+ # message named. `preflight-secrets` in that file refuses the value at
+ # boot; generating them here means a fresh install never holds one.
+ #
+ # Hex rather than urlsafe base64: these travel inside DSNs
+ # (`redis://:$REDIS_PASSWORD@…`) and a `/` or `+` in the userinfo would
+ # have to be percent-encoded by every consumer that builds one.
+ "POSTGRES_PASSWORD": (
+ lambda: secrets.token_hex(24),
+ "Postgres owner role. Owns every table and applies the migration chain; no service connects as it.",
+ ),
+ "AISOC_APP_DB_PASSWORD": (
+ lambda: secrets.token_hex(24),
+ "Postgres runtime role (aisoc_app). DML only, so the row-level-security policies apply to it.",
+ ),
+ "REDIS_PASSWORD": (
+ lambda: secrets.token_hex(24),
+ "Redis AUTH password. Referenced by REDIS_URL rather than repeated inside it.",
+ ),
+ "CLICKHOUSE_PASSWORD": (
+ lambda: secrets.token_hex(24),
+ "ClickHouse event-lake password. Referenced by CLICKHOUSE_URL rather than repeated inside it.",
+ ),
}
diff --git a/tests/test_env_placeholder_gate.py b/tests/test_env_placeholder_gate.py
index 887d5ab9a..ff1ea1cd1 100644
--- a/tests/test_env_placeholder_gate.py
+++ b/tests/test_env_placeholder_gate.py
@@ -71,12 +71,10 @@ DELIBERATE_DEFAULTS: dict[str, str] = {
"AISOC_REALTIME_TICKET_TTL_SECONDS": "a duration",
"CONNECTORS_SERVICE_URL": "the compose hostname of the connectors service",
"CONNECTORS_SERVICE_TIMEOUT_SECONDS": "a duration",
- "POSTGRES_PASSWORD": "dev Postgres password; works out of the box, documented as changeable",
- "AISOC_APP_DB_PASSWORD": "dev password for the runtime DB role; same reasoning",
- "DATABASE_URL": "a DSN built from the two passwords above",
+ "DATABASE_URL": "a DSN that references the generated passwords rather than repeating them",
"DATABASE_MIGRATION_URL": "the owner-role DSN used only by the migration runner",
- "REDIS_URL": "dev Redis DSN",
- "CLICKHOUSE_URL": "dev ClickHouse DSN",
+ "REDIS_URL": "a DSN that references REDIS_PASSWORD rather than repeating it",
+ "CLICKHOUSE_URL": "a DSN that references CLICKHOUSE_PASSWORD rather than repeating it",
"KAFKA_BOOTSTRAP_SERVERS": "a host:port",
"OPENSEARCH_URL": "a URL",
"QDRANT_URL": "a URL",
@@ -94,9 +92,6 @@ DELIBERATE_DEFAULTS: dict[str, str] = {
"SPLUNK_SCHEME": "a URL scheme",
"SPLUNK_VERIFY_SSL": "a boolean, and the secure default",
"AWS_REGION": "a region",
- "NEXT_PUBLIC_API_URL": "a localhost URL",
- "NEXT_PUBLIC_REALTIME_URL": "a localhost URL",
- "NEXT_PUBLIC_WS_URL": "a localhost URL",
}
#: The exact strings the old grep failed to match. Pinned as a regression test:
@@ -145,6 +140,22 @@ def test_every_shipped_value_is_either_a_placeholder_or_a_declared_default() ->
)
+def test_no_declared_default_outlives_the_value_it_describes() -> None:
+ """The list above runs in one direction only unless this runs the other.
+
+ A row whose variable no longer ships a non-empty value is prose nobody
+ checks: `POSTGRES_PASSWORD` sat here described as "works out of the box,
+ documented as changeable" for as long as the template shipped
+ `aisoc_dev_secret`, and would have kept saying so after it stopped.
+ """
+ live = {key for _lineno, key, value in _example_entries() if value.strip() and not check_env_placeholders.is_placeholder(value)}
+ stale = sorted(set(DELIBERATE_DEFAULTS) - live)
+ assert not stale, (
+ "these are declared as real defaults but .env.example no longer ships a non-empty "
+ f"value for them: {stale}. Remove the row, or the description outlives the value."
+ )
+
+
@pytest.mark.parametrize("value", HISTORICAL_PLACEHOLDERS)
def test_the_detector_still_catches_every_placeholder_this_repo_has_shipped(value: str) -> None:
assert check_env_placeholders.is_placeholder(value), (
diff --git a/tests/test_production_compose_gate.py b/tests/test_production_compose_gate.py
index bc92ef568..8d5cba81b 100644
--- a/tests/test_production_compose_gate.py
+++ b/tests/test_production_compose_gate.py
@@ -19,8 +19,12 @@ file.
from __future__ import annotations
import ast
+import importlib.util
+import os
import pathlib
import re
+import subprocess
+import sys
import pytest
import yaml
@@ -131,6 +135,48 @@ def prod() -> dict:
return _services(PROD)
+class TestTheDocumentedCommandIsTheOneThatWorks:
+ """The deployment page and this file must name the same invocation.
+
+ The production stack was written with `include:` and a single `-f`, which
+ resolves on Compose 5.x and is rejected by 2.x with
+ `services.<name> conflicts with imported resource` — `include` imports a
+ model, and overriding a service it imported is an error. Measured against
+ v2.29.7 and v2.39.4: both fail. So the documented production command
+ worked on almost no installation, and nothing noticed because the smoke
+ job only ever drove `docker-compose.yml`.
+
+ These are static assertions rather than a subprocess call, so they hold on
+ a runner with no Docker; the compose-smoke workflow exercises the real
+ binary.
+ """
+
+ def test_the_production_file_does_not_import_the_base(self) -> None:
+ document = yaml.load(PROD.read_text(encoding="utf-8"), Loader=_ComposeLoader) # noqa: S506
+ assert "include" not in (document or {}), (
+ "`include:` plus an override of an imported service is rejected by every released Compose 2.x. Use two `-f` flags instead."
+ )
+
+ def test_the_docs_give_both_files_in_order(self) -> None:
+ page = (REPO / "apps" / "docs" / "docs" / "deployment" / "docker.md").read_text(encoding="utf-8")
+ assert "-f docker-compose.yml -f docker-compose.prod.yml" in page, (
+ "the deployment page must give both files, base first — the overlay alone does not resolve on Compose 2.x"
+ )
+ assert "-f docker-compose.prod.yml up" not in page.replace("-f docker-compose.yml -f docker-compose.prod.yml up", ""), (
+ "the page still shows the single-file form somewhere"
+ )
+
+ def test_the_smoke_workflow_drives_the_same_command(self) -> None:
+ """A workflow that exercises a different invocation than the docs
+ publish proves nothing about the documented one."""
+ flow = (REPO / ".github" / "workflows" / "compose-smoke.yml").read_text(encoding="utf-8")
+ if "docker-compose.prod.yml" in flow:
+ assert "-f docker-compose.yml -f docker-compose.prod.yml" in flow
+ assert flow.count("-f docker-compose.prod.yml") == flow.count("-f docker-compose.yml -f docker-compose.prod.yml"), (
+ "some invocation still passes the overlay alone"
+ )
+
+
class TestTheBypassIsUnreachable:
def test_no_service_runs_in_a_dev_class_environment(self, prod: dict) -> None:
assert not _dev_environments(prod)
@@ -398,3 +444,121 @@ class TestNoDatastoreIsBoundToTheHost:
profiles = (prod.get("kafka-ui") or {}).get("profiles") or []
assert "full" not in profiles, "`--profile full` would start kafka-ui beside production data"
assert profiles, "kafka-ui has no profile at all, so it now starts in the default stack"
+
+
+# ─── `${VAR:?}` cannot look at a value ───────────────────────────────────────
+#
+# The sixteen assertions above all read this file statically, and every one of
+# them passed while the stack booted on `aisoc_dev_secret`. Compose's `:?`
+# operator rejects an **unset or empty** variable; it has no way to compare
+# one. `.env.example` shipped `POSTGRES_PASSWORD=aisoc_dev_secret` and
+# `docker-compose.yml` defaults the same variable to the same literal, so the
+# one input `${POSTGRES_PASSWORD:?… the development default is a published
+# literal}` names is the one input it accepts.
+#
+# `TestNothingStartsOnAPublishedCredential` above is therefore about the
+# *shape* of the guard. What follows is about the value, and it runs the real
+# program rather than reading the file that describes it.
+
+
+def _load_checker():
+ spec = importlib.util.spec_from_file_location("check_published_secrets", REPO / "scripts" / "check_published_secrets.py")
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _run_checker(env: dict[str, str]) -> subprocess.CompletedProcess[str]:
+ """`--check-env` in a subprocess, with a controlled environment.
+
+ A subprocess rather than a function call: `--check-env` reads
+ `os.environ`, and the thing worth asserting is the exit status the
+ preflight container produces, not a return value.
+ """
+ return subprocess.run( # noqa: S603 - fixed argv, no shell
+ [sys.executable, str(REPO / "scripts" / "check_published_secrets.py"), "--check-env"],
+ capture_output=True,
+ text=True,
+ check=False,
+ env={"PATH": os.environ.get("PATH", ""), "AISOC_REPO_ROOT": str(REPO), **env},
+ )
+
+
+class TestAPublishedValueCannotSatisfyAGuard:
+ def test_the_harvest_finds_the_literals_this_repository_publishes(self) -> None:
+ published = _load_checker().published_literals(REPO)
+ # Named explicitly. The harvest is derived from the tree so it cannot
+ # go stale, but a regex that silently stops matching would make it
+ # derive nothing and every check below would pass.
+ for literal in ("aisoc_dev_secret", "aisoc_app_dev_secret", "redis_dev_secret", "clickhouse_dev_secret"):
+ assert literal in published, f"{literal} is published in this tree and was not harvested"
+
+ def test_a_real_secret_is_accepted(self) -> None:
+ """The other direction. A checker that refused everything would pass
+ the test below and ship a production stack that cannot start."""
+ result = _run_checker({"POSTGRES_PASSWORD": "9b20969c058203d8a725c09800645f4666f913d80590c094"}) # gitleaks:allow
+ assert result.returncode == 0, result.stderr
+
+ @pytest.mark.parametrize(
+ ("variable", "value"),
+ [
+ ("POSTGRES_PASSWORD", "aisoc_dev_secret"),
+ ("AISOC_APP_DB_PASSWORD", "aisoc_app_dev_secret"),
+ ("REDIS_PASSWORD", "redis_dev_secret"),
+ ("CLICKHOUSE_PASSWORD", "clickhouse_dev_secret"),
+ ("SECRET_KEY", "dev_secret_key_change_in_production"),
+ ("GRAFANA_ADMIN_PASSWORD", "admin"),
+ # The value, not the variable. Reusing one variable's published
+ # literal on another is the same disclosure.
+ ("NEO4J_PASSWORD", "aisoc_dev_secret"),
+ # And inside a DSN, which is where three of them used to live.
+ ("REDIS_URL", "redis://:redis_dev_secret@redis:6379/0"),
+ ],
+ )
+ def test_a_published_value_is_refused(self, variable: str, value: str) -> None:
+ result = _run_checker({variable: value})
+ assert result.returncode == 1, f"{variable}={value} was accepted:\n{result.stdout}{result.stderr}"
+ assert variable in result.stderr
+
+ def test_the_checker_refuses_rather_than_reporting_clean_over_an_empty_tree(self, tmp_path: pathlib.Path) -> None:
+ """`published_literals` over a tree with no compose files harvests
+ nothing, and nothing matches nothing. Reporting OK there would make
+ the preflight a no-op in any deployment whose mount went wrong."""
+ result = subprocess.run( # noqa: S603 - fixed argv, no shell
+ [sys.executable, str(REPO / "scripts" / "check_published_secrets.py"), "--check-env"],
+ capture_output=True,
+ text=True,
+ check=False,
+ env={"PATH": os.environ.get("PATH", ""), "AISOC_REPO_ROOT": str(tmp_path)},
+ )
+ assert result.returncode != 0
+ assert "harvested no published values" in result.stderr
+
+ def test_every_guard_reaches_the_preflight(self) -> None:
+ """A guard added later without extending the preflight is how this
+ rots: the variable would be required-non-empty and unchecked."""
+ checker = _load_checker()
+ guarded = checker.guarded_variables(PROD)
+ preflight = _services(PROD).get(checker.PREFLIGHT_SERVICE) or {}
+ received = {key for key, _ in _env_items(preflight)}
+ assert guarded - received == set(), f"guarded but never checked: {sorted(guarded - received)}"
+
+ def test_nothing_starts_before_the_preflight(self) -> None:
+ checker = _load_checker()
+ overlay = _services(PROD)
+ ungated = sorted(
+ name
+ for name, service in overlay.items()
+ if name != checker.PREFLIGHT_SERVICE and checker.PREFLIGHT_SERVICE not in ((service or {}).get("depends_on") or {})
+ )
+ assert not ungated, f"these start without waiting for the credential check: {ungated}"
+
+ def test_every_base_service_is_covered_by_the_overlay(self) -> None:
+ """`depends_on` can only be added to a service the overlay names. A
+ service defined only in the base file inherits nothing from here, and
+ one such service starting ahead of the check is the whole hole."""
+ checker = _load_checker()
+ overlay = set(_services(PROD))
+ missing = sorted(set(_services(DEV)) - overlay - {checker.PREFLIGHT_SERVICE})
+ assert not missing, f"defined in docker-compose.yml and not restated here, so ungated: {missing}"