feat(deploy): add an isolated demo stand with synthetic seed and guarded reset

This commit is contained in:
shira committed 2026-10-09 14:46:18 +03:00
1 parent bd23c839fd
commit e1df4ff77c
26 files changed
+3292 -2

No files matched your search

+1
View File
@@ -1 +1,2 @@
/release/
/demo/demo.env
+30 -2
View File
@@ -17,6 +17,7 @@ ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml
MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml
E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml
E2E_MAIL_FILE := $(ROOT)/deploy/docker/docker-compose.e2e-mail.yml
DEMO_FILE := $(ROOT)/deploy/docker/docker-compose.demo.yml
RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml
ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml
RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py
@@ -36,9 +37,23 @@ RELEASE_MANIFEST_ARG = $(if $(strip $(RELEASE_MANIFEST)),--manifest "$(RELEASE_M
# Recursive on purpose: git is asked only by the targets that use the tag. The
# project-specific name keeps a generic RELEASE_TAG from enabling release mode.
LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" tag)
# Isolated demonstration stand (deploy/scripts/demo.sh). Every demo target
# needs DEMO_MODE=isolated on the command line and acts only on DEMO_PROJECT.
DEMO_MODE ?=
DEMO_PROJECT ?= lincodex-demo
DEMO_HTTP_PORT ?= 8090
DEMO_PUBLIC_URL ?= http://localhost:$(DEMO_HTTP_PORT)
DEMO_SUBNET ?= 172.29.84.0/24
DEMO_FRONTEND_IP ?= 172.29.84.10
DEMO_ACTOR ?= operator:demo-seed
# demo.env is local; the checked-in example is used when it does not exist.
DEMO_ENV ?= $(if $(wildcard $(ROOT)/deploy/demo/demo.env),$(ROOT)/deploy/demo/demo.env,$(ROOT)/deploy/demo/demo.env.example)
DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DEMO_PROJECT)" APP_PROJECT="$(APP_PROJECT)" \
ENV_FILE="$(ENV_FILE)" DEMO_ENV_FILE="$(DEMO_ENV)" DEMO_HTTP_PORT="$(DEMO_HTTP_PORT)" DEMO_PUBLIC_URL="$(DEMO_PUBLIC_URL)" \
DEMO_SUBNET="$(DEMO_SUBNET)" DEMO_FRONTEND_IP="$(DEMO_FRONTEND_IP)" DEMO_ACTOR="$(DEMO_ACTOR)"
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down
help: ## Show deployment commands
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -53,6 +68,7 @@ config: ## Render all Compose files with safe example values
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet
APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet
APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(DEMO_FILE)" --profile demo-seed config --quiet
E2E_COMPANY_FIXTURE_TOKEN=render-only-company-fixture-token-00000000000000000000000000000000 APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet
build: ## Build local frontend and backend images
@@ -116,7 +132,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl
edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container
@DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)"
check: config check-workflows check-release check-perimeter check-e2e-mail ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check: config check-workflows check-release check-perimeter check-e2e-mail check-demo ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check-workflows: ## Check that each workflow aggregate job requires every other job
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py'
@@ -130,6 +146,9 @@ check-perimeter: ## Check published ports, the app Nginx paths, limits, and the
check-e2e-mail: ## Check that the mail fixture stays inside the explicit local E2E network
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_e2e_mail.py'
check-demo: ## Check the guards of the demo targets and the demo overlay without starting services
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_demo.py'
perimeter-test: ## Start throwaway Nginx containers and test denied paths, limits, headers, and forwarded headers over HTTP
LINCODEX_PERIMETER_LIVE=1 DOCKER="$(DOCKER)" PERIMETER_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -v -s "$(ROOT)/deploy/scripts" -p 'test_perimeter.py'
@@ -170,3 +189,12 @@ release-down: ## Stop the release project selected by the immutable manifest and
release-clean: ## Remove local release image references not retained by an immutable manifest
@$(RELEASE) clean-images
demo-seed: ## Start the isolated demo stand when needed and seed its synthetic data (needs DEMO_MODE=isolated)
@$(DEMO_SCRIPT_ENV) bash scripts/demo.sh seed
demo-reset: ## Discard only the isolated demo project when it holds no ordinary account, then seed it again (needs DEMO_MODE=isolated)
@$(DEMO_SCRIPT_ENV) bash scripts/demo.sh reset
demo-down: ## Stop the isolated demo stand and keep its volumes (needs DEMO_MODE=isolated)
@$(DEMO_SCRIPT_ENV) bash scripts/demo.sh down
+1
View File
@@ -9,6 +9,7 @@ Configuration for running the application with Docker Compose and Nginx.
- `nginx/` configures frontend serving and API proxying.
- `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner.
- `docker/docker-compose.release.yml` and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/<service>:<tag>` and never pull them from a registry.
- `docker/docker-compose.demo.yml` and `demo/` belong to the isolated demo stand with synthetic data: `make -C deploy demo-seed DEMO_MODE=isolated` starts and seeds it, `demo-reset` rebuilds it only when it holds no ordinary account, and `demo-down` stops it; see the [isolated demo stand](../docs/en/DEPLOY.md#isolated-demo-stand).
- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images.
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
- `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address).
+1
View File
@@ -9,6 +9,7 @@
- `nginx/` содержит конфигурацию раздачи frontend и проксирования API.
- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright.
- `docker/docker-compose.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/<service>:<tag>` без скачивания из registry.
- `docker/docker-compose.demo.yml` и `demo/` относятся к изолированному демонстрационному стенду с синтетическими данными: `make -C deploy demo-seed DEMO_MODE=isolated` запускает и заполняет его, `demo-reset` пересоздает его, только если в нем нет обычных аккаунтов, а `demo-down` останавливает; см. [изолированный демонстрационный стенд](../docs/ru/DEPLOY.md#изолированный-демонстрационный-стенд).
- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска.
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
- `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента).
+10
View File
@@ -0,0 +1,10 @@
# Settings of the synthetic demo accounts on an isolated demo stand. Copy this
# file to demo.env next to it to use another password; demo.env is local and
# ignored by Git. Without demo.env, make -C deploy demo-seed reads this
# example. The value is a published demo credential of synthetic accounts on
# a stand without real people, not a secret: never reuse it anywhere else.
#
# Shared password of every synthetic account the seed creates (at least 15
# characters). It applies when an account is created; change it by editing
# demo.env and running make -C deploy demo-reset DEMO_MODE=isolated.
DEMO_ACCOUNT_PASSWORD=synthetic demo stand only 2026
+52
View File
@@ -0,0 +1,52 @@
# Overlay of the isolated demonstration stand. Only deploy/scripts/demo.sh
# combines it with docker-compose.yml, under the dedicated demo project
# (DEMO_PROJECT, lincodex-demo by default); never apply it to the working
# stand. The demo stand holds synthetic data only.
services:
backend:
environment:
# A full test on the demo stand assigns an uncalibrated synthetic
# demonstration category, as the prepared attempts do.
ASSESSMENT_DEMO_CATEGORIES_ENABLED: "true"
labels:
org.lincodex.demo-mode: isolated
demo-seed:
build:
context: ../../backend
dockerfile: Dockerfile.demo-seed
profiles: ["demo-seed"]
environment:
DATABASE_URL: postgres://${POSTGRES_USER:?Set POSTGRES_USER}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:?Set POSTGRES_DB}?sslmode=disable
# The command checks the mode itself; demo.sh passes it only after its
# own guard.
DEMO_MODE: ${DEMO_MODE:-}
DEMO_ACCOUNT_PASSWORD: ${DEMO_ACCOUNT_PASSWORD:?Set DEMO_ACCOUNT_PASSWORD in the demo env file}
depends_on:
postgres:
condition: service_healthy
# The command reaches PostgreSQL only; it never joins the storage network.
networks:
- default
restart: "no"
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
deploy:
resources:
limits:
cpus: "1.0"
memory: 256M
# The label is set when a volume is created, so only volumes that this
# overlay created carry it; demo.sh refuses to discard a volume without it.
volumes:
postgres_data:
labels:
org.lincodex.demo-mode: isolated
seaweedfs_data:
labels:
org.lincodex.demo-mode: isolated
kafka_data:
labels:
org.lincodex.demo-mode: isolated
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env bash
# Operator actions of the isolated demonstration stand.
#
# The stand is a dedicated Compose project (DEMO_PROJECT, lincodex-demo by
# default) of docker-compose.yml with docker-compose.demo.yml. Every action
# requires DEMO_MODE=isolated and addresses only that project; the ordinary
# project (APP_PROJECT) and its volumes are never touched.
#
# Usage: demo.sh seed|reset|down
# seed start the demo project when needed, run the idempotent seed, and
# print the inventory of its records
# reset check that the demo database holds no account outside the
# synthetic domain, discard the demo project with its volumes,
# start it again, and seed
# down stop the demo project and keep its volumes
#
# Environment (deploy/Makefile sets it):
# DEMO_MODE must be "isolated"
# DEMO_PROJECT Compose project of the demo stand; contains "demo" and
# differs from APP_PROJECT
# APP_PROJECT the ordinary project, only compared against
# ENV_FILE root env file with the stand secrets
# DEMO_ENV_FILE demo env file with DEMO_ACCOUNT_PASSWORD
# DEMO_HTTP_PORT host port of the demo frontend
# DEMO_PUBLIC_URL public origin of the demo stand
# DEMO_SUBNET, DEMO_FRONTEND_IP pinned network of the demo project
# DEMO_ACTOR operator:<handle> that the seed records
# DOCKER docker CLI
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
compose_file="$root/deploy/docker/docker-compose.yml"
demo_file="$root/deploy/docker/docker-compose.demo.yml"
docker_cli="${DOCKER:-docker}"
demo_label='org.lincodex.demo-mode'
ready_attempts=120
fail() {
printf 'demo: %s\n' "$1" >&2
exit 2
}
if [[ "$#" -ne 1 ]]; then
fail 'usage: demo.sh seed|reset|down'
fi
action=$1
case "$action" in
seed | reset | down) ;;
*) fail 'usage: demo.sh seed|reset|down' ;;
esac
# The guards run before any Docker command.
if [[ "${DEMO_MODE:-}" != isolated ]]; then
fail "refusing to $action: set DEMO_MODE=isolated; the demo targets act only on an isolated demo stand"
fi
project="${DEMO_PROJECT:-lincodex-demo}"
ordinary_project="${APP_PROJECT:-app}"
if [[ ! "$project" =~ ^[a-z0-9][a-z0-9_-]*$ || "$project" != *demo* ]]; then
fail "refusing to $action: DEMO_PROJECT must be a Compose project name that contains 'demo'"
fi
if [[ "$project" == "$ordinary_project" ]]; then
fail "refusing to $action: DEMO_PROJECT must differ from the ordinary project APP_PROJECT=$ordinary_project"
fi
env_file="${ENV_FILE:-$root/.env}"
demo_env_file="${DEMO_ENV_FILE:-$root/deploy/demo/demo.env.example}"
[[ -f "$env_file" ]] || fail "missing $env_file; copy .env.example to .env and replace the placeholder passwords"
[[ -f "$demo_env_file" ]] || fail "missing demo env file $demo_env_file"
actor="${DEMO_ACTOR:-operator:demo-seed}"
[[ "$actor" =~ ^operator:[a-z0-9][a-z0-9._-]*$ ]] || fail 'DEMO_ACTOR must be operator:<handle>'
port="${DEMO_HTTP_PORT:-8090}"
[[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] || fail 'DEMO_HTTP_PORT must be a port number'
public_url="${DEMO_PUBLIC_URL:-http://localhost:$port}"
subnet="${DEMO_SUBNET:-172.29.84.0/24}"
frontend_ip="${DEMO_FRONTEND_IP:-172.29.84.10}"
# The shell values override the env files, so the root .env cannot point the
# demo project at the ordinary project's names, network, or port.
compose() {
APP_PROJECT="$project" APP_NETWORK="${project}_default" APP_STORAGE_NETWORK="${project}_storage" \
APP_HTTP_PORT="$port" APP_SUBNET="$subnet" APP_FRONTEND_IP="$frontend_ip" APP_PUBLIC_URL="$public_url" \
DEMO_MODE=isolated "$docker_cli" compose \
--env-file "$env_file" --env-file "$demo_env_file" \
-p "$project" -f "$compose_file" -f "$demo_file" "$@"
}
volume_exists() {
"$docker_cli" volume inspect "$1" >/dev/null 2>&1
}
# A volume carries the demo label only when the demo overlay created it, so a
# volume of an ordinary stand under this name is never adopted or discarded.
check_volumes() {
local volume label
for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data"; do
if volume_exists "$volume"; then
label=$("$docker_cli" volume inspect --format "{{ index .Labels \"$demo_label\" }}" "$volume")
if [[ "$label" != isolated ]]; then
fail "refusing to $action: volume $volume was not created by the demo overlay"
fi
fi
done
}
start_stand() {
compose up -d --build --wait --wait-timeout 300
local attempt response
for ((attempt = 1; attempt <= ready_attempts; attempt++)); do
response=$(compose exec -T frontend wget -q -O - http://backend:8080/readyz 2>/dev/null || true)
if [[ "$response" == '{"status":"ready"}' ]]; then
return 0
fi
sleep 1
done
fail "the backend of $project did not become ready"
}
run_command() {
compose --profile demo-seed run --rm --build demo-seed "$@"
}
# The inventory after the seed lets two runs be compared line by line.
seed() {
start_stand
run_command seed --actor "$actor"
run_command inventory
printf 'demo: the stand %s serves %s; the password is DEMO_ACCOUNT_PASSWORD of %s\n' \
"$project" "$public_url" "$demo_env_file"
}
check_volumes
case "$action" in
seed)
seed
;;
reset)
if volume_exists "${project}_postgres_data"; then
start_stand
if ! run_command check-reset; then
fail "reset refused for $project; nothing was deleted"
fi
fi
compose down --volumes --remove-orphans
seed
;;
down)
compose down
;;
esac
+215
View File
@@ -0,0 +1,215 @@
"""Guards of the isolated demo targets and the boundary of the demo overlay.
The script tests run demo.sh against a recording stub of the docker CLI, so
they prove which Docker commands a refusal never reaches. The render tests
need the docker CLI and are skipped without it.
"""
import json
import os
import shutil
import stat
import subprocess
import tempfile
import textwrap
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DEPLOY = ROOT / "deploy"
SCRIPT = DEPLOY / "scripts" / "demo.sh"
DOCKER = os.environ.get("DOCKER", "docker")
# The stub answers like a running demo stand: volumes exist with the label
# given in STUB_LABEL, the backend is ready, and check-reset exits with
# STUB_CHECK_RESET. Every call is appended to STUB_LOG.
STUB = textwrap.dedent(
"""\
#!/usr/bin/env bash
printf '%s\\n' "$*" >> "$STUB_LOG"
args=" $* "
if [[ "$args" == *" volume inspect --format "* ]]; then
printf '%s\\n' "${STUB_LABEL:-}"
exit 0
fi
if [[ "$args" == *" volume inspect "* ]]; then
exit "${STUB_VOLUME_STATUS:-0}"
fi
if [[ "$args" == *" wget "* ]]; then
printf '%s' '{"status":"ready"}'
exit 0
fi
if [[ "$args" == *" check-reset "* ]]; then
exit "${STUB_CHECK_RESET:-0}"
fi
exit 0
"""
)
class DemoScriptGuardTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
base = Path(self.directory.name)
self.stub = base / "docker"
self.stub.write_text(STUB)
self.stub.chmod(self.stub.stat().st_mode | stat.S_IXUSR)
self.log = base / "calls.log"
self.log.write_text("")
self.env_file = base / "root.env"
self.env_file.write_text("POSTGRES_USER=demo\n")
self.demo_env = base / "demo.env"
self.demo_env.write_text("DEMO_ACCOUNT_PASSWORD=synthetic demo stand only 2026\n")
def run_script(self, action, **overrides):
environment = {
"PATH": os.environ.get("PATH", ""),
"HOME": os.environ.get("HOME", ""),
"DOCKER": str(self.stub),
"STUB_LOG": str(self.log),
"DEMO_MODE": "isolated",
"DEMO_PROJECT": "lincodex-demo-test",
"APP_PROJECT": "app",
"ENV_FILE": str(self.env_file),
"DEMO_ENV_FILE": str(self.demo_env),
"STUB_LABEL": "isolated",
}
for key, value in overrides.items():
if value is None:
environment.pop(key, None)
else:
environment[key] = value
return subprocess.run(
["bash", str(SCRIPT), action], capture_output=True, text=True, env=environment, check=False
)
def calls(self):
return [line for line in self.log.read_text().splitlines() if line]
def test_every_action_refuses_without_the_isolated_mode_before_docker(self):
for action in ("seed", "reset", "down"):
for mode in (None, "", "production", "ISOLATED"):
with self.subTest(action=action, mode=mode):
result = self.run_script(action, DEMO_MODE=mode)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertIn("DEMO_MODE=isolated", result.stderr)
self.assertEqual(self.calls(), [])
def test_the_project_must_be_a_separate_demo_project(self):
cases = (
{"DEMO_PROJECT": "app"},
{"DEMO_PROJECT": "lincodex-demo-test", "APP_PROJECT": "lincodex-demo-test"},
{"DEMO_PROJECT": "lincodex"},
{"DEMO_PROJECT": "Demo Stand"},
{"DEMO_ACTOR": "alice"},
{"ENV_FILE": str(Path(self.directory.name) / "missing.env")},
)
for overrides in cases:
with self.subTest(overrides=overrides):
result = self.run_script("reset", **overrides)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertEqual(self.calls(), [])
def test_a_volume_without_the_demo_label_is_never_used(self):
for action in ("seed", "reset"):
with self.subTest(action=action):
result = self.run_script(action, STUB_LABEL="")
self.assertEqual(result.returncode, 2, result.stderr)
self.assertIn("was not created by the demo overlay", result.stderr)
self.assertFalse([call for call in self.calls() if call.startswith("compose")])
def test_reset_stops_before_down_when_the_check_refuses(self):
result = self.run_script("reset", STUB_CHECK_RESET="2")
self.assertEqual(result.returncode, 2, result.stderr)
self.assertIn("nothing was deleted", result.stderr)
calls = self.calls()
self.assertTrue(any(" check-reset" in call for call in calls))
self.assertFalse([call for call in calls if " down" in call])
def test_reset_discards_only_the_demo_project_and_seeds_again(self):
result = self.run_script("reset")
self.assertEqual(result.returncode, 0, result.stderr)
compose_calls = [call for call in self.calls() if call.startswith("compose")]
down = [call for call in compose_calls if " down --volumes" in call]
self.assertEqual(len(down), 1)
for call in compose_calls:
self.assertIn("-p lincodex-demo-test ", call)
self.assertIn("docker-compose.demo.yml", call)
self.assertLess(compose_calls.index(next(call for call in compose_calls if " check-reset" in call)), compose_calls.index(down[0]))
self.assertIn(" seed --actor operator:demo-seed", compose_calls[-2])
self.assertTrue(compose_calls[-1].endswith(" inventory"))
def test_down_keeps_the_volumes(self):
result = self.run_script("down")
self.assertEqual(result.returncode, 0, result.stderr)
compose_calls = [call for call in self.calls() if call.startswith("compose")]
self.assertEqual(len(compose_calls), 1)
self.assertTrue(compose_calls[0].endswith(" down"))
def render_demo(project="lincodex-demo-render"):
environment = dict(
os.environ,
APP_PROJECT=project,
APP_NETWORK=f"{project}_default",
APP_STORAGE_NETWORK=f"{project}_storage",
APP_HTTP_PORT="8090",
APP_SUBNET="172.29.84.0/24",
APP_FRONTEND_IP="172.29.84.10",
IDENTITY_KEY_SECRET="render-only-identity-key-secret",
DEMO_ACCOUNT_PASSWORD="render-only-demo-account-password",
DEMO_MODE="isolated",
)
environment.pop("APP_HTTP_BIND", None)
command = [
DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project,
"-f", str(DEPLOY / "docker" / "docker-compose.yml"), "-f", str(DEPLOY / "docker" / "docker-compose.demo.yml"),
"--profile", "demo-seed", "config", "--format", "json",
]
result = subprocess.run(command, capture_output=True, text=True, env=environment, check=False)
if result.returncode != 0:
raise AssertionError(f"docker compose config failed: {result.stderr}")
return json.loads(result.stdout)
class DemoOverlayTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if shutil.which(DOCKER) is None:
raise unittest.SkipTest("docker CLI is not available")
cls.rendered = render_demo()
def test_only_the_frontend_is_published_on_loopback(self):
published = {name: service["ports"] for name, service in self.rendered["services"].items() if service.get("ports")}
self.assertEqual(list(published), ["frontend"])
for port in published["frontend"]:
self.assertEqual(port["host_ip"], "127.0.0.1")
self.assertEqual(port["published"], "8090")
def test_the_seed_reaches_only_the_default_network(self):
seed = self.rendered["services"]["demo-seed"]
self.assertEqual(seed["profiles"], ["demo-seed"])
self.assertEqual(list(seed["networks"]), ["default"])
self.assertEqual(seed["build"]["dockerfile"], "Dockerfile.demo-seed")
self.assertTrue(seed["read_only"])
self.assertEqual(seed["environment"]["DEMO_MODE"], "isolated")
def test_volumes_carry_the_demo_label_and_the_project_name(self):
for name, volume in self.rendered["volumes"].items():
with self.subTest(volume=name):
self.assertEqual(volume["labels"]["org.lincodex.demo-mode"], "isolated")
self.assertTrue(volume["name"].startswith("lincodex-demo-render_"))
def test_the_demo_backend_assigns_synthetic_categories(self):
backend = self.rendered["services"]["backend"]
self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true")
self.assertEqual(backend["labels"]["org.lincodex.demo-mode"], "isolated")
def test_release_and_ordinary_images_never_contain_the_seed(self):
for dockerfile in ("Dockerfile", "Dockerfile.e2e"):
self.assertNotIn("demo-seed", (ROOT / "backend" / dockerfile).read_text())
if __name__ == "__main__":
unittest.main()