Files
planet/backend/tests/test_production_hardening.py
T

572 lines
20 KiB
Python

"""Tests for production deployment configs, security hardening, and health probes."""
from __future__ import annotations
import json
import os
from pathlib import Path
import shlex
import shutil
import stat
import subprocess
import sys
from cryptography.fernet import Fernet
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
import pytest
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
import yaml
from app.api.v1 import settings as settings_api
from app.api.v1.auth import _LOCAL_LOGIN_FAILURES, _client_ip, router as auth_router
from app.core import secret_crypto, security
from app.core.config import Settings, settings, validate_production_security
from app.db.session import ensure_default_admin_user, get_db, seed_default_datasources
from app.main import app as main_app
from app.models.datasource import DataSource
from app.models.system_setting import SystemSetting
from app.models.user import User
REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
class _AsyncSQLiteSession:
"""AsyncSession-compatible test adapter over an isolated in-memory SQLite Session."""
def __init__(self, session: Session):
self._session = session
def get_bind(self):
return self._session.get_bind()
def add(self, instance) -> None:
self._session.add(instance)
def add_all(self, instances) -> None:
self._session.add_all(instances)
async def get(self, entity, ident):
return self._session.get(entity, ident)
async def execute(self, statement, params=None):
if params is not None:
return self._session.execute(statement, params)
return self._session.execute(statement)
async def scalar(self, statement):
return self._session.scalar(statement)
async def scalars(self, statement):
return self._session.scalars(statement)
async def flush(self) -> None:
self._session.flush()
async def commit(self) -> None:
self._session.commit()
async def rollback(self) -> None:
self._session.rollback()
async def refresh(self, instance) -> None:
self._session.refresh(instance)
def test_deploy_compose_fixes_ai_url_frontend_target_volumes_and_ports():
compose = yaml.safe_load((REPO_ROOT / "docker-compose.deploy.yml").read_text(encoding="utf-8"))
services = compose["services"]
backend = services["backend"]
backend_env = backend["environment"]
assert "AI_PROVIDER_SERVICE_URL" in backend_env
assert "AI_PROVIDER_BASE_URL" not in backend_env
assert "ports" not in backend
assert "8000" in [str(item) for item in backend.get("expose", [])]
assert "/health/ready" in " ".join(backend["healthcheck"]["test"])
volume_targets = {str(item).split(":", 1)[1] for item in backend.get("volumes", [])}
assert "/app/backend/data/earth-brand" in volume_targets
assert "/root/.cache/planet/downloads" in volume_targets
admin = services["admin"]
assert "full" in str(admin["build"]["args"]["PLANET_FRONTEND_TARGET"])
worker = services["worker"]
assert "split" in worker.get("profiles", [])
assert worker["environment"]["PLANET_ROLE"] == "worker"
for name, service in services.items():
assert service.get("logging", {}).get("driver") == "json-file", name
assert "mem_limit" in service, name
def test_helm_templates_and_values_fix_ai_provider_and_probes():
configmap_text = (
REPO_ROOT / "deploy/helm/planet/templates/configmap.yaml"
).read_text(encoding="utf-8")
assert "AI_PROVIDER_SERVICE_URL" in configmap_text
assert "AI_BASE_URL:" not in configmap_text
assert "AI_PROVIDER_API:" not in configmap_text
backend_yaml_text = (
REPO_ROOT / "deploy/helm/planet/templates/backend.yaml"
).read_text(encoding="utf-8")
assert "/health/ready" in backend_yaml_text
assert "/health/live" in backend_yaml_text
assert "startupProbe:" in backend_yaml_text
worker_yaml_text = (
REPO_ROOT / "deploy/helm/planet/templates/worker.yaml"
).read_text(encoding="utf-8")
assert ".Values.worker.enabled" in worker_yaml_text
assert "app.worker" in worker_yaml_text
values = yaml.safe_load(
(REPO_ROOT / "deploy/helm/planet/values.yaml").read_text(encoding="utf-8")
)
assert values["backend"]["env"]["APP_ENV"] == "production"
assert "limits" in values["backend"]["resources"]
assert "limits" in values["frontend"]["resources"]
assert "limits" in values["aiprovider"]["resources"]
def test_nginx_template_sets_timeouts_streaming_and_upload_limits():
nginx_text = (REPO_ROOT / "frontend/nginx.conf.template").read_text(encoding="utf-8")
assert "client_max_body_size 25m;" in nginx_text
assert "proxy_read_timeout 180s;" in nginx_text
assert "proxy_buffering off;" in nginx_text
assert "proxy_read_timeout 3600s;" in nginx_text
assert "/api/health/ready" in nginx_text
assert "/api/health/live" in nginx_text
assert "X-Content-Type-Options" in nginx_text
def test_validate_production_security_enforces_strong_defaults(monkeypatch):
weak_cfg = Settings(
APP_ENV="production",
SECRET_KEY="short-secret",
ACCESS_TOKEN_EXPIRE_MINUTES=0,
REFRESH_TOKEN_EXPIRE_DAYS=0,
CORS_ORIGINS=["*"],
AI_PROVIDER_SERVICE_URL="http://aiprovider:8010",
AI_PROVIDER_SERVICE_TOKEN="",
)
with pytest.raises(RuntimeError, match="Production security validation failed"):
validate_production_security(weak_cfg)
strong_cfg = Settings(
APP_ENV="production",
SECRET_KEY="x" * 40,
ACCESS_TOKEN_EXPIRE_MINUTES=60,
REFRESH_TOKEN_EXPIRE_DAYS=7,
CORS_ORIGINS=["https://planet.example.com"],
AI_PROVIDER_SERVICE_URL="http://aiprovider:8010",
AI_PROVIDER_SERVICE_TOKEN="internal-token-123456",
)
validate_production_security(strong_cfg)
from aiprovider import main as aiprovider_main
monkeypatch.setattr(aiprovider_main.settings, "APP_ENV", "production")
monkeypatch.setattr(aiprovider_main.settings, "AI_PROVIDER_SERVICE_TOKEN", "")
with pytest.raises(RuntimeError, match="AI_PROVIDER_SERVICE_TOKEN"):
aiprovider_main.validate_provider_security()
@pytest.mark.asyncio
async def test_secret_crypto_roundtrip_and_database_storage(monkeypatch):
monkeypatch.setattr(settings, "SETTINGS_ENCRYPTION_KEY", "test-master-passphrase-2026")
engine = create_engine("sqlite://")
SystemSetting.__table__.create(engine)
with Session(engine) as sync_session:
db = _AsyncSQLiteSession(sync_session)
await settings_api.save_setting_payload(
db,
"smtp",
{"host": "smtp.example.com", "port": 587, "password": "smtp-secret-value"},
)
raw_record = sync_session.execute(
select(SystemSetting).where(SystemSetting.category == "smtp")
).scalar_one()
assert raw_record.payload["password"].startswith(secret_crypto.ENCRYPTED_PREFIX)
loaded = await settings_api.get_setting_payload(db, "smtp")
assert loaded["password"] == "smtp-secret-value"
legacy_decrypted = secret_crypto.decrypt_setting_payload(
"smtp", {"host": "smtp.example.com", "password": "legacy-plaintext"}
)
assert legacy_decrypted["password"] == "legacy-plaintext"
engine.dispose()
@pytest.mark.asyncio
async def test_auth_refresh_logout_revocation_rate_limit_and_redis_fallback(monkeypatch):
security._LOCAL_REVOKED_TOKENS.clear()
_LOCAL_LOGIN_FAILURES.clear()
class BrokenRedis:
async def exists(self, *_args):
raise ConnectionError("redis down")
async def sismember(self, *_args):
raise ConnectionError("redis down")
async def set(self, *_args, **_kwargs):
raise ConnectionError("redis down")
async def get(self, *_args):
raise ConnectionError("redis down")
async def incr(self, *_args):
raise ConnectionError("redis down")
async def delete(self, *_args):
raise ConnectionError("redis down")
monkeypatch.setattr(
security._AsyncRedisClient, "get_client", classmethod(lambda cls: BrokenRedis())
)
monkeypatch.setattr(settings, "LOGIN_RATE_LIMIT_MAX_ATTEMPTS", 2)
monkeypatch.setattr(settings, "LOGIN_RATE_LIMIT_WINDOW_SECONDS", 60)
engine = create_engine("sqlite://")
User.__table__.create(engine)
with Session(engine) as seed_session:
seed_session.add(
User(
username="ops_user",
email="ops@example.com",
password_hash=security.get_password_hash("CorrectPass123!"),
role="admin",
is_active=True,
email_verified=True,
)
)
seed_session.commit()
test_app = FastAPI()
test_app.include_router(auth_router, prefix="/auth")
async def override_db():
with Session(engine) as sync_session:
yield _AsyncSQLiteSession(sync_session)
test_app.dependency_overrides[get_db] = override_db
async with AsyncClient(transport=ASGITransport(app=test_app), base_url="http://test") as client:
for _ in range(2):
fail_resp = await client.post(
"/auth/login", data={"username": "ops_user", "password": "wrong"}
)
assert fail_resp.status_code == 401
blocked_resp = await client.post(
"/auth/login", data={"username": "ops_user", "password": "CorrectPass123!"}
)
assert blocked_resp.status_code == 429
assert int(blocked_resp.headers["Retry-After"]) >= 1
_LOCAL_LOGIN_FAILURES.clear()
login_resp = await client.post(
"/auth/login", data={"username": "ops_user", "password": "CorrectPass123!"}
)
assert login_resp.status_code == 200
tokens = login_resp.json()
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
me_resp = await client.get("/auth/me", headers={"Authorization": f"Bearer {access_token}"})
assert me_resp.status_code == 200
bad_refresh = await client.post(
"/auth/refresh", headers={"Authorization": f"Bearer {access_token}"}
)
assert bad_refresh.status_code == 401
ok_refresh = await client.post(
"/auth/refresh", headers={"Authorization": f"Bearer {refresh_token}"}
)
assert ok_refresh.status_code == 200
new_access = ok_refresh.json()["access_token"]
assert new_access != access_token
logout_resp = await client.post(
"/auth/logout",
headers={"Authorization": f"Bearer {new_access}"},
json={"refresh_token": refresh_token},
)
assert logout_resp.status_code == 200
revoked_me = await client.get("/auth/me", headers={"Authorization": f"Bearer {new_access}"})
assert revoked_me.status_code == 401
revoked_refresh = await client.post(
"/auth/refresh", headers={"Authorization": f"Bearer {refresh_token}"}
)
assert revoked_refresh.status_code == 401
security._LOCAL_REVOKED_TOKENS.clear()
_LOCAL_LOGIN_FAILURES.clear()
engine.dispose()
@pytest.mark.asyncio
async def test_seeding_preserves_custom_datasource_schedule_and_production_admin(monkeypatch):
engine = create_engine("sqlite://")
DataSource.__table__.create(engine)
User.__table__.create(engine)
with Session(engine) as sync_session:
db = _AsyncSQLiteSession(sync_session)
await seed_default_datasources(db)
first = sync_session.execute(select(DataSource).limit(1)).scalar_one()
first.frequency_minutes = 777
first.priority = "P9"
first.is_active = False
sync_session.commit()
await seed_default_datasources(db)
reloaded = sync_session.get(DataSource, first.id)
assert reloaded.frequency_minutes == 777
assert reloaded.priority == "P9"
assert reloaded.is_active is False
monkeypatch.setattr(settings, "APP_ENV", "production")
monkeypatch.setattr(settings, "SEED_DEFAULT_DEV_USERS", None)
monkeypatch.setattr(settings, "INITIAL_ADMIN_USERNAME", "prod_root")
monkeypatch.setattr(settings, "INITIAL_ADMIN_PASSWORD", "ProdStrongPass!123")
monkeypatch.setattr(settings, "INITIAL_ADMIN_EMAIL", "root@planet.example.com")
await ensure_default_admin_user(db)
usernames = {row[0] for row in sync_session.execute(select(User.username)).all()}
assert usernames == {"prod_root"}
engine.dispose()
@pytest.mark.asyncio
async def test_scheduler_jobs_requires_auth_and_health_ready_checks_deps(monkeypatch):
async with AsyncClient(transport=ASGITransport(app=main_app), base_url="http://test") as client:
unauth_jobs = await client.get("/api/v1/scheduler/jobs")
assert unauth_jobs.status_code in {401, 403}
live_resp = await client.get("/health/live")
assert live_resp.status_code == 200
assert live_resp.json()["status"] == "alive"
class HealthySession:
async def __aenter__(self):
return self
async def __aexit__(self, *_args):
return False
async def execute(self, *_args):
return None
class HealthyRedis:
async def ping(self):
return True
monkeypatch.setattr("app.main.async_session_factory", HealthySession)
monkeypatch.setattr(
security._AsyncRedisClient, "get_client", classmethod(lambda cls: HealthyRedis())
)
async with AsyncClient(transport=ASGITransport(app=main_app), base_url="http://test") as client:
ready_ok = await client.get("/health/ready")
assert ready_ok.status_code == 200
assert ready_ok.json()["checks"] == {"database": "ok", "redis": "ok"}
class FailingRedis:
async def ping(self):
raise ConnectionError("down")
monkeypatch.setattr(
security._AsyncRedisClient, "get_client", classmethod(lambda cls: FailingRedis())
)
async with AsyncClient(transport=ASGITransport(app=main_app), base_url="http://test") as client:
ready_fail = await client.get("/health/ready")
assert ready_fail.status_code == 503
assert ready_fail.json()["checks"]["redis"] == "error"
def test_backend_dockerfile_and_dockerignore_ship_db_migrate():
dockerfile = (REPO_ROOT / "backend/Dockerfile").read_text(encoding="utf-8")
dockerignore = (REPO_ROOT / ".dockerignore").read_text(encoding="utf-8")
assert "COPY scripts/db_migrate.py /app/scripts/db_migrate.py" in dockerfile
assert "!scripts/db_migrate.py" in dockerignore
def test_planet_sh_deploy_backup_migrate_cli_and_env_generation(tmp_path: Path):
if shutil.which("zsh") is None:
pytest.skip("zsh not available")
for subcmd in ("deploy", "backup", "migrate"):
res = subprocess.run(
["zsh", str(REPO_ROOT / "planet.sh"), subcmd, "--help"],
capture_output=True,
text=True,
timeout=15,
check=False,
)
assert res.returncode == 0, res.stderr
env_path = tmp_path / ".env.deploy"
zsh_script = "\n".join(
[
"set -e",
f"SCRIPT_DIR={shlex.quote(str(REPO_ROOT))}",
"log_step() { :; }",
"log_warn() { :; }",
"log_error() { echo \"$1\" >&2; }",
"log_success() { :; }",
"log_note() { :; }",
f"source {shlex.quote(str(REPO_ROOT / 'scripts/lib/deploy.zsh'))}",
f"deploy_init_env {shlex.quote(str(env_path))} 0 < /dev/null",
f"deploy_validate_env_file {shlex.quote(str(env_path))}",
]
)
gen = subprocess.run(
["zsh", "-f"],
input=zsh_script,
capture_output=True,
text=True,
timeout=15,
check=False,
env={**os.environ, "INITIAL_ADMIN_PASSWORD": "StrongProdPassword!1"},
)
assert gen.returncode == 0, gen.stderr
assert env_path.exists()
assert stat.S_IMODE(env_path.stat().st_mode) == 0o600
parsed = {}
for line in env_path.read_text(encoding="utf-8").splitlines():
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1)
parsed[k] = v
assert parsed["APP_ENV"] == "production"
assert len(parsed["SECRET_KEY"]) >= 32
assert parsed["INITIAL_ADMIN_PASSWORD"] == "StrongProdPassword!1"
Fernet(parsed["SETTINGS_ENCRYPTION_KEY"].encode("ascii"))
# Generated file must pass Pydantic Settings + validate_production_security directly.
loaded_cfg = Settings(_env_file=env_path)
validate_production_security(loaded_cfg)
# Weak placeholder file must fail deploy_validate_env_file.
weak_path = tmp_path / ".env.weak"
weak_path.write_text(
"APP_ENV=production\nSECRET_KEY=short\nAI_PROVIDER_SERVICE_TOKEN=change_me\nCORS_ORIGINS=[\"*\"]\n",
encoding="utf-8",
)
weak_check = subprocess.run(
["zsh", "-f"],
input="\n".join(
[
f"SCRIPT_DIR={shlex.quote(str(REPO_ROOT))}",
"log_error() { echo \"$1\" >&2; }",
f"source {shlex.quote(str(REPO_ROOT / 'scripts/lib/deploy.zsh'))}",
f"deploy_validate_env_file {shlex.quote(str(weak_path))}",
]
),
capture_output=True,
text=True,
timeout=15,
check=False,
)
assert weak_check.returncode != 0
def test_planet_sh_dev_cors_builder_includes_electron_and_lan_origins():
if shutil.which("zsh") is None:
pytest.skip("zsh not available")
planet_text = (REPO_ROOT / "planet.sh").read_text(encoding="utf-8")
start = planet_text.index("build_dev_cors_origins_json() {")
end = planet_text.index("\nstart_backend_with_retry()", start)
fn_code = planet_text[start:end]
res = subprocess.run(
["zsh", "-f"],
input="\n".join(
[
"set -e",
fn_code,
"FRONTEND_LAN_ENABLED=1",
"get_recommended_lan_ipv4() { echo 192.168.10.25; }",
"build_dev_cors_origins_json 8000 3000 3000",
]
),
capture_output=True,
text=True,
timeout=10,
check=False,
)
assert res.returncode == 0, res.stderr
origins = json.loads(res.stdout.strip())
assert "http://localhost:3000" in origins
assert "http://127.0.0.1:3000" in origins
assert "planet://earth" in origins
assert "http://192.168.10.25:3000" in origins
assert "http://192.168.10.25:8000" in origins
@pytest.mark.asyncio
async def test_client_ip_trusts_only_private_proxy_rightmost_hop_and_forged_logout_ignored(
monkeypatch,
):
from types import SimpleNamespace
# Trusted proxy peer uses X-Real-IP, or rightmost X-Forwarded-For entry appended by nginx.
trusted_real_req = SimpleNamespace(
client=SimpleNamespace(host="172.18.0.5"),
headers={"X-Real-IP": "198.51.100.42", "X-Forwarded-For": "9.9.9.9, 198.51.100.42"},
)
assert _client_ip(trusted_real_req) == "198.51.100.42"
trusted_xff_req = SimpleNamespace(
client=SimpleNamespace(host="127.0.0.1"),
headers={"X-Forwarded-For": "9.9.9.9, 203.0.113.88"},
)
assert _client_ip(trusted_xff_req) == "203.0.113.88"
# Untrusted direct public peer cannot spoof rate-limit keys via headers.
untrusted_req = SimpleNamespace(
client=SimpleNamespace(host="203.0.113.55"),
headers={"X-Real-IP": "1.1.1.1", "X-Forwarded-For": "8.8.8.8"},
)
assert _client_ip(untrusted_req) == "203.0.113.55"
# Forged / invalid JWT passed to revoke_token must not pollute local revocation cache or Redis.
security._LOCAL_REVOKED_TOKENS.clear()
redis_sets: list[str] = []
class RecordingRedis:
async def set(self, key, *_args, **_kwargs):
redis_sets.append(key)
monkeypatch.setattr(
security._AsyncRedisClient, "get_client", classmethod(lambda cls: RecordingRedis())
)
await security.revoke_token("not-a-valid-jwt-token")
security.blacklist_token("also-invalid-token")
assert len(security._LOCAL_REVOKED_TOKENS) == 0
assert redis_sets == []
def test_helm_backend_deployment_sets_api_role_when_worker_enabled():
backend_yaml_text = (
REPO_ROOT / "deploy/helm/planet/templates/backend.yaml"
).read_text(encoding="utf-8")
assert "{{- if .Values.worker.enabled }}" in backend_yaml_text
assert 'name: PLANET_ROLE' in backend_yaml_text
assert 'value: "api"' in backend_yaml_text