diff --git a/.env.example b/.env.example index eedc104..9b77206 100644 --- a/.env.example +++ b/.env.example @@ -107,6 +107,8 @@ AUTH_ENABLED=false AUTH_REQUIRED_BY_DEFAULT=false # CRITICAL FOR PRODUCTION: Generate with python3 -c "import secrets; print(secrets.token_urlsafe(32))" +# The placeholder below is rejected when ENVIRONMENT=production - see +# core/config.py:INSECURE_JWT_SECRET_KEYS. Replace it before deploying. JWT_SECRET_KEY=your_secure_random_32_byte_jwt_secret_key ACCESS_TOKEN_EXPIRE_MINUTES=15 REFRESH_TOKEN_EXPIRE_DAYS=7 diff --git a/core/config.py b/core/config.py index 44657da..9185d52 100644 --- a/core/config.py +++ b/core/config.py @@ -101,6 +101,19 @@ def _env_list(name: str, default: Optional[List[str]] = None) -> List[str]: # could have tokens minted against it by anyone who has read this file. DEV_JWT_SECRET_KEY = "dev-secret-key-change-in-production" +# Every signing key that is published in this repository. The startup check +# must reject all of them in production, not just the development default: +# `.env.example` is the value most deployments actually start from, and it +# was previously accepted because the check compared against one constant. +INSECURE_JWT_SECRET_KEYS = frozenset({ + DEV_JWT_SECRET_KEY, + "your_secure_random_32_byte_jwt_secret_key", + # Published in tests/test_live_interview_api.py. It is long enough to + # pass a naive entropy/length check, but it is still repository-known + # and therefore just as forgeable as the development default. + "test-jwt-secret-that-is-at-least-thirty-two-bytes-long", +}) + class AppSettings(BaseModel): """Validated, immutable service configuration. @@ -285,12 +298,35 @@ def model_post_init(self, __context) -> None: raise ValueError("DEBUG=true is not permitted when ENVIRONMENT=production.") # ------------------------------------------------------------------ + @property + def jwt_secret_is_blank(self) -> bool: + """Whether no JWT signing key has been configured at all.""" + return not self.jwt_secret_key.strip() + + @property + def jwt_secret_is_placeholder(self) -> bool: + """Whether the configured key is a published placeholder. + + This is deliberately distinct from a blank secret: operators should + not be told they are using a placeholder when they simply forgot to + configure a key. + """ + return ( + not self.jwt_secret_is_blank + and self.jwt_secret_key.strip() in INSECURE_JWT_SECRET_KEYS + ) + @property def jwt_secret_is_default(self) -> bool: - """Whether JWT tokens are being signed with the public placeholder - rather than a real secret. Checked at startup - see - core/lifespan.py:validate_startup_configuration.""" - return self.jwt_secret_key == DEV_JWT_SECRET_KEY + """Whether JWT tokens are being signed with a public placeholder or + no secret at all. Checked at startup - see + core/lifespan.py:validate_startup_configuration. + + A blank value is just as forgeable as a published one, and + `.env.example` ships a different placeholder from + `DEV_JWT_SECRET_KEY`, so both are treated as insecure. + """ + return self.jwt_secret_is_blank or self.jwt_secret_is_placeholder @property def is_production(self) -> bool: diff --git a/core/lifespan.py b/core/lifespan.py index 5c7371b..63ef7f4 100644 --- a/core/lifespan.py +++ b/core/lifespan.py @@ -169,11 +169,22 @@ def validate_startup_configuration( # public, anyone at all) can mint a valid access token for any account, # including an admin's. Production must refuse to start on it. if settings.is_production and settings.jwt_secret_is_default: + if settings.jwt_secret_is_blank: + problem = ( + "ENVIRONMENT=production with an empty JWT_SECRET_KEY - tokens " + "would be signed with an empty key, so anyone could forge a " + "session for any account. " + ) + else: + problem = ( + "ENVIRONMENT=production with a placeholder JWT_SECRET_KEY - " + "tokens would be signed with a key published in this " + "repository's source, so anyone could forge a session for any " + "account. " + ) problems.append( - "ENVIRONMENT=production with the default JWT_SECRET_KEY - tokens " - "would be signed with a placeholder published in this " - "repository's source, so anyone could forge a session for any " - "account. Set JWT_SECRET_KEY to a real secret, e.g. " + problem + + "Set JWT_SECRET_KEY to a real secret, e.g. " "python3 -c \"import secrets; print(secrets.token_urlsafe(32))\"." ) diff --git a/pages/admin.html b/pages/admin.html index ff24e45..51e3350 100644 --- a/pages/admin.html +++ b/pages/admin.html @@ -480,9 +480,12 @@

System status

s.database.connected ? 'Database: connected' : 'Database: unreachable', s.database.connected, )); + const jwtSecretLabel = s.jwt_secret_is_blank + ? 'JWT secret: NOT CONFIGURED' + : (s.jwt_secret_is_placeholder ? 'JWT secret: PLACEHOLDER' : 'JWT secret: configured'); flags.appendChild(statusChip( - s.jwt_secret_is_placeholder ? 'JWT secret: PLACEHOLDER' : 'JWT secret: configured', - !s.jwt_secret_is_placeholder, + jwtSecretLabel, + !s.jwt_secret_is_blank && !s.jwt_secret_is_placeholder, )); flags.appendChild(statusChip( s.auth_enabled ? 'Auth: enabled' : 'Auth: disabled', diff --git a/schemas/admin.py b/schemas/admin.py index 67271e3..d0f05f5 100644 --- a/schemas/admin.py +++ b/schemas/admin.py @@ -120,6 +120,7 @@ class SystemStatusResponse(BaseModel): persistence: str auth_enabled: bool jwt_secret_is_placeholder: bool + jwt_secret_is_blank: bool providers: ProviderStatus database: DatabaseStatus evaluation_queue: EvaluationQueueStatus diff --git a/services/admin_service.py b/services/admin_service.py index 13accd7..fc138b1 100644 --- a/services/admin_service.py +++ b/services/admin_service.py @@ -314,7 +314,8 @@ async def get_system_status(self) -> dict: "environment": settings.environment, "persistence": "postgres" if self._database_pool is not None else "memory", "auth_enabled": settings.auth_enabled, - "jwt_secret_is_placeholder": settings.jwt_secret_is_default, + "jwt_secret_is_placeholder": settings.jwt_secret_is_placeholder, + "jwt_secret_is_blank": settings.jwt_secret_is_blank, "providers": { "llm": settings.llm_provider, "embedding": settings.embedding_provider, diff --git a/tests/test_backend_admin.py b/tests/test_backend_admin.py index c44138c..4c95cb9 100644 --- a/tests/test_backend_admin.py +++ b/tests/test_backend_admin.py @@ -894,13 +894,43 @@ async def test_unreachable_database_reports_disconnected_not_raise(self): @pytest.mark.asyncio async def test_reports_jwt_secret_placeholder_flag(self): placeholder_settings = AppSettings() + blank_settings = AppSettings(jwt_secret_key="") real_settings = AppSettings(jwt_secret_key="a-real-generated-secret") placeholder_status = await _system_status_service(settings=placeholder_settings).get_system_status() + blank_status = await _system_status_service(settings=blank_settings).get_system_status() real_status = await _system_status_service(settings=real_settings).get_system_status() assert placeholder_status["jwt_secret_is_placeholder"] is True + assert placeholder_status["jwt_secret_is_blank"] is False + assert blank_status["jwt_secret_is_placeholder"] is False + assert blank_status["jwt_secret_is_blank"] is True assert real_status["jwt_secret_is_placeholder"] is False + assert real_status["jwt_secret_is_blank"] is False + + @pytest.mark.asyncio + async def test_system_status_response_schema_keeps_jwt_secret_flags(self): + """GET /admin/system/status validates the service dict through + SystemStatusResponse (api/routes/admin.py) - pydantic silently drops + undeclared fields, so any flag the admin console reads + (pages/admin.html) must be declared on the schema too. A missing + jwt_secret_is_blank declaration would render a blank secret as + 'configured'.""" + from schemas.admin import SystemStatusResponse + + for name, settings in ( + ("development default", AppSettings()), + ("blank", AppSettings(jwt_secret_key="")), + ( + ".env.example placeholder", + AppSettings(jwt_secret_key="your_secure_random_32_byte_jwt_secret_key"), + ), + ("real", AppSettings(jwt_secret_key="a-real-generated-secret")), + ): + status = await _system_status_service(settings=settings).get_system_status() + rendered = SystemStatusResponse.model_validate(status) + assert rendered.jwt_secret_is_placeholder is status["jwt_secret_is_placeholder"], name + assert rendered.jwt_secret_is_blank is status["jwt_secret_is_blank"], name @pytest.mark.asyncio async def test_reports_evaluation_queue_running_count(self): diff --git a/tests/test_backend_foundation.py b/tests/test_backend_foundation.py index 5db6b95..7d88b0a 100644 --- a/tests/test_backend_foundation.py +++ b/tests/test_backend_foundation.py @@ -239,6 +239,46 @@ def test_production_with_the_default_jwt_secret_refuses_to_start(self): ) assert "JWT_SECRET_KEY" in exc.value.internal_detail + @pytest.mark.parametrize( + "secret", + [ + "your_secure_random_32_byte_jwt_secret_key", + "test-jwt-secret-that-is-at-least-thirty-two-bytes-long", + " ", + "", + ], + ) + def test_production_rejects_public_or_blank_jwt_secrets(self, secret): + """The .env.example placeholder, the test fixture and a blank value + are all public knowledge; none may be used to sign production + tokens.""" + settings = AppSettings(environment="production", jwt_secret_key=secret) + with pytest.raises(ConfigurationError) as exc: + validate_startup_configuration( + settings, self._container(settings, persistence_is_ephemeral=False) + ) + assert "JWT_SECRET_KEY" in exc.value.internal_detail + + def test_blank_and_placeholder_secrets_are_distinguished(self): + blank = AppSettings(jwt_secret_key="") + placeholder = AppSettings() + + assert blank.jwt_secret_is_blank is True + assert blank.jwt_secret_is_placeholder is False + assert blank.jwt_secret_is_default is True + + assert placeholder.jwt_secret_is_blank is False + assert placeholder.jwt_secret_is_placeholder is True + assert placeholder.jwt_secret_is_default is True + + def test_blank_secret_startup_error_says_it_is_empty(self): + settings = AppSettings(environment="production", jwt_secret_key="") + with pytest.raises(ConfigurationError) as exc: + validate_startup_configuration( + settings, self._container(settings, persistence_is_ephemeral=False) + ) + assert "empty JWT_SECRET_KEY" in exc.value.internal_detail + def test_production_with_a_real_jwt_secret_is_allowed(self): settings = AppSettings( environment="production", jwt_secret_key="a-real-secret-from-the-environment"