from pathlib import Path import pytest from app.core.config import Settings, _default_env_files def test_default_env_files_include_repo_root_env(): env_files = {Path(path) for path in _default_env_files()} repo_root = Path(__file__).resolve().parents[3] server_root = Path(__file__).resolve().parents[2] assert repo_root / ".env" in env_files assert server_root / ".env" in env_files # Regression: the EC2 deploy migration step crashed at boot with # ``SettingsError: error parsing value for field "TRUSTED_PROXY_IPS"``. # A ``list[str]`` field is "complex", so pydantic-settings JSON-decodes # the env value at the SOURCE level, BEFORE any ``mode="before"`` # validator — so a value from an env_file (``a,b`` or a Compose-mangled # ``[a,b]``) is not valid JSON and raises at boot. The fix is ``NoDecode`` # on the field so the raw string reaches the validator. # # This test builds a real ``Settings()`` with the env var set (the exact # path that crashed prod) — a validator-only unit test would NOT catch a # regression of the source-level decode. _REQUIRED_ENV = { "DATABASE_URL": "mysql+asyncmy://u:p@localhost/helix", "DATABASE_URL_SYNC": "mysql+pymysql://u:p@localhost/helix", "JWT_SECRET_KEY": "x" * 40, "GOOGLE_CLIENT_ID": "cid", } @pytest.mark.parametrize("raw,expected", [ ("127.0.0.1,::1,172.28.0.0/16", ["127.0.0.1", "::1", "172.28.0.0/16"]), ('["127.0.0.1","::1"]', ["127.0.0.1", "::1"]), ("[127.0.0.1,::1]", ["127.0.0.1", "::1"]), # Compose-mangled JSON ("127.0.0.1", ["127.0.0.1"]), (" 127.0.0.1 , ::1 ", ["127.0.0.1", "::1"]), ]) def test_trusted_proxy_ips_env_does_not_crash_boot(monkeypatch, raw, expected): for k, v in _REQUIRED_ENV.items(): monkeypatch.setenv(k, v) monkeypatch.setenv("TRUSTED_PROXY_IPS", raw) # ``_env_file=None`` so a developer's local .env can't shadow the test. s = Settings(_env_file=None) assert s.TRUSTED_PROXY_IPS == expected def test_trusted_proxy_ips_default_is_loopback(): # Required fields via init kwargs so the real env isn't polluted. s = Settings(_env_file=None, **_REQUIRED_ENV) assert s.TRUSTED_PROXY_IPS == ["127.0.0.1", "::1"] def test_cors_origins_accepts_production_ssm_json_array(monkeypatch): for key, value in _REQUIRED_ENV.items(): monkeypatch.setenv(key, value) monkeypatch.setenv("CORS_ORIGINS", '["https://helix.pingcap.net"]') settings = Settings(_env_file=None) assert settings.CORS_ORIGINS == ["https://helix.pingcap.net"]