fix(docker): add missing certs.sh COPY to backend/all-in-one Dockerfile

Backend entrypoint sources certs.sh for CA certificate installation,
but the file was never copied into the Docker image — causing
container crash loop on startup (regression in 7f932610).

Changes:
- docker/backend.Dockerfile, docker/all-in-one.Dockerfile: COPY certs.sh
- docker/backend.entrypoint.sh: remove dead install_llm_ca_certs,
  install_certificates (replaced by docker/certs.sh); update @INVARIANT
- backend/src/core/ssl.py: fix describe_context() to report actual
  system cert count (SSLContext.capath attr does not exist in Python 3)
- __tests__: rewrite stale tests asserting LLM_SSL_VERIFY=false →
  verify=False; behaviour is permanently removed — always CERT_REQUIRED
- backend/tests/integration/test_backend_container.py [new]: 5 tests
  verifying certs.sh presence, sourceability, and full-stack smoke
  (testcontainers PG → entrypoint → migrations → health)
- conftest.py: restore health-wait loop and fixtures in superset_container
- ADR-0009, README.md, scripts, .env: align docs with centralized SSL
This commit is contained in:
2026-07-07 00:58:41 +03:00
parent aafd89f2c7
commit 702ee25ae4
12 changed files with 645 additions and 371 deletions

View File

@@ -485,11 +485,11 @@ def superset_container(request, superset_db_url, superset_secret_key, superset_a
key_pem = ca_chain["server_key_encrypted"]
key_pass = ca_chain["server_key_passphrase"]
key_b64 = base64.b64encode(key_pem.encode()).decode()
_write_certs = f"echo '{fullchain_b64}' | base64 -d > /tmp/server.crt && echo '{key_b64}' | base64 -d > /tmp/server.key"
_decrypt_key = f"export SSL_KEY_PASSPHRASE='{key_pass}' && openssl rsa -in /tmp/server.key -passin env:SSL_KEY_PASSPHRASE -out /tmp/server.key 2>/dev/null; if [ $? -ne 0 ]; then echo 'ERROR: Failed to decrypt private key with SSL_KEY_PASSPHRASE'; exit 1; fi"
_write_certs = f'echo "{fullchain_b64}" | base64 -d > /tmp/server.crt && echo "{key_b64}" | base64 -d > /tmp/server.key'
_decrypt_key = f'export SSL_KEY_PASSPHRASE="{key_pass}" && openssl rsa -in /tmp/server.key -passin env:SSL_KEY_PASSPHRASE -out /tmp/server.key 2>/dev/null; if [ $? -ne 0 ]; then echo "ERROR: Failed to decrypt private key with SSL_KEY_PASSPHRASE"; exit 1; fi'
else:
key_b64 = base64.b64encode(ca_chain["server_key"].encode()).decode()
_write_certs = f"echo '{fullchain_b64}' | base64 -d > /tmp/server.crt && echo '{key_b64}' | base64 -d > /tmp/server.key"
_write_certs = f'echo "{fullchain_b64}" | base64 -d > /tmp/server.crt && echo "{key_b64}" | base64 -d > /tmp/server.key'
_decrypt_key = ""
_protocol = "https"
@@ -537,6 +537,119 @@ def superset_container(request, superset_db_url, superset_secret_key, superset_a
if use_tls and _write_certs:
_decrypt_prefix = f"{_decrypt_key} && " if _decrypt_key else ""
web_cmd = f"sh -c 'python -m pip install psycopg2-binary -q && {_write_certs} && {_decrypt_prefix}{_bootstrap_config}{_export_config} && {_superset_run}'"
else:
web_cmd = f"sh -c 'python -m pip install psycopg2-binary -q && {_bootstrap_config}{_export_config} && {_superset_run}'"
superset.with_command(web_cmd)
superset.with_exposed_ports(8088)
superset.start()
# Store protocol on the container object for superset_url fixture
superset._ss_protocol = _protocol
# Wait for the /health endpoint to respond
host = superset.get_container_host_ip()
port = superset.get_exposed_port(8088)
health_url = f"{_protocol}://{host}:{port}/health"
deadline = time.time() + 90
last_error = None
while time.time() < deadline:
try:
# verify=False in TLS mode because the custom CA hasn't been installed yet
resp = requests.get(health_url, timeout=3, verify=False)
if resp.status_code == 200:
break
except requests.RequestException as e:
last_error = e
time.sleep(2)
else:
logs = superset.get_logs()
superset.stop()
raise TimeoutError(f"Superset did not become healthy within 90s. Last error: {last_error}\nContainer logs:\n{logs}")
yield superset
superset.stop()
# #endregion superset_container
# #region superset_url [C:1] [TYPE Fixture]
# @BRIEF Function-scoped — base URL of the running Superset container (auto-detects http/https).
@pytest.fixture
def superset_url(superset_container):
host = superset_container.get_container_host_ip()
port = superset_container.get_exposed_port(8088)
protocol = getattr(superset_container, "_ss_protocol", "http")
return f"{protocol}://{host}:{port}"
# #endregion superset_url
# #region superset_admin_headers [C:2] [TYPE Fixture]
# @BRIEF Function-scoped — authenticated session headers for Superset admin API calls.
@pytest.fixture
def superset_admin_headers(superset_url, superset_admin_password):
"""Log in as admin and return headers with CSRF token and session cookie."""
session = requests.Session()
# Step 1: Get CSRF token from login page
login_url = f"{superset_url}/login/"
resp = session.get(login_url, timeout=10)
resp.raise_for_status()
csrf_token = None
if "csrf_token" in resp.text:
import re
match = re.search(r'csrf_token"\s*:\s*"([^"]+)"', resp.text)
if match:
csrf_token = match.group(1)
# Step 2: Submit login form
resp = session.post(
login_url,
data={
"username": "admin",
"password": superset_admin_password,
"csrf_token": csrf_token or "",
},
headers={"Referer": login_url},
timeout=10,
)
resp.raise_for_status()
return session
# #endregion superset_admin_headers
# ── JWT-based Superset Fixtures ────────────────────────────────────
# ADR-0012: после установки psycopg2 + superset_config.py + Docker bridge IP,
# JWT-авторизация (/api/v1/security/login) работает в тестовом контейнере.
# #region superset_jwt_headers [C:2] [TYPE Fixture]
# @BRIEF Function-scoped — JWT Bearer token headers for Superset REST API.
# @POST Returns dict with Authorization: Bearer <access_token>.
@pytest.fixture
def superset_jwt_headers(superset_url, superset_admin_password):
"""Obtain JWT access token from the running Superset container."""
resp = requests.post(
f"{superset_url}/api/v1/security/login",
json={
"username": "admin",
"password": superset_admin_password,
"provider": "db",
},
timeout=10,
)
resp.raise_for_status()
data = resp.json()
access_token = data["access_token"]

View File

@@ -0,0 +1,312 @@
# #region TestBackendContainer [C:3] [TYPE Module] [SEMANTICS test,integration,backend,container,docker,entrypoint,certs]
# @BRIEF Integration tests for the superset-tools-backend Docker image:
# verifies entrypoint + certs.sh work correctly inside the container.
# @RELATION BINDS_TO -> [docker/backend.Dockerfile]
# @RELATION BINDS_TO -> [docker/certs.sh]
# @RELATION BINDS_TO -> [docker/backend.entrypoint.sh]
# @RELATION CALLS -> [TestSupersetTlsCustomCA]
# @RATIONALE In 0.5.0 release, backend entrypoint crashed with
# "/app/entrypoint.sh: line 264: /app/certs.sh: No such file or directory"
# because docker/backend.Dockerfile was missing COPY for certs.sh.
# Existing testcontainers tests only exercise apache/superset containers,
# not the superset-tools backend container. These tests close that gap.
# @TEST_CONTRACT BackendImageCertPaths ->
# /app/certs.sh exists and is readable
# source /app/certs.sh defines install_all_certs, install_ca_to_nss, normalize_cert
# /app/entrypoint.sh exists and is executable
# @TEST_CONTRACT BackendContainerSmoke ->
# docker compose up backend starts successfully
# /api/health/summary responds 200
# Container logs do NOT contain "certs.sh: No such file or directory"
# Container logs do NOT contain "Traceback" or unrecoverable startup error
# @REQUIRES Docker daemon running. --run-integration flag.
"""Integration tests for superset-tools-backend Docker image.
Two test suites:
1. **TestBackendImageCertsSh** — fast (no DB, no compose).
Builds the backend Docker image, runs a container with --entrypoint bash,
and verifies certs.sh is present, sourceable, and all certificate
installation functions are defined.
2. **TestBackendContainerSmoke** — full stack (needs PostgreSQL).
Starts PostgreSQL via testcontainers, deploys backend via docker compose,
waits for the health endpoint, and checks container logs for startup errors.
"""
import os
import re
import subprocess
import time
from pathlib import Path
import pytest
# ── Project paths ────────────────────────────────────────────────────────
PROJECT_ROOT = Path(__file__).resolve().parents[3]
BACKEND_IMAGE = "superset-tools-backend:test-integration"
# ── Fixtures ──────────────────────────────────────────────────────────────
@pytest.fixture(scope="module")
def _backend_image():
"""Build superset-tools-backend:test-integration once per module."""
# Only rebuild if the Dockerfile changed (simple mtime check)
dockerfile = PROJECT_ROOT / "docker" / "backend.Dockerfile"
image_marker = PROJECT_ROOT / "backend" / ".image-built"
if not image_marker.exists() or image_marker.stat().st_mtime < dockerfile.stat().st_mtime:
subprocess.run(
["docker", "build", "-f", str(dockerfile), "-t", BACKEND_IMAGE, str(PROJECT_ROOT)],
check=True,
capture_output=True,
text=True,
timeout=300,
)
image_marker.touch()
return BACKEND_IMAGE
# ══════════════════════════════════════════════════════════════════════════
# TEST 1: Fast — verify certs.sh presence and basic functionality
# ══════════════════════════════════════════════════════════════════════════
class TestBackendImageCertPaths:
"""Fast checks: certs.sh exists, is sourceable, defines all functions.
These tests run in ~10s without PostgreSQL or docker compose.
They catch the 'certs.sh: No such file or directory' failure mode.
"""
@pytest.fixture(autouse=True)
def _image(self, _backend_image):
pass
# ── helpers ─────────────────────────────────────────────────────
@staticmethod
def _run_bash(command: str) -> subprocess.CompletedProcess:
return subprocess.run(
["docker", "run", "--rm", "--entrypoint", "bash", BACKEND_IMAGE, "-c", command],
capture_output=True,
text=True,
timeout=30,
)
# ── tests ───────────────────────────────────────────────────────
# #region test_certs_sh_exists [C:1] [TYPE Function] [SEMANTICS test,integration,certs]
# @BRIEF /app/certs.sh must exist and be readable.
def test_certs_sh_exists(self):
r = self._run_bash("test -f /app/certs.sh && test -r /app/certs.sh")
assert r.returncode == 0, f"File exists: {r.returncode == 0}, stderr: {r.stderr[:200]}"
# #endregion test_certs_sh_exists
# #region test_entrypoint_sh_exists [C:1] [TYPE Function] [SEMANTICS test,integration,entrypoint]
# @BRIEF /app/entrypoint.sh must exist and be executable.
def test_entrypoint_sh_exists(self):
r = self._run_bash("test -f /app/entrypoint.sh && test -x /app/entrypoint.sh")
assert r.returncode == 0, f"File: /app/entrypoint.sh, stderr: {r.stderr[:200]}"
# #endregion test_entrypoint_sh_exists
# #region test_certs_sh_source_defines_functions [C:2] [TYPE Function] [SEMANTICS test,integration,certs]
# @BRIEF sourcing /app/certs.sh defines install_all_certs, install_ca_to_nss, normalize_cert.
def test_certs_sh_source_defines_functions(self):
r = self._run_bash("source /app/certs.sh && declare -F install_all_certs >/dev/null 2>&1 && echo -n 'install_all_certs '; declare -F install_ca_to_nss >/dev/null 2>&1 && echo -n 'install_ca_to_nss '; declare -F normalize_cert >/dev/null 2>&1 && echo -n 'normalize_cert'")
assert "install_all_certs" in r.stdout, f"install_all_certs not defined:\n{r.stderr}"
assert "install_ca_to_nss" in r.stdout, f"install_ca_to_nss not defined:\n{r.stderr}"
assert "normalize_cert" in r.stdout, f"normalize_cert not defined:\n{r.stderr}"
# #endregion test_certs_sh_source_defines_functions
# #region test_entrypoint_sources_certs_sh_ok [C:2] [TYPE Function] [SEMANTICS test,integration,entrypoint]
# @BRIEF Running the real entrypoint script (without DB) must not crash on source certs.sh.
# We pass a short DB wait timeout so it fails fast instead of retrying 30 times.
# The certs.sh sourcing happens BEFORE the DB wait loop.
def test_entrypoint_sources_certs_sh_ok(self):
r = subprocess.run(
[
"docker",
"run",
"--rm",
"-e",
"POSTGRES_HOST=does-not-exist",
"-e",
"POSTGRES_USER=test",
"-e",
"POSTGRES_PASSWORD=test",
"-e",
"POSTGRES_DB=test",
# Reduce wait time — if certs.sh source succeeds, the error
# will be about DB connection, not certs.sh
"--entrypoint",
"bash",
BACKEND_IMAGE,
"-c",
"timeout 5 /app/entrypoint.sh 2>&1 || true",
],
capture_output=True,
text=True,
timeout=15,
)
# The certs.sh source comes BEFORE DB wait.
# If certs.sh is missing, the output MUST contain "No such file or directory".
# If certs.sh loads OK, the output should show DB connection error OR cert install.
assert re.search(r"No such file or directory.*certs\.sh|certs\.sh.*No such file or directory", r.stdout + r.stderr) is None, f"certs.sh not found! Entrypoint tried to source missing file:\nSTDOUT:\n{r.stdout[:2000]}\nSTDERR:\n{r.stderr[:2000]}"
# #endregion test_entrypoint_sources_certs_sh_ok
# ══════════════════════════════════════════════════════════════════════════
# TEST 2: Full stack — docker compose up backend + health check
# ══════════════════════════════════════════════════════════════════════════
@pytest.mark.skipif(
not os.environ.get("E2E_BACKEND_CONTAINER"),
reason="Skipped by default — set E2E_BACKEND_CONTAINER=1 to run full-stack test",
)
@pytest.mark.usefixtures("_backend_image")
class TestBackendContainerSmoke:
"""Full-stack smoke test: deploy backend container via docker compose
with PostgreSQL, wait for health endpoint, verify container logs.
Requires: set E2E_BACKEND_CONTAINER=1 (takes 30-60s, needs PostgreSQL).
"""
# #region test_backend_health [C:3] [TYPE Function] [SEMANTICS test,integration,smoke]
# @BRIEF docker run (host network) backend with testcontainers PostgreSQL,
# wait for health, check container logs for startup errors.
# @PRE Docker daemon running. Port 8000 must be free on the host.
# @POST Backend health endpoint responds 200. Container logs show no certs.sh errors.
# @SIDE_EFFECT Starts/stops PostgreSQL and backend Docker containers.
def test_backend_health(self):
import time as time_module
import urllib.request
import urllib.error
# ── Use host network mode so backend can reach PG on localhost ──
from testcontainers.postgres import PostgresContainer
pg = PostgresContainer(
"postgres:16-alpine",
dbname="ss_tools",
username="postgres",
password="postgres",
)
pg.start()
pg_port = pg.get_exposed_port(5432)
# ── Start backend container (host network) ──
container_name = f"ss-tools-integration-backend-{os.urandom(4).hex()}"
backend_port = "8000"
db_url = f"postgresql://postgres:postgres@127.0.0.1:{pg_port}/ss_tools"
run_cmd = [
"docker",
"run",
"-d",
"--name",
container_name,
"--network",
"host",
"-e",
f"DATABASE_URL={db_url}",
"-e",
"INITIAL_ADMIN_CREATE=true",
"-e",
"INITIAL_ADMIN_USERNAME=admin",
"-e",
"INITIAL_ADMIN_PASSWORD=admin123",
"-e",
"INITIAL_ADMIN_EMAIL=admin@example.com",
"-e",
"ENABLE_BELIEF_STATE_LOGGING=true",
"-e",
"TASK_LOG_LEVEL=ERROR",
"-e",
"CERTS_PATH=/opt/certs",
BACKEND_IMAGE,
]
r = subprocess.run(run_cmd, capture_output=True, text=True, timeout=30)
if r.returncode != 0:
pg.stop()
pytest.fail(f"docker run failed:\nSTDERR: {r.stderr[:2000]}")
container_id = r.stdout.strip()
container_removed = False
def _cleanup(rm_container=True):
nonlocal container_removed
if rm_container and not container_removed:
subprocess.run(["docker", "rm", "-f", container_id], capture_output=True, timeout=10)
container_removed = True
try:
pg.stop()
except Exception:
pass
try:
# ── Wait for health ──
health_url = f"http://127.0.0.1:{backend_port}/api/health/summary"
deadline = time_module.time() + 60
last_error = ""
while time_module.time() < deadline:
try:
hr = subprocess.run(
["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--connect-timeout", "2", "--max-time", "4", health_url],
capture_output=True,
text=True,
timeout=10,
)
http_code = hr.stdout.strip()
if http_code in ("200", "401", "403"):
break
last_error = f"HTTP {http_code}"
except subprocess.TimeoutExpired:
last_error = "curl timeout"
except Exception as e:
last_error = str(e)
time_module.sleep(2)
else:
# Timeout — dump container logs
logs_r = subprocess.run(
["docker", "logs", container_id, "--tail", "60"],
capture_output=True,
text=True,
timeout=10,
)
full_log = logs_r.stdout[:5000] + logs_r.stderr[:2000]
_cleanup(rm_container=True)
pytest.fail(f"Backend health check failed after 60s.\nLast error: {last_error}\nContainer logs:\n{full_log}")
# ── Check container logs for startup errors ──
logs_r = subprocess.run(
["docker", "logs", container_id],
capture_output=True,
text=True,
timeout=10,
)
combined_logs = logs_r.stdout + logs_r.stderr
if re.search(r"No such file or directory.*certs\.sh|certs\.sh.*No such file", combined_logs):
_cleanup(rm_container=True)
pytest.fail(f"certs.sh not found! Entrypoint crashed:\n{combined_logs[:3000]}")
if re.search(r"Traceback|Error.*certs\.sh", combined_logs):
_cleanup(rm_container=True)
pytest.fail(f"Entrypoint crash detected:\n{combined_logs[:3000]}")
finally:
_cleanup(rm_container=True)
# #endregion test_backend_health
# #endregion TestBackendContainer